Example usage for javax.transaction Status STATUS_ROLLEDBACK

List of usage examples for javax.transaction Status STATUS_ROLLEDBACK

Introduction

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

Prototype

int STATUS_ROLLEDBACK

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

Click Source Link

Document

A transaction is associated with the target object and the outcome has been determined to be rollback.

Usage

From source file:org.alfresco.repo.search.impl.lucene.AbstractLuceneIndexerImpl.java

/**
 * Commit this index/*  w w w  .  j  av  a  2  s  .  c o m*/
 * 
 * @throws LuceneIndexException
 */
public void commit() throws LuceneIndexException {
    if (s_logger.isDebugEnabled()) {
        s_logger.debug(Thread.currentThread().getName() + " Starting Commit");
    }
    switch (getStatus().getStatus()) {
    case Status.STATUS_COMMITTING:
        throw new LuceneIndexException("Unable to commit: Transaction is committing");
    case Status.STATUS_COMMITTED:
        throw new LuceneIndexException("Unable to commit: Transaction is commited ");
    case Status.STATUS_ROLLING_BACK:
        throw new LuceneIndexException("Unable to commit: Transaction is rolling back");
    case Status.STATUS_ROLLEDBACK:
        throw new LuceneIndexException("Unable to commit: Transaction is aleady rolled back");
    case Status.STATUS_MARKED_ROLLBACK:
        throw new LuceneIndexException("Unable to commit: Transaction is marked for roll back");
    case Status.STATUS_PREPARING:
        throw new LuceneIndexException("Unable to commit: Transaction is preparing");
    case Status.STATUS_ACTIVE:
        // special case - commit from active
        prepare();
        // drop through to do the commit;
    default:
        if (getStatus().getStatus() != Status.STATUS_PREPARED) {
            throw new LuceneIndexException("Index must be prepared to commit");
        }
        try {
            setStatus(TransactionStatus.COMMITTING);
            if (isModified()) {
                doCommit();
            }
            setStatus(TransactionStatus.COMMITTED);
        } catch (LuceneIndexException e) {
            // If anything goes wrong we try and do a roll back
            rollback();
            if (s_logger.isDebugEnabled()) {
                s_logger.debug(Thread.currentThread().getName() + " Commit Failed", e);
            }
            throw new LuceneIndexException("Commit failed", e);
        } catch (Throwable t) {
            // If anything goes wrong we try and do a roll back
            rollback();
            if (s_logger.isDebugEnabled()) {
                s_logger.debug(Thread.currentThread().getName() + " Commit Failed", t);
            }
            throw new LuceneIndexException("Commit failed", t);
        } finally {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug(Thread.currentThread().getName() + " Ending Commit");
            }

            // Make sure we tidy up
            // deleteDelta();
        }
        break;
    }
}

From source file:org.alfresco.repo.search.impl.lucene.AbstractLuceneIndexerImpl.java

/**
 * Prepare to commit At the moment this makes sure we have all the locks TODO: This is not doing proper
 * serialisation against the index as would a data base transaction.
 * /*  ww w  . j  a va  2 s .co m*/
 * @return the tx state
 * @throws LuceneIndexException
 */
public int prepare() throws LuceneIndexException {
    if (s_logger.isDebugEnabled()) {
        s_logger.debug(Thread.currentThread().getName() + " Starting Prepare");
    }
    switch (getStatus().getStatus()) {
    case Status.STATUS_COMMITTING:
        throw new IndexerException("Unable to prepare: Transaction is committing");
    case Status.STATUS_COMMITTED:
        throw new IndexerException("Unable to prepare: Transaction is commited ");
    case Status.STATUS_ROLLING_BACK:
        throw new IndexerException("Unable to prepare: Transaction is rolling back");
    case Status.STATUS_ROLLEDBACK:
        throw new IndexerException("Unable to prepare: Transaction is aleady rolled back");
    case Status.STATUS_MARKED_ROLLBACK:
        throw new IndexerException("Unable to prepare: Transaction is marked for roll back");
    case Status.STATUS_PREPARING:
        throw new IndexerException("Unable to prepare: Transaction is already preparing");
    case Status.STATUS_PREPARED:
        throw new IndexerException("Unable to prepare: Transaction is already prepared");
    default:
        try {
            setStatus(TransactionStatus.PREPARING);
            if (isModified()) {
                doPrepare();
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug(Thread.currentThread().getName() + " Waiting to Finish Preparing");
                }
            }
            setStatus(TransactionStatus.PREPARED);
            return isModified() ? XAResource.XA_OK : XAResource.XA_RDONLY;
        } catch (LuceneIndexException e) {
            setRollbackOnly();
            if (s_logger.isDebugEnabled()) {
                s_logger.debug(Thread.currentThread().getName() + " Prepare Failed", e);
            }
            throw new LuceneIndexException("Index failed to prepare", e);
        } catch (Throwable t) {
            // If anything goes wrong we try and do a roll back
            rollback();
            if (s_logger.isDebugEnabled()) {
                s_logger.debug(Thread.currentThread().getName() + " Prepare Failed", t);
            }
            throw new LuceneIndexException("Prepared failed", t);
        } finally {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug(Thread.currentThread().getName() + " Ending Prepare");
            }
        }
    }
}

From source file:org.alfresco.repo.search.impl.lucene.AbstractLuceneIndexerImpl.java

/**
 * Roll back the index changes (this just means they are never added)
 * /*from   w  ww.  j a v  a  2 s.co  m*/
 * @throws LuceneIndexException
 */
public void rollback() throws LuceneIndexException {
    switch (getStatus().getStatus()) {

    case Status.STATUS_COMMITTED:
        throw new IndexerException("Unable to roll back: Transaction is committed ");
    case Status.STATUS_ROLLING_BACK:
        throw new IndexerException("Unable to roll back: Transaction is rolling back");
    case Status.STATUS_ROLLEDBACK:
        throw new IndexerException("Unable to roll back: Transaction is already rolled back");
    case Status.STATUS_COMMITTING:
        // Can roll back during commit
    default:
        try {
            setStatus(TransactionStatus.ROLLINGBACK);
            doRollBack();
            setStatus(TransactionStatus.ROLLEDBACK);
        } catch (IOException e) {
            throw new LuceneIndexException("rollback failed ", e);
        }
        break;
    }
}

From source file:org.alfresco.repo.transaction.RetryingTransactionHelper.java

/**
 * Execute a callback in a transaction until it succeeds, fails
 * because of an error not the result of an optimistic locking failure,
 * or a deadlock loser failure, or until a maximum number of retries have
 * been attempted.//from   w  w w  .  ja v  a  2  s .com
 * <p>
 * It is possible to force a new transaction to be created or to partake in
 * any existing transaction.
 *
 * @param cb                The callback containing the unit of work.
 * @param readOnly          Whether this is a read only transaction.
 * @param requiresNew       <tt>true</tt> to force a new transaction or
 *                          <tt>false</tt> to partake in any existing transaction.
 * @return                  Returns the result of the unit of work.
 * @throws                  RuntimeException  all checked exceptions are converted
 */
public <R> R doInTransaction(RetryingTransactionCallback<R> cb, boolean readOnly, boolean requiresNew) {
    // First validate the requiresNew setting
    if (!requiresNew) {
        TxnReadState readState = AlfrescoTransactionSupport.getTransactionReadState();
        switch (readState) {
        case TXN_READ_ONLY:
            if (!readOnly) {
                // The current transaction is read-only, but a writable transaction is requested
                throw new AlfrescoRuntimeException(
                        "Read-Write transaction started within read-only transaction");
            }
            // We are in a read-only transaction and this is what we require so continue with it.
            break;
        case TXN_READ_WRITE:
            // We are in a read-write transaction.  It cannot be downgraded so just continue with it.
            break;
        case TXN_NONE:
            // There is no current transaction so we need a new one.
            requiresNew = true;
            break;
        default:
            throw new RuntimeException("Unknown transaction state: " + readState);
        }
    }

    // If we need a new transaction, then we have to check that the read-write request can be served
    if (requiresNew) {
        if (this.readOnly && !readOnly) {
            throw new AccessDeniedException(MSG_READ_ONLY);
        }
    }

    // If we are time limiting, set ourselves a time limit and maintain the count of concurrent transactions
    long startTime = 0;
    Throwable stackTrace = null;
    if (requiresNew && maxExecutionMs > 0) {
        startTime = System.currentTimeMillis();
        synchronized (this) {
            if (txnCount > 0) {
                // If this transaction would take us above our ceiling, reject it
                long oldestStart = txnsInProgress.firstKey();
                long oldestDuration = startTime - oldestStart;
                if (oldestDuration > maxExecutionMs) {
                    throw new TooBusyException("Too busy: " + txnCount + " transactions. Oldest "
                            + oldestDuration + " milliseconds", txnsInProgress.get(oldestStart).get(0));
                }
            }
            // Record the start time and stack trace of the starting thread
            List<Throwable> traces = txnsInProgress.get(startTime);
            if (traces == null) {
                traces = new LinkedList<Throwable>();
                txnsInProgress.put(startTime, traces);
            }
            stackTrace = new Exception("Stack trace");
            traces.add(stackTrace);
            ++txnCount;
        }
    }

    try {
        // Track the last exception caught, so that we
        // can throw it if we run out of retries.
        RuntimeException lastException = null;
        for (int count = 0; count == 0 || count < maxRetries; count++) {
            UserTransaction txn = null;
            try {
                if (requiresNew) {
                    txn = txnService.getNonPropagatingUserTransaction(readOnly, forceWritable);

                    txn.begin();
                    // Wrap it to protect it
                    UserTransactionProtectionAdvise advise = new UserTransactionProtectionAdvise();
                    ProxyFactory proxyFactory = new ProxyFactory(txn);
                    proxyFactory.addAdvice(advise);
                    UserTransaction wrappedTxn = (UserTransaction) proxyFactory.getProxy();
                    // Store the UserTransaction for static retrieval.  There is no need to unbind it
                    // because the transaction management will do that for us.
                    AlfrescoTransactionSupport.bindResource(KEY_ACTIVE_TRANSACTION, wrappedTxn);
                }
                // Do the work.
                R result = cb.execute();
                // Only commit if we 'own' the transaction.
                if (txn != null) {
                    if (txn.getStatus() == Status.STATUS_MARKED_ROLLBACK) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("\n" + "Transaction marked for rollback: \n" + "   Thread: "
                                    + Thread.currentThread().getName() + "\n" + "   Txn:    " + txn + "\n"
                                    + "   Iteration: " + count);
                        }
                        // Something caused the transaction to be marked for rollback
                        // There is no recovery or retrying with this
                        txn.rollback();
                    } else {
                        // The transaction hasn't been flagged for failure so the commit
                        // sould still be good.
                        txn.commit();
                    }
                }
                if (logger.isDebugEnabled()) {
                    if (count != 0) {
                        logger.debug("\n" + "Transaction succeeded: \n" + "   Thread: "
                                + Thread.currentThread().getName() + "\n" + "   Txn:    " + txn + "\n"
                                + "   Iteration: " + count);
                    }
                }
                return result;
            } catch (Throwable e) {
                // Somebody else 'owns' the transaction, so just rethrow.
                if (txn == null) {
                    RuntimeException ee = AlfrescoRuntimeException.makeRuntimeException(e,
                            "Exception from transactional callback: " + cb);
                    throw ee;
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("\n" + "Transaction commit failed: \n" + "   Thread: "
                            + Thread.currentThread().getName() + "\n" + "   Txn:    " + txn + "\n"
                            + "   Iteration: " + count + "\n" + "   Exception follows:", e);
                }
                // Rollback if we can.
                if (txn != null) {
                    try {
                        int txnStatus = txn.getStatus();
                        // We can only rollback if a transaction was started (NOT NO_TRANSACTION) and
                        // if that transaction has not been rolled back (NOT ROLLEDBACK).
                        // If an exception occurs while the transaction is being created (e.g. no database connection)
                        // then the status will be NO_TRANSACTION.
                        if (txnStatus != Status.STATUS_NO_TRANSACTION
                                && txnStatus != Status.STATUS_ROLLEDBACK) {
                            txn.rollback();
                        }
                    } catch (Throwable e1) {
                        // A rollback failure should not preclude a retry, but logging of the rollback failure is required
                        logger.error("Rollback failure.  Normal retry behaviour will resume.", e1);
                    }
                }
                if (e instanceof RollbackException) {
                    lastException = (e.getCause() instanceof RuntimeException) ? (RuntimeException) e.getCause()
                            : new AlfrescoRuntimeException("Exception in Transaction.", e.getCause());
                } else {
                    lastException = (e instanceof RuntimeException) ? (RuntimeException) e
                            : new AlfrescoRuntimeException("Exception in Transaction.", e);
                }
                // Check if there is a cause for retrying
                Throwable retryCause = extractRetryCause(e);
                // ALF-17361 fix, also check for configured extra exceptions 
                if (retryCause == null && extraExceptions != null && !extraExceptions.isEmpty()) {
                    retryCause = ExceptionStackUtil.getCause(e, extraExceptions.toArray(new Class[] {}));
                }

                if (retryCause != null) {
                    // Sleep a random amount of time before retrying.
                    // The sleep interval increases with the number of retries.
                    int sleepIntervalRandom = (count > 0 && retryWaitIncrementMs > 0)
                            ? random.nextInt(count * retryWaitIncrementMs)
                            : minRetryWaitMs;
                    int sleepInterval = Math.min(maxRetryWaitMs, sleepIntervalRandom);
                    sleepInterval = Math.max(sleepInterval, minRetryWaitMs);
                    if (logger.isInfoEnabled() && !logger.isDebugEnabled()) {
                        String msg = String.format(
                                "Retrying %s: count %2d; wait: %1.1fs; msg: \"%s\"; exception: (%s)",
                                Thread.currentThread().getName(), count, (double) sleepInterval / 1000D,
                                retryCause.getMessage(), retryCause.getClass().getName());
                        logger.info(msg);
                    }
                    try {
                        Thread.sleep(sleepInterval);
                    } catch (InterruptedException ie) {
                        // Do nothing.
                    }
                    // Try again
                    continue;
                } else {
                    // It was a 'bad' exception.
                    throw lastException;
                }
            }
        }
        // We've worn out our welcome and retried the maximum number of times.
        // So, fail.
        throw lastException;
    } finally {
        if (requiresNew && maxExecutionMs > 0) {
            synchronized (this) {
                txnCount--;
                List<Throwable> traces = txnsInProgress.get(startTime);
                if (traces != null) {
                    if (traces.size() == 1) {
                        txnsInProgress.remove(startTime);
                    } else {
                        traces.remove(stackTrace);
                    }
                }
            }
        }
    }
}

From source file:org.alfresco.repo.webdav.auth.BaseNTLMAuthenticationFilter.java

/**
 * Get the stored MD4 hashed password for the user, or null if the user does not exist
 * //w  w  w  .ja  va2s.  co  m
 * @param userName String
 *
 * @return MD4 hash or null
 */
protected String getMD4Hash(String userName) {
    String md4hash = null;

    // Wrap the auth component calls in a transaction
    UserTransaction tx = transactionService.getUserTransaction();
    try {
        tx.begin();

        // Get the stored MD4 hashed password for the user, or null if the user does not exist
        md4hash = nltmAuthenticator.getMD4HashedPassword(userName);
    } catch (Throwable ex) {
        if (getLogger().isDebugEnabled())
            getLogger().debug(ex);
    } finally {
        // Rollback/commit the transaction if still valid
        if (tx != null) {
            try {
                // Commit or rollback the transaction
                if (tx.getStatus() == Status.STATUS_MARKED_ROLLBACK
                        || tx.getStatus() == Status.STATUS_ROLLEDBACK
                        || tx.getStatus() == Status.STATUS_ROLLING_BACK) {
                    // Transaction is marked for rollback
                    tx.rollback();
                } else {
                    // Commit the transaction
                    tx.commit();
                }
            } catch (Throwable ex) {
                if (getLogger().isDebugEnabled())
                    getLogger().debug(ex);
            }
        }
    }

    return md4hash;
}

From source file:org.apache.ofbiz.entity.transaction.TransactionUtil.java

public static String getTransactionStateString(int state) {
    /*//from  w  ww  . j  a v a2  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 + ")";
    }
}

From source file:org.apache.ojb.odmg.JTATxManager.java

private static String getStatusString(int status) {
    switch (status) {
    case Status.STATUS_ACTIVE:
        return "STATUS_ACTIVE";
    case Status.STATUS_COMMITTED:
        return "STATUS_COMMITTED";
    case Status.STATUS_COMMITTING:
        return "STATUS_COMMITTING";
    case Status.STATUS_MARKED_ROLLBACK:
        return "STATUS_MARKED_ROLLBACK";
    case Status.STATUS_NO_TRANSACTION:
        return "STATUS_NO_TRANSACTION";
    case Status.STATUS_PREPARED:
        return "STATUS_PREPARED";
    case Status.STATUS_PREPARING:
        return "STATUS_PREPARING";
    case Status.STATUS_ROLLEDBACK:
        return "STATUS_ROLLEDBACK";
    case Status.STATUS_ROLLING_BACK:
        return "STATUS_ROLLING_BACK";
    case Status.STATUS_UNKNOWN:
        return "STATUS_UNKNOWN";
    default:/* w  w w .  j  a va  2s.  c om*/
        return "NO STATUS FOUND";
    }
}

From source file:org.apache.ojb.odmg.TransactionImpl.java

/**
 * Abort and close the transaction. Calling abort abandons all persistent
 * object modifications and releases the associated locks. Aborting a
 * transaction does not restore the state of modified transient objects
 *///from   w  w  w  .j  av  a  2s.  co m
public void abort() {
    /*
    do nothing if already rolledback
    */
    if (txStatus == Status.STATUS_NO_TRANSACTION || txStatus == Status.STATUS_UNKNOWN
            || txStatus == Status.STATUS_ROLLEDBACK) {
        log.info("Nothing to abort, tx is not active - status is " + TxUtil.getStatusString(txStatus));
        return;
    }
    // check status of tx
    if (txStatus != Status.STATUS_ACTIVE && txStatus != Status.STATUS_PREPARED
            && txStatus != Status.STATUS_MARKED_ROLLBACK) {
        throw new IllegalStateException(
                "Illegal state for abort call, state was '" + TxUtil.getStatusString(txStatus) + "'");
    }
    if (log.isEnabledFor(Logger.INFO)) {
        log.info("Abort transaction was called on tx " + this);
    }
    try {
        try {
            doAbort();
        } catch (Exception e) {
            log.error("Error while abort transaction, will be skipped", e);
        }

        // used in managed environments, ignored in non-managed
        this.implementation.getTxManager().abortExternalTx(this);

        try {
            if (hasBroker() && getBroker().isInTransaction()) {
                getBroker().abortTransaction();
            }
        } catch (Exception e) {
            log.error("Error while do abort used broker instance, will be skipped", e);
        }
    } finally {
        txStatus = Status.STATUS_ROLLEDBACK;
        // cleanup things, e.g. release all locks
        doClose();
    }
}

From source file:org.apache.openjpa.kernel.BrokerImpl.java

/**
 * Mark the current transaction as rollback-only.
 *//*w  w  w.  j ava2 s  . c  om*/
private void setRollbackOnlyInternal(Throwable cause) {
    try {
        javax.transaction.Transaction trans = _runtime.getTransactionManager().getTransaction();
        if (trans == null)
            throw new InvalidStateException(_loc.get("null-trans"));
        // ensure tran is in a valid state to accept the setRollbackOnly
        int tranStatus = trans.getStatus();
        if ((tranStatus != Status.STATUS_NO_TRANSACTION) && (tranStatus != Status.STATUS_ROLLEDBACK)
                && (tranStatus != Status.STATUS_COMMITTED))
            _runtime.setRollbackOnly(cause);
        else if (_log.isTraceEnabled())
            _log.trace(_loc.get("invalid-tran-status", Integer.valueOf(tranStatus), "setRollbackOnly"));
    } catch (OpenJPAException ke) {
        throw ke;
    } catch (Exception e) {
        throw new GeneralException(e);
    }
}

From source file:org.apache.openjpa.kernel.BrokerImpl.java

public void afterCompletion(int status) {
    beginOperation(false);//w  w w.  j  ava 2  s  .  c  o m
    try {
        assertActiveTransaction();

        _flags |= FLAG_TRANS_ENDING;
        endTransaction(status);
        if (_sync != null)
            _sync.afterCompletion(status);

        if ((_autoDetach & DETACH_COMMIT) != 0)
            detachAllInternal(null);
        else if (status == Status.STATUS_ROLLEDBACK && (_autoDetach & DETACH_ROLLBACK) != 0) {
            detachAllInternal(null);
        }

        // in an ee context, it's possible that the user tried to close
        // us but we didn't actually close because we were waiting on this
        // transaction; if that's true, then close now
        if ((_flags & FLAG_CLOSE_INVOKED) != 0 && _compat.getCloseOnManagedCommit())
            free();
    } catch (OpenJPAException ke) {
        if (_log.isTraceEnabled())
            _log.trace(_loc.get("end-trans-error"), ke);
        throw translateManagedCompletionException(ke);
    } catch (RuntimeException re) {
        if (_log.isTraceEnabled())
            _log.trace(_loc.get("end-trans-error"), re);
        throw translateManagedCompletionException(new StoreException(re));
    } finally {
        _flags &= ~FLAG_ACTIVE;
        _flags &= ~FLAG_FLUSHED;
        _flags &= ~FLAG_TRANS_ENDING;

        // event manager nulled if freed broker
        if (_transEventManager != null && _transEventManager.hasEndListeners()) {
            fireTransactionEvent(new TransactionEvent(this,
                    status == Status.STATUS_COMMITTED ? TransactionEvent.AFTER_COMMIT_COMPLETE
                            : TransactionEvent.AFTER_ROLLBACK_COMPLETE,
                    null, null, null, null));
        }

        endOperation();
    }
}