Example usage for javax.transaction Status STATUS_NO_TRANSACTION

List of usage examples for javax.transaction Status STATUS_NO_TRANSACTION

Introduction

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

Prototype

int STATUS_NO_TRANSACTION

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

Click Source Link

Document

No transaction is currently associated with the target object.

Usage

From source file:org.alfresco.util.transaction.SpringAwareUserTransaction.java

/**
 * @throws NotSupportedException if an attempt is made to reuse this instance
 *///  w w w. j a v a  2s.co m
public synchronized void begin() throws NotSupportedException, SystemException {
    // make sure that the status and info align - the result may or may not be null
    @SuppressWarnings("unused")
    TransactionInfo txnInfo = getTransactionInfo();
    if (internalStatus != Status.STATUS_NO_TRANSACTION) {
        throw new NotSupportedException("The UserTransaction may not be reused");
    }

    // check 

    if ((propagationBehaviour != TransactionDefinition.PROPAGATION_REQUIRES_NEW)) {
        if (!readOnly && TransactionSynchronizationManager.isSynchronizationActive()
                && TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
            throw new IllegalStateException("Nested writable transaction in a read only transaction");
        }
    }

    // begin a transaction
    try {
        internalTxnInfo = createTransactionIfNecessary((Method) null, (Class<?>) null); // super class will just pass nulls back to us
    } catch (CannotCreateTransactionException e) {
        throw new ConnectionPoolException("The DB connection pool is depleted.", e);
    }

    internalStatus = Status.STATUS_ACTIVE;
    threadId = Thread.currentThread().getId();

    // Record that transaction details now that begin was successful
    isBeginMatched = false;
    if (isCallStackTraced) {
        // get the stack trace
        Exception e = new Exception();
        e.fillInStackTrace();
        beginCallStack = e.getStackTrace();
    }

    // done
    if (logger.isDebugEnabled()) {
        logger.debug("Began user transaction: " + this);
    }
}

From source file:com._4dconcept.springframework.data.marklogic.datasource.DatabaseConnectorJtaTransactionTest.java

private void doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(final boolean requiresNew,
        boolean notSupported) throws Exception {

    if (notSupported) {
        given(userTransaction.getStatus()).willReturn(Status.STATUS_ACTIVE, Status.STATUS_NO_TRANSACTION,
                Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
        given(transactionManager.suspend()).willReturn(transaction);
    } else {//from  ww w .j ava  2 s .  c o m
        given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION,
                Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
    }

    final ContentSource contentSource = mock(ContentSource.class);
    final Session session1 = mock(Session.class);
    final Session session2 = mock(Session.class);
    given(contentSource.newSession()).willReturn(session1, session2);

    final JtaTransactionManager ptm = new JtaTransactionManager(userTransaction, transactionManager);
    TransactionTemplate tt = new TransactionTemplate(ptm);
    tt.setPropagationBehavior(notSupported ? TransactionDefinition.PROPAGATION_NOT_SUPPORTED
            : TransactionDefinition.PROPAGATION_SUPPORTS);

    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
            assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
            assertSame(session1, ContentSourceUtils.getSession(contentSource));
            assertSame(session1, ContentSourceUtils.getSession(contentSource));

            TransactionTemplate tt2 = new TransactionTemplate(ptm);
            tt2.setPropagationBehavior(requiresNew ? TransactionDefinition.PROPAGATION_REQUIRES_NEW
                    : TransactionDefinition.PROPAGATION_REQUIRED);
            tt2.execute(new TransactionCallbackWithoutResult() {
                @Override
                protected void doInTransactionWithoutResult(TransactionStatus status) {
                    assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
                    assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
                    assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
                    assertSame(session2, ContentSourceUtils.getSession(contentSource));
                    assertSame(session2, ContentSourceUtils.getSession(contentSource));
                }
            });

            assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
            assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
            assertSame(session1, ContentSourceUtils.getSession(contentSource));
        }
    });
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
    verify(userTransaction).begin();
    verify(userTransaction).commit();
    if (notSupported) {
        verify(transactionManager).resume(transaction);
    }
    verify(session2).close();
    verify(session1).close();
}

From source file:org.alfresco.util.transaction.SpringAwareUserTransaction.java

/**
 * @throws IllegalStateException if a transaction was not started
 *//* w ww.ja v a2  s .c om*/
public synchronized void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException,
        SecurityException, IllegalStateException, SystemException {
    // perform checks
    TransactionInfo txnInfo = getTransactionInfo();

    int status = getStatus();
    // check the status
    if (status == Status.STATUS_NO_TRANSACTION) {
        throw new IllegalStateException("The transaction has not yet begun");
    } else if (status == Status.STATUS_ROLLING_BACK || status == Status.STATUS_ROLLEDBACK) {
        throw new RollbackException("The transaction has already been rolled back");
    } else if (status == Status.STATUS_MARKED_ROLLBACK) {
        throw new RollbackException("The transaction has already been marked for rollback");
    } else if (status == Status.STATUS_COMMITTING || status == Status.STATUS_COMMITTED) {
        throw new IllegalStateException("The transaction has already been committed");
    } else if (status != Status.STATUS_ACTIVE || txnInfo == null) {
        throw new IllegalStateException("No user transaction is active");
    }

    if (!finalized) {
        try {
            // the status seems correct - we can try a commit
            commitTransactionAfterReturning(txnInfo);
        } catch (Throwable e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Transaction didn't commit", e);
            }
            // commit failed
            internalStatus = Status.STATUS_ROLLEDBACK;
            RollbackException re = new RollbackException("Transaction didn't commit: " + e.getMessage());
            // Stick the originating reason for failure into the exception.
            re.initCause(e);
            throw re;
        } finally {
            // make sure that we clean up the stack
            cleanupTransactionInfo(txnInfo);
            finalized = true;
            // clean up leaked transaction logging
            isBeginMatched = true;
            beginCallStack = null;
        }
    }

    // regardless of whether the transaction was finally committed or not, the status
    // as far as UserTransaction is concerned should be 'committed'

    // keep track that this UserTransaction was explicitly committed
    internalStatus = Status.STATUS_COMMITTED;

    // done
    if (logger.isDebugEnabled()) {
        logger.debug("Committed user transaction: " + this);
    }
}

From source file:com._4dconcept.springframework.data.marklogic.datasource.DatabaseConnectorJtaTransactionTest.java

private void doTestJtaTransactionWithPropagationRequiresNewAndBeginException(boolean suspendException,
        final boolean openOuterConnection, final boolean useTransactionAwareContentSource) throws Exception {

    given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE,
            Status.STATUS_ACTIVE);
    if (suspendException) {
        given(transactionManager.suspend()).willThrow(new SystemException());
    } else {// w  w  w . j  a v  a  2  s .  c o m
        given(transactionManager.suspend()).willReturn(transaction);
        willThrow(new SystemException()).given(userTransaction).begin();
    }

    given(session.getTransactionMode()).willReturn(Session.TransactionMode.QUERY);

    final ContentSource dsToUse = useTransactionAwareContentSource
            ? new TransactionAwareContentSourceProxy(contentSource)
            : contentSource;
    if (dsToUse instanceof TransactionAwareContentSourceProxy) {
        ((TransactionAwareContentSourceProxy) dsToUse).setReobtainTransactionalSessions(true);
    }

    JtaTransactionManager ptm = new JtaTransactionManager(userTransaction, transactionManager);
    final TransactionTemplate tt = new TransactionTemplate(ptm);
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(dsToUse));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

    try {
        tt.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
                assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(dsToUse));
                assertTrue("JTA synchronizations active",
                        TransactionSynchronizationManager.isSynchronizationActive());
                assertTrue("Is new transaction", status.isNewTransaction());

                Session c = ContentSourceUtils.getSession(dsToUse);
                assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(dsToUse));
                c.getTransactionMode();
                ContentSourceUtils.releaseSession(c, dsToUse);

                c = ContentSourceUtils.getSession(dsToUse);
                assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(dsToUse));
                if (!openOuterConnection) {
                    ContentSourceUtils.releaseSession(c, dsToUse);
                }

                try {
                    tt.execute(new TransactionCallbackWithoutResult() {
                        @Override
                        protected void doInTransactionWithoutResult(TransactionStatus status)
                                throws RuntimeException {
                            assertTrue("Hasn't thread session",
                                    !TransactionSynchronizationManager.hasResource(dsToUse));
                            assertTrue("JTA synchronizations active",
                                    TransactionSynchronizationManager.isSynchronizationActive());
                            assertTrue("Is new transaction", status.isNewTransaction());

                            Session c = ContentSourceUtils.getSession(dsToUse);
                            assertTrue("Has thread session",
                                    TransactionSynchronizationManager.hasResource(dsToUse));
                            ContentSourceUtils.releaseSession(c, dsToUse);

                            c = ContentSourceUtils.getSession(dsToUse);
                            assertTrue("Has thread session",
                                    TransactionSynchronizationManager.hasResource(dsToUse));
                            ContentSourceUtils.releaseSession(c, dsToUse);
                        }
                    });
                } finally {
                    if (openOuterConnection) {
                        c.getTransactionMode();
                        ContentSourceUtils.releaseSession(c, dsToUse);

                    }
                }
            }
        });

        fail("Should have thrown TransactionException");
    } catch (TransactionException ex) {
        // expected
    }

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(dsToUse));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

    verify(userTransaction).begin();
    if (suspendException) {
        verify(userTransaction).rollback();
    }

    if (suspendException) {
        verify(session, atLeastOnce()).close();
    } else {
        verify(session, never()).close();
    }
}

From source file:com._4dconcept.springframework.data.marklogic.datasource.DatabaseConnectorJtaTransactionTest.java

@Test
public void testJtaTransactionWithIsolationLevelContentSourceAdapter() throws Exception {
    given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE,
            Status.STATUS_ACTIVE, Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);

    final IsolationLevelContentSourceAdapter dsToUse = new IsolationLevelContentSourceAdapter();
    dsToUse.setTargetContentSource(contentSource);
    dsToUse.afterPropertiesSet();//from ww  w. ja va  2 s  . c o  m

    JtaTransactionManager ptm = new JtaTransactionManager(userTransaction);
    ptm.setAllowCustomIsolationLevels(true);

    TransactionTemplate tt = new TransactionTemplate(ptm);
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            Session c = ContentSourceUtils.getSession(dsToUse);
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(dsToUse));
            assertSame(session, c);
            ContentSourceUtils.releaseSession(c, dsToUse);
        }
    });

    tt.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
    tt.setReadOnly(true);
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            Session c = ContentSourceUtils.getSession(dsToUse);
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(dsToUse));
            assertSame(session, c);
            ContentSourceUtils.releaseSession(c, dsToUse);
        }
    });

    verify(userTransaction, times(2)).begin();
    verify(userTransaction, times(2)).commit();
    verify(session).setTransactionMode(Session.TransactionMode.QUERY);
    verify(session, times(2)).close();
}

From source file:com._4dconcept.springframework.data.marklogic.datasource.DatabaseConnectorJtaTransactionTest.java

private void doTestJtaTransactionWithIsolationLevelContentSourceRouter() throws Exception {
    given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE,
            Status.STATUS_ACTIVE, Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);

    final ContentSource contentSource1 = mock(ContentSource.class);
    final Session session1 = mock(Session.class);
    given(contentSource1.newSession()).willReturn(session1);

    final ContentSource contentSource2 = mock(ContentSource.class);
    final Session session2 = mock(Session.class);
    given(contentSource2.newSession()).willReturn(session2);

    final IsolationLevelContentSourceRouter dsToUse = new IsolationLevelContentSourceRouter();
    Map<Object, Object> targetContentSources = new HashMap<Object, Object>();

    targetContentSources.put("ISOLATION_REPEATABLE_READ", contentSource2);
    dsToUse.setDefaultTargetContentSource(contentSource1);

    dsToUse.setTargetContentSources(targetContentSources);
    dsToUse.afterPropertiesSet();/*from ww w.  j  a va 2s.  c  om*/

    JtaTransactionManager ptm = new JtaTransactionManager(userTransaction);
    ptm.setAllowCustomIsolationLevels(true);

    TransactionTemplate tt = new TransactionTemplate(ptm);
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            Session c = ContentSourceUtils.getSession(dsToUse);
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(dsToUse));
            assertSame(session1, c);
            ContentSourceUtils.releaseSession(c, dsToUse);
        }
    });

    tt.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            Session c = ContentSourceUtils.getSession(dsToUse);
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(dsToUse));
            assertSame(session2, c);
            ContentSourceUtils.releaseSession(c, dsToUse);
        }
    });

    verify(userTransaction, times(2)).begin();
    verify(userTransaction, times(2)).commit();
    verify(session1).close();
    verify(session2).close();
}

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.//  w  w w . ja  va 2s.  c o m
 * <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.apache.ode.daohib.JotmTransaction.java

/**
 * {@inheritDoc}/*from w  w  w. j a v a 2  s .co m*/
 */
public void begin() throws HibernateException {
    if (begun) {
        return;
    }
    if (commitFailed) {
        throw new TransactionException("cannot re-start transaction after failed commit");
    }

    log.debug("begin");

    try {
        newTransaction = userTransaction.getStatus() == Status.STATUS_NO_TRANSACTION;
        if (newTransaction) {
            userTransaction.begin();
            log.debug("Began a new JTA transaction");
        }
    } catch (Exception e) {
        log.error("JTA transaction begin failed", e);
        throw new TransactionException("JTA transaction begin failed", e);
    }

    /*if (newTransaction) {
    // don't need a synchronization since we are committing
    // or rolling back the transaction ourselves - assuming
    // that we do no work in beforeTransactionCompletion()
    synchronization = false;
    }*/

    boolean synchronization = jdbcContext.registerSynchronizationIfPossible();

    if (!newTransaction && !synchronization) {
        log.warn("You should set hibernate.transaction.manager_lookup_class if cache is enabled");
    }

    if (!synchronization) {
        //if we could not register a synchronization,
        //do the before/after completion callbacks
        //ourself (but we need to let jdbcContext
        //know that this is what we are going to
        //do, so it doesn't keep trying to register
        //synchronizations)
        callback = jdbcContext.registerCallbackIfNecessary();
    }

    begun = true;
    commitSucceeded = false;

    jdbcContext.afterTransactionBegin(this);
}

From source file:org.apache.ode.scheduler.simple.SimpleScheduler.java

public boolean isTransacted() {
    TransactionManager txm = _txm;/*from   ww  w.ja v  a 2 s . c  o m*/
    if (txm == null) {
        throw new ContextException("Cannot locate the transaction manager; the server might be shutting down.");
    }

    try {
        Transaction tx = txm.getTransaction();
        return (tx != null && tx.getStatus() != Status.STATUS_NO_TRANSACTION);
    } catch (SystemException e) {
        throw new ContextException("Internal Error: Could not obtain transaction status.");
    }
}

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

public static String getTransactionStateString(int state) {
    /*//www . j  ava 2 s. co  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 + ")";
    }
}