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:com.taobao.metamorphosis.transaction.XATransactionId.java

public XATransactionId(final Xid xid, final String uniqueQualifier) {
    this.formatId = xid.getFormatId();
    this.globalTransactionId = xid.getGlobalTransactionId();
    this.branchQualifier = xid.getBranchQualifier();
    this.uniqueQualifier = uniqueQualifier;
    if (StringUtils.isBlank(uniqueQualifier)) {
        throw new IllegalArgumentException("Blank uniqueQualifier");
    }//  w w  w  .  j a  va 2 s .c  om
}

From source file:com.alibaba.napoli.metamorphosis.client.transaction.TransactionContext.java

private boolean equals(final Xid xid1, final Xid xid2) {
    if (xid1 == xid2) {
        return true;
    }/*from w  ww  . j av  a  2s .com*/
    if (xid1 == null || xid2 == null) {
        return false;
    }
    return xid1.getFormatId() == xid2.getFormatId()
            && Arrays.equals(xid1.getBranchQualifier(), xid2.getBranchQualifier())
            && Arrays.equals(xid1.getGlobalTransactionId(), xid2.getGlobalTransactionId());
}

From source file:org.bytesoft.bytejta.logging.SampleTransactionLogger.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.getXidFactory();

    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);/*  w  ww  .  ja  v a 2s  .  c  om*/
            } 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> nativeResources = archive.getNativeResources();
                for (int i = 0; matched == false && nativeResources != null
                        && i < nativeResources.size(); i++) {
                    XAResourceArchive element = nativeResources.get(i);
                    if (resourceArchive.getXid().equals(element.getXid())) {
                        matched = true;
                        nativeResources.set(i, resourceArchive);
                    }
                }

                XAResourceArchive optimizedResource = archive.getOptimizedResource();
                if (matched == false && optimizedResource != null) {
                    if (resourceArchive.getXid().equals(optimizedResource.getXid())) {
                        matched = true;
                        archive.setOptimizedResource(resourceArchive);
                    }
                }

                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) {
                    logger.error("Error occurred while recovering resource archive: {}, invalid resoure!", obj);
                }

            }

        }
    });

    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.bytejta.supports.dubbo.spi.TransactionServiceFilter.java

public Result providerInvokeForJTA(Invoker<?> invoker, Invocation invocation) throws RpcException {
    TransactionBeanRegistry beanRegistry = TransactionBeanRegistry.getInstance();
    TransactionBeanFactory beanFactory = beanRegistry.getBeanFactory();
    XidFactory xidFactory = beanFactory.getXidFactory();
    TransactionRepository transactionRepository = beanFactory.getTransactionRepository();
    RemoteCoordinator transactionCoordinator = beanFactory.getTransactionCoordinator();

    Class<?>[] parameterTypeArray = invocation.getParameterTypes();
    Class<?> parameterType = (parameterTypeArray == null || parameterTypeArray.length == 0) ? null
            : parameterTypeArray[0];//from  w  ww .j  a va  2s  . com
    if (parameterTypeArray == null || parameterTypeArray.length == 0) {
        return this.wrapResultForProvider(invoker, invocation, false);
    } else if (Xid.class.equals(parameterType) == false) {
        return this.wrapResultForProvider(invoker, invocation, false);
    }

    RpcResult result = new RpcResult();

    Object[] arguments = invocation.getArguments();
    Xid xid = (Xid) arguments[0];

    TransactionXid globalXid = xidFactory.createGlobalXid(xid.getGlobalTransactionId());
    Transaction transaction = transactionRepository.getTransaction(globalXid);
    if (transaction == null) {
        InvocationResult wrapped = new InvocationResult();
        wrapped.setError(new XAException(XAException.XAER_NOTA));
        wrapped.setVariable(TransactionCoordinator.class.getName(), transactionCoordinator.getIdentifier());

        result.setException(null);
        result.setValue(wrapped);
    } else {
        TransactionContext transactionContext = transaction.getTransactionContext();
        String propagatedBy = String.valueOf(transactionContext.getPropagatedBy());

        String remoteAddr = invocation.getAttachment(TransactionCoordinator.class.getName());

        if (StringUtils.equals(propagatedBy, remoteAddr)) {
            return this.wrapResultForProvider(invoker, invocation, false);
        }

        InvocationResult wrapped = new InvocationResult();
        wrapped.setError(new XAException(XAException.XAER_PROTO));
        wrapped.setVariable(TransactionCoordinator.class.getName(), transactionCoordinator.getIdentifier());

        result.setException(null);
        result.setValue(wrapped);

        logger.warn("{}| branch should be invoked by its own coordinator.", globalXid);
    }

    return result;
}

From source file:org.bytesoft.bytejta.supports.jdbc.RecoveredResource.java

public void recoverable(Xid xid) throws XAException {
    byte[] globalTransactionId = xid.getGlobalTransactionId();
    byte[] branchQualifier = xid.getBranchQualifier();

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

    Connection conn = null;//from w ww .j a  va 2  s. com
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
        conn = this.dataSource.getConnection();
        stmt = conn.prepareStatement("select gxid, bxid from bytejta where xid = ?");
        stmt.setString(1, identifier);
        rs = stmt.executeQuery();
        if (rs.next() == false) {
            throw new XAException(XAException.XAER_NOTA);
        }
    } catch (SQLException ex) {
        try {
            this.isTableExists(conn);
        } catch (SQLException sqlEx) {
            logger.warn("Error occurred while recovering local-xa-resource.", ex);
            throw new XAException(XAException.XAER_RMFAIL);
        } catch (RuntimeException rex) {
            logger.warn("Error occurred while recovering local-xa-resource.", ex);
            throw new XAException(XAException.XAER_RMFAIL);
        }

        throw new XAException(XAException.XAER_RMERR);
    } catch (RuntimeException ex) {
        logger.warn("Error occurred while recovering local-xa-resource.", ex);
        throw new XAException(XAException.XAER_RMERR);
    } finally {
        this.closeQuietly(rs);
        this.closeQuietly(stmt);
        this.closeQuietly(conn);
    }
}

From source file:org.bytesoft.bytejta.supports.jdbc.RecoveredResource.java

public synchronized void forget(Xid[] xids) throws XAException {
    if (xids == null || xids.length == 0) {
        return;/*from w w  w  . j  a  v  a 2s.c o m*/
    }

    String[] xidArray = new String[xids.length];

    for (int i = 0; i < xids.length; i++) {
        Xid xid = xids[i];

        byte[] globalTransactionId = xid.getGlobalTransactionId();
        byte[] branchQualifier = xid.getBranchQualifier();
        xidArray[i] = this.getIdentifier(globalTransactionId, branchQualifier);
    }

    Connection conn = null;
    PreparedStatement stmt = null;
    Boolean autoCommit = null;
    try {
        conn = this.dataSource.getConnection();
        autoCommit = conn.getAutoCommit();
        conn.setAutoCommit(false);
        stmt = conn.prepareStatement("delete from bytejta where xid = ?");
        for (int i = 0; i < xids.length; i++) {
            stmt.setString(1, xidArray[i]);
            stmt.addBatch();
        }
        stmt.executeBatch();
        conn.commit();
    } catch (Exception ex) {
        logger.error("Error occurred while forgetting resources.");

        try {
            conn.rollback();
        } catch (Exception sqlEx) {
            logger.error("Error occurred while rolling back local resources.", sqlEx);
        }

        boolean tableExists = false;
        try {
            tableExists = this.isTableExists(conn);
        } catch (Exception sqlEx) {
            logger.warn("Error occurred while forgeting local resources.", ex);
            throw new XAException(XAException.XAER_RMFAIL);
        }

        if (tableExists) {
            throw new XAException(XAException.XAER_RMERR);
        }
    } finally {
        if (autoCommit != null) {
            try {
                conn.setAutoCommit(autoCommit);
            } catch (SQLException sqlEx) {
                logger.error("Error occurred while configuring attribute 'autoCommit'.", sqlEx);
            }
        }

        this.closeQuietly(stmt);
        this.closeQuietly(conn);
    }
}

From source file:org.bytesoft.bytejta.supports.jdbc.RecoveredResource.java

public synchronized void forget(Xid xid) throws XAException {
    if (xid == null) {
        logger.warn("Error occurred while forgeting local-xa-resource: invalid xid.");
        return;/*from w ww. j  a v a 2s .  com*/
    }

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

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

    Connection conn = null;
    PreparedStatement stmt = null;
    try {
        conn = this.dataSource.getConnection();
        stmt = conn.prepareStatement("delete from bytejta where xid = ?");
        stmt.setString(1, identifier);
        stmt.executeUpdate();
    } catch (Exception ex) {
        boolean tableExists = false;
        try {
            tableExists = this.isTableExists(conn);
        } catch (Exception sqlEx) {
            logger.warn("Error occurred while forgeting local-xa-resource.", ex);
            throw new XAException(XAException.XAER_RMFAIL);
        }

        if (tableExists) {
            throw new XAException(XAException.XAER_RMERR);
        }
    } finally {
        this.closeQuietly(stmt);
        this.closeQuietly(conn);
    }
}

From source file:org.bytesoft.bytejta.supports.springcloud.SpringCloudCoordinator.java

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 {//from w  ww . j  a va 2s  .  co  m
        byte[] byteArray = CommonUtils.serializeObject(arg);
        return ByteUtils.byteArrayToString(byteArray);
    }
}

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

private synchronized void fireNativeParticipantRecoveryCancelForRecoveredTransaction() throws SystemException {
    boolean errorExists = false;

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

    boolean previouCancelled = false;
    for (int i = this.archiveList.size() - 1; i >= 0; i--) {
        CompensableArchive current = this.archiveList.get(i);
        boolean currentCancelled = current.isCancelled();

        if (currentCancelled) {
            continue;
        }//  w  w  w . j a v a  2s  . co m

        if (current.isTried() == false) /* this.transactionContext.isCoordinator() == false && */ {
            String identifier = current.getTransactionResourceKey();
            if (StringUtils.isBlank(identifier)) {
                logger.warn(
                        "There is no valid resource participated in the trying branch transaction, the status of the branch transaction is unknown!");
            } else {
                XAResource xares = resourceDeserializer.deserialize(identifier);
                if (RecoveredResource.class.isInstance(xares)) {
                    RecoveredResource resource = (RecoveredResource) xares;
                    try {
                        resource.recoverable(current.getTransactionXid());
                        current.setTried(true);
                        compensableLogger.updateCompensable(current);
                    } catch (XAException xaex) {
                        switch (xaex.errorCode) {
                        case XAException.XAER_NOTA:
                            current.setTried(false);
                            continue;
                        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:
                            errorExists = true;

                            Xid xid = current.getTransactionXid();
                            logger.error("Error occurred while recovering the branch transaction service: {}",
                                    ByteUtils.byteArrayToString(xid.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!");
                }
            }
        }

        TransactionXid compensableXid = (TransactionXid) current.getCompensableXid();
        try {
            this.positive = false;
            this.archive = current;

            String identifier = current.getCompensableResourceKey();
            if (StringUtils.isBlank(identifier)) {
                if (previouCancelled) {
                    logger.warn(
                            "There is no valid resource participated in the current branch transaction, the status of the current branch transaction is unknown!");
                } else {
                    logger.debug("There is no valid resource participated in the current branch transaction!");
                }
            } else {
                XAResource xares = resourceDeserializer.deserialize(identifier);
                if (RecoveredResource.class.isInstance(xares)) {
                    RecoveredResource resource = (RecoveredResource) xares;
                    try {
                        resource.recoverable(compensableXid);
                        current.setCancelled(true);
                        compensableLogger.updateCompensable(current);
                        continue;
                    } catch (XAException xaex) {
                        switch (xaex.errorCode) {
                        case XAException.XAER_NOTA:
                            break;
                        case XAException.XAER_RMERR:
                            logger.warn(
                                    "The database table 'bytejta' cannot found, the status of the current branch transaction is unknown!");
                            break;
                        case XAException.XAER_RMFAIL:
                            errorExists = true;
                            logger.error(
                                    "{}| error occurred while recovering the branch transaction service: {}",
                                    ByteUtils.byteArrayToString(
                                            this.transactionContext.getXid().getGlobalTransactionId()),
                                    ByteUtils.byteArrayToString(
                                            current.getIdentifier().getGlobalTransactionId()),
                                    xaex);
                            break;
                        default:
                            logger.error(
                                    "Illegal state, the status of the current branch transaction is unknown!");
                        }
                    }
                } else {
                    logger.error("Illegal resources, the status of the current branch transaction is unknown!");
                }
            }

            CompensableInvocation invocation = current.getCompensable();
            if (current.isTried() == false) {
                logger.info(
                        "{}| the operation in try phase is rolled back, so the cancel operation is ignored, compensable service: {}.",
                        ByteUtils.byteArrayToString(transactionContext.getXid().getGlobalTransactionId()),
                        ByteUtils.byteArrayToString(current.getIdentifier().getGlobalTransactionId()));
            } else if (invocation == null) {
                errorExists = true;
                logger.error(
                        "{}| error occurred while cancelling service: {}, please check whether the params of method(compensable-service) supports serialization.",
                        ByteUtils.byteArrayToString(this.transactionContext.getXid().getGlobalTransactionId()),
                        ByteUtils.byteArrayToString(current.getIdentifier().getGlobalTransactionId()));
            } else if (StringUtils.isNotBlank(invocation.getCancellableKey())) {
                container.cancel(invocation);
            } else {
                this.archive.setCancelled(true);
                logger.info("{}| cancel: identifier= {}, resourceKey= {}, resourceXid= {}.",
                        ByteUtils.byteArrayToString(this.transactionContext.getXid().getGlobalTransactionId()),
                        ByteUtils.byteArrayToString(current.getIdentifier().getGlobalTransactionId()),
                        current.getCompensableResourceKey(), current.getCompensableXid());
            }
        } catch (RuntimeException rex) {
            errorExists = true;
            logger.error("{}| error occurred while cancelling service: {}",
                    ByteUtils.byteArrayToString(this.transactionContext.getXid().getGlobalTransactionId()),
                    this.archive, rex);
        } finally {
            this.archive = null;
            this.positive = null;

            previouCancelled = currentCancelled;
        }
    }

    if (errorExists) {
        throw new SystemException();
    }

}

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

public synchronized void recoveryForget() throws SystemException {
    LocalResourceCleaner resourceCleaner = this.beanFactory.getLocalResourceCleaner();

    boolean success = true;
    for (int i = 0; i < this.archiveList.size(); i++) {
        CompensableArchive current = this.archiveList.get(i);

        String transactionResourceKey = current.getTransactionResourceKey();
        String compensableResourceKey = current.getCompensableResourceKey();
        if (StringUtils.isNotBlank(transactionResourceKey)) {
            Xid branchXid = current.getTransactionXid();
            try {
                resourceCleaner.forget(branchXid, transactionResourceKey);
            } catch (RuntimeException rex) {
                success = false;//from w  w  w .  j a  v a 2 s  . co  m
                logger.error("forget-transaction: error occurred while forgetting branch: {}", branchXid, rex);
            }
        }

        if (StringUtils.isNotBlank(compensableResourceKey)) {
            Xid branchXid = current.getCompensableXid();
            try {
                resourceCleaner.forget(branchXid, compensableResourceKey);
            } catch (RuntimeException rex) {
                success = false;
                logger.error("forget-transaction: error occurred while forgetting branch: {}", branchXid, rex);
            }
        }

    }

    for (int i = 0; i < this.resourceList.size(); i++) {
        XAResourceArchive current = this.resourceList.get(i);

        XidFactory xidFactory = this.beanFactory.getCompensableXidFactory();
        TransactionXid branchXid = (TransactionXid) current.getXid();
        TransactionXid globalXid = xidFactory.createGlobalXid(branchXid.getGlobalTransactionId());
        try {
            current.recoveryForget(globalXid);
        } catch (XAException ex) {
            switch (ex.errorCode) {
            case XAException.XAER_NOTA:
                break;
            default:
                success = false;
                logger.error("forget-transaction: error occurred while forgetting branch: {}", branchXid, ex);
            }
        } catch (RuntimeException rex) {
            success = false;
            logger.error("forget-transaction: error occurred while forgetting branch: {}", branchXid, rex);
        }
    }

    if (success) {
        CompensableLogger compensableLogger = this.beanFactory.getCompensableLogger();
        TransactionRepository compensableRepository = this.beanFactory.getCompensableRepository();

        compensableLogger.deleteTransaction(this.getTransactionArchive());

        compensableRepository.removeErrorTransaction(this.transactionContext.getXid());
        compensableRepository.removeTransaction(this.transactionContext.getXid());

        logger.info("{}| forget transaction.",
                ByteUtils.byteArrayToString(this.transactionContext.getXid().getGlobalTransactionId()));
    } else {
        throw new SystemException();
    }

}