Example usage for javax.transaction Status STATUS_PREPARED

List of usage examples for javax.transaction Status STATUS_PREPARED

Introduction

In this page you can find the example usage for javax.transaction Status STATUS_PREPARED.

Prototype

int STATUS_PREPARED

To view the source code for javax.transaction Status STATUS_PREPARED.

Click Source Link

Document

A transaction is associated with the target object and it has been prepared.

Usage

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

private void recoverParticipant(Transaction transaction)
        throws CommitRequiredException, RollbackRequiredException, SystemException {

    TransactionImpl transactionImpl = (TransactionImpl) transaction;
    switch (transaction.getTransactionStatus()) {
    case Status.STATUS_PREPARED:
    case Status.STATUS_COMMITTING:
        break;//from   w  w w  .  j  a v a 2 s .c  o m
    case Status.STATUS_COMMITTED:
    case Status.STATUS_ROLLEDBACK:
        break;
    case Status.STATUS_ACTIVE:
    case Status.STATUS_MARKED_ROLLBACK:
    case Status.STATUS_PREPARING:
    case Status.STATUS_UNKNOWN:
    case Status.STATUS_ROLLING_BACK:
    default:
        transactionImpl.recoveryRollback();
        transactionImpl.forgetQuietly();
    }
}

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
            }//from www.ja v a 2s. 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.TransactionRecoveryImpl.java

public synchronized void recoverCoordinator(Transaction transaction)
        throws CommitRequiredException, RollbackRequiredException, SystemException {

    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.recoveryRollback();/*from  w  w  w . j a  v  a 2 s  . c om*/
        transaction.recoveryForget();
        break;
    case Status.STATUS_PREPARED:
    case Status.STATUS_COMMITTING:
        transaction.recoveryCommit();
        transaction.recoveryForget();
        break;
    case Status.STATUS_COMMITTED:
    case Status.STATUS_ROLLEDBACK:
    default:
        // ignore
    }

}

From source file:org.castor.persist.AbstractTransactionContext.java

/**
 * {@inheritDoc}/*from  w ww.  j  ava2 s. c  o  m*/
 * @see org.castor.persist.TransactionContext#prepare()
 */
public final synchronized boolean prepare() throws TransactionAbortedException {
    ArrayList<Object> todo = new ArrayList<Object>();
    ArrayList<Object> done = new ArrayList<Object>();

    if (_status == Status.STATUS_MARKED_ROLLBACK) {
        throw new TransactionAbortedException("persist.markedRollback");
    }
    if (_status != Status.STATUS_ACTIVE) {
        throw new IllegalStateException(Messages.message("persist.noTransaction"));
    }

    try {
        // No objects in this transaction -- this is a read only transaction
        // Put it into the try block to close connections
        if (_tracker.readWriteSize() == 0) {
            _status = Status.STATUS_PREPARED;
            return false;
        }

        Collection readWriteObjects = _tracker.getReadWriteObjects();
        while (readWriteObjects.size() != done.size()) {
            todo.clear();
            Iterator rwIterator = readWriteObjects.iterator();
            while (rwIterator.hasNext()) {
                Object object = rwIterator.next();
                if (!done.contains(object)) {
                    todo.add(object);
                }
            }

            Iterator<Object> todoIterator = todo.iterator();
            while (todoIterator.hasNext()) {
                Object object = todoIterator.next();
                // Anything not marked 'deleted' or 'creating' is ready to
                // consider for store.
                if ((!_tracker.isDeleted(object)) && (!_tracker.isCreating(object))) {
                    LockEngine engine = _tracker.getMolderForObject(object).getLockEngine();
                    //_tracker.getMolderForObject(object);
                    OID oid = _tracker.getOIDForObject(object);

                    OID newoid = engine.preStore(this, oid, object, _lockTimeout);
                    if (newoid != null) {
                        _tracker.trackOIDChange(object, engine, oid, newoid);
                        _tracker.markUpdateCacheNeeded(object);
                    }
                }
                done.add(object);
            }
        }

        // preStore will actually walk all existing object and it might
        // marked
        // some object to be created (and to be removed).
        walkObjectsToBeCreated();

        // Now mark anything ready for create to create them.
        prepareForCreate();

        _status = Status.STATUS_PREPARING;
        prepareForDelete();
        _status = Status.STATUS_PREPARED;

        return true;
    } catch (Exception except) {
        _status = Status.STATUS_MARKED_ROLLBACK;
        if (except instanceof TransactionAbortedException) {
            throw (TransactionAbortedException) except;
        }
        // Any error is reported as transaction aborted
        throw new TransactionAbortedException(Messages.format("persist.nested", except), except);
    }
}

From source file:org.castor.persist.AbstractTransactionContext.java

/**
 * {@inheritDoc}/*  w  ww  . j av  a2  s .c  om*/
 * @see org.castor.persist.TransactionContext#commit()
 */
public final synchronized void commit() throws TransactionAbortedException {
    // Never commit transaction that has been marked for rollback
    if (_status == Status.STATUS_MARKED_ROLLBACK) {
        throw new TransactionAbortedException("persist.markedRollback");
    }
    if (_status != Status.STATUS_PREPARED) {
        throw new IllegalStateException(Messages.message("persist.missingPrepare"));
    }

    try {
        _status = Status.STATUS_COMMITTING;

        // Go through all the connections opened in this transaction,
        // commit and close them one by one.
        commitConnections();
    } catch (Exception except) {
        // Any error that happens, we're going to rollback the transaction.
        _status = Status.STATUS_MARKED_ROLLBACK;
        throw new TransactionAbortedException(Messages.format("persist.nested", except), except);
    }

    // Assuming all went well in the connection department,
    // no deadlocks, etc. clean all the transaction locks with
    // regards to the persistence engine.
    Collection readWriteObjects = _tracker.getReadWriteObjects();
    Iterator it = readWriteObjects.iterator();
    while (it.hasNext()) {
        Object toCommit = it.next();

        ClassMolder molder = _tracker.getMolderForObject(toCommit);
        LockEngine engine = molder.getLockEngine();
        OID oid = _tracker.getOIDForObject(toCommit);

        if (_tracker.isDeleted(toCommit)) {
            // Object has been deleted inside transaction,
            // engine must forget about it.
            engine.forgetObject(this, oid);
        } else {
            // Object has been created/accessed inside the
            // transaction, release its lock.
            if (_tracker.isUpdateCacheNeeded(toCommit)) {
                engine.updateCache(this, oid, toCommit);
            }

            engine.releaseLock(this, oid);
        }

        // Call our release callback on all processed objects.
        if (_callback != null) {
            _callback.releasing(toCommit, true);
        } else if (molder.getCallback() != null) {
            molder.getCallback().releasing(toCommit, true);
        }
    }

    // Call txcommited() before objects are removed to allow
    // TxSynchronizable to iterate through the objects.
    txcommitted();

    // Forget about all the objects in this transaction,
    // and mark it as completed.
    _tracker.clear();
    _status = Status.STATUS_COMMITTED;
}

From source file:org.castor.persist.AbstractTransactionContext.java

/**
 * {@inheritDoc}/*  w  w w  .  j  a v a  2 s  . c  o m*/
 * @see org.castor.persist.TransactionContext#rollback()
 */
public final synchronized void rollback() {
    if (_status != Status.STATUS_ACTIVE && _status != Status.STATUS_PREPARED
            && _status != Status.STATUS_MARKED_ROLLBACK) {
        throw new IllegalStateException(Messages.message("persist.noTransaction"));
    }

    // Go through all the connections opened in this transaction,
    // rollback and close them one by one.
    rollbackConnections();

    // un-delete object first
    _tracker.unmarkAllDeleted();

    // Clean the transaction locks with regards to the database engine.
    Collection readWriteObjects = _tracker.getReadWriteObjects();
    OID oid = null;
    try {
        Iterator it = readWriteObjects.iterator();
        // First revert all objects
        while (it.hasNext()) {
            Object object = it.next();
            LockEngine engine = _tracker.getMolderForObject(object).getLockEngine();
            oid = _tracker.getOIDForObject(object);
            if (!_tracker.isCreating(object)) {
                engine.revertObject(this, oid, object);
            }
        }

        // then forget object or release lock on them
        it = readWriteObjects.iterator();
        while (it.hasNext()) {
            Object object = it.next();
            ClassMolder molder = _tracker.getMolderForObject(object);
            LockEngine engine = molder.getLockEngine();
            oid = _tracker.getOIDForObject(object);

            if (!_tracker.isCreating(object)) {
                if (_tracker.isCreated(object)) {
                    // Object has been created in this transaction,
                    // it no longer exists, forget about it in the engine.
                    engine.forgetObject(this, oid);
                } else {
                    // Object has been queried (possibly) deleted in this
                    // transaction and release the lock.
                    engine.releaseLock(this, oid);
                }
            }

            if (_callback != null) {
                _callback.releasing(object, false);
            } else if (molder.getCallback() != null) {
                molder.getCallback().releasing(object, false);
            }
        }
    } catch (Exception except) {
        // Don't thow exceptions during a rollback. Just report them.
        LOG.error("Caught exception at rollback of object with OID " + oid, except);
    }

    // Forget about all the objects in this transaction,
    // and mark it as completed.
    _tracker.clear();
    txrolledback();
    _status = Status.STATUS_ROLLEDBACK;
}

From source file:org.commonjava.maven.galley.cache.infinispan.FastLocalCacheProvider.java

private boolean isTxActive(CacheInstance<String, String> cacheInstance) throws SystemException {
    final int[] ACTIVE_STATUS = new int[] { Status.STATUS_ACTIVE, Status.STATUS_COMMITTING,
            Status.STATUS_PREPARING, Status.STATUS_PREPARED, Status.STATUS_ROLLING_BACK };
    boolean isActive = false;
    for (int status : ACTIVE_STATUS) {
        if (cacheInstance.getTransactionStatus() == status) {
            isActive = true;/*from   ww w  .jav  a2 s .c  om*/
            break;
        }
    }
    return isActive;
}

From source file:org.enhydra.jdbc.standard.StandardXADataSource.java

/**
 * Returns the number of connections that are either
 * prepared or heuristically completed.//  w ww.j a v a  2s. co  m
 */
public int getXidCount() {
    int count = 0; // the return value
    Enumeration cons = xidConnections.elements();
    // used to iterate through the used connections
    while (cons.hasMoreElements()) { // while there are more connections
        Object o = cons.nextElement(); // get the next connection
        StandardXAStatefulConnection cur = (StandardXAStatefulConnection) o;
        // cast to something more convenient
        if ((cur.getState() == Status.STATUS_PREPARED) || // if prepared
                (cur.getState() == Status.STATUS_PREPARING)) {
            // ...or heuristically committed
            count++; // one more connection with a valid xid
        }
    }
    log.debug("StandardXADataSource:getXidCount return XidCount=<" + count + ">");
    return count;
}

From source file:org.enhydra.jdbc.standard.StandardXADataSource.java

/**
 * Constructs a list of all prepared connections' xids.
 *//* www  . ja va 2  s. c o m*/
Xid[] recover() {
    int nodeCount = getXidCount();
    // get number of connections in transactions
    Xid[] xids = new Xid[nodeCount]; // create the return array
    int i = 0; // used as xids index
    Enumeration cons = xidConnections.elements();
    // used to iterate through the used connections
    while (cons.hasMoreElements()) { // while there are more connections
        Object o = cons.nextElement(); // get the next connection
        StandardXAStatefulConnection cur = (StandardXAStatefulConnection) o;
        // cast to something more convenient
        if ((cur.getState() == Status.STATUS_PREPARED) || // if prepared
                (cur.getState() == Status.STATUS_PREPARING)) {
            // ...or heuristically committed
            xids[i++] = cur.xid; // save in list
        }
    }
    return xids;
}

From source file:org.etk.entity.engine.plugins.transaction.TransactionUtil.java

public static String getTransactionStateString(int state) {
    /*//w  ww . j ava  2 s  .c  o m
     * javax.transaction.Status STATUS_ACTIVE 0 STATUS_MARKED_ROLLBACK 1
     * STATUS_PREPARED 2 STATUS_COMMITTED 3 STATUS_ROLLEDBACK 4 STATUS_UNKNOWN 5
     * STATUS_NO_TRANSACTION 6 STATUS_PREPARING 7 STATUS_COMMITTING 8
     * STATUS_ROLLING_BACK 9
     */
    switch (state) {
    case Status.STATUS_ACTIVE:
        return "Transaction Active (" + state + ")";
    case Status.STATUS_COMMITTED:
        return "Transaction Committed (" + state + ")";
    case Status.STATUS_COMMITTING:
        return "Transaction Committing (" + state + ")";
    case Status.STATUS_MARKED_ROLLBACK:
        return "Transaction Marked Rollback (" + state + ")";
    case Status.STATUS_NO_TRANSACTION:
        return "No Transaction (" + state + ")";
    case Status.STATUS_PREPARED:
        return "Transaction Prepared (" + state + ")";
    case Status.STATUS_PREPARING:
        return "Transaction Preparing (" + state + ")";
    case Status.STATUS_ROLLEDBACK:
        return "Transaction Rolledback (" + state + ")";
    case Status.STATUS_ROLLING_BACK:
        return "Transaction Rolling Back (" + state + ")";
    case Status.STATUS_UNKNOWN:
        return "Transaction Status Unknown (" + state + ")";
    default:
        return "Not a valid state code (" + state + ")";
    }
}