Example usage for javax.transaction UserTransaction getStatus

List of usage examples for javax.transaction UserTransaction getStatus

Introduction

In this page you can find the example usage for javax.transaction UserTransaction getStatus.

Prototype

int getStatus() throws SystemException;

Source Link

Document

Obtain the status of the transaction associated with the current thread.

Usage

From source file:org.alfresco.repo.cache.CacheTest.java

public void testTransactionalCacheStatsDisabled() throws Throwable {
    // add item to global cache
    TransactionalCache.putSharedCacheValue(backingCacheNoStats, "stats-test1", "v", null);
    TransactionalCache.putSharedCacheValue(backingCacheNoStats, "stats-test2", "v", null);
    TransactionalCache.putSharedCacheValue(backingCacheNoStats, "stats-test3", "v", null);

    TransactionService transactionService = serviceRegistry.getTransactionService();
    UserTransaction txn = transactionService.getUserTransaction();

    for (OpType opType : OpType.values()) {
        try {/*from w ww.j  a v  a 2 s  .c o  m*/
            cacheStats.count("transactionalCacheNoStats", opType);
            fail("Expected NoStatsForCache error.");
        } catch (NoStatsForCache e) {
            // Good
        }
    }

    try {
        // begin a transaction
        txn.begin();

        // Perform some puts
        transactionalCacheNoStats.put("stats-test4", "v");
        transactionalCache.put("stats-test5", "v");
        transactionalCache.put("stats-test6", "v");
        transactionalCache.put("stats-test7", "v");
        transactionalCache.put("stats-test8", "v");

        // Perform some gets...
        // hits
        transactionalCache.get("stats-test3");
        transactionalCache.get("stats-test2");
        transactionalCache.get("stats-test1");
        // repeated hits won't touch the shared cache
        transactionalCache.get("stats-test2");
        transactionalCache.get("stats-test1");
        // misses - not yet committed
        transactionalCache.get("stats-miss1");
        transactionalCache.get("stats-miss2");
        transactionalCache.get("stats-miss3");
        transactionalCache.get("stats-miss4");
        // repeated misses won't touch the shared cache
        transactionalCache.get("stats-miss2");
        transactionalCache.get("stats-miss3");

        // Perform some removals
        transactionalCache.remove("stats-test1");
        transactionalCache.remove("stats-test2");
        transactionalCache.remove("stats-test3");
        transactionalCache.remove("stats-test9");
        transactionalCache.remove("stats-test10");
        transactionalCache.remove("stats-test11");
        transactionalCache.remove("stats-test12");
        transactionalCache.remove("stats-test13");

        // Check nothing has changed - changes not written through until commit or rollback
        for (OpType opType : OpType.values()) {
            try {
                cacheStats.count("transactionalCacheNoStats", opType);
                fail("Expected NoStatsForCache error.");
            } catch (NoStatsForCache e) {
                // Good
            }
        }

        // commit the transaction
        txn.commit();

        // Post-commit, nothing should have changed.
        for (OpType opType : OpType.values()) {
            try {
                cacheStats.count("transactionalCacheNoStats", opType);
                fail("Expected NoStatsForCache error.");
            } catch (NoStatsForCache e) {
                // Good
            }
        }
    } catch (Throwable e) {
        if (txn.getStatus() == Status.STATUS_ACTIVE) {
            txn.rollback();
        }
        throw e;
    }
}

From source file:org.alfresco.repo.cache.CacheTest.java

public void testTransactionalCacheStatsForClears() throws Throwable {
    // add item to global cache
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test1", "v", null);
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test2", "v", null);
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test3", "v", null);

    TransactionService transactionService = serviceRegistry.getTransactionService();
    UserTransaction txn = transactionService.getUserTransaction();

    final long hitsAtStart = cacheStats.count("transactionalCache", OpType.GET_HIT);
    final long missesAtStart = cacheStats.count("transactionalCache", OpType.GET_MISS);
    final long putsAtStart = cacheStats.count("transactionalCache", OpType.PUT);
    final long removesAtStart = cacheStats.count("transactionalCache", OpType.REMOVE);
    final long clearsAtStart = cacheStats.count("transactionalCache", OpType.CLEAR);

    try {/*  w  w  w .ja  v  a2s . c  o m*/
        // begin a transaction
        txn.begin();

        // Perform some puts
        transactionalCache.put("stats-test4", "v");
        transactionalCache.put("stats-test5", "v");
        transactionalCache.put("stats-test6", "v");
        transactionalCache.put("stats-test7", "v");
        transactionalCache.put("stats-test8", "v");

        // Perform some gets...
        // hits
        transactionalCache.get("stats-test3");
        transactionalCache.get("stats-test2");
        transactionalCache.get("stats-test1");
        // repeated hits won't touch the shared cache
        transactionalCache.get("stats-test2");
        transactionalCache.get("stats-test1");
        // misses - not yet committed
        transactionalCache.get("stats-miss1");
        transactionalCache.get("stats-miss2");
        transactionalCache.get("stats-miss3");
        transactionalCache.get("stats-miss4");
        // repeated misses won't touch the shared cache
        transactionalCache.get("stats-miss2");
        transactionalCache.get("stats-miss3");

        // Perform some removals
        transactionalCache.remove("stats-test1");
        transactionalCache.remove("stats-test2");
        transactionalCache.remove("stats-test3");
        transactionalCache.remove("stats-test9");
        transactionalCache.remove("stats-test10");
        transactionalCache.remove("stats-test11");
        transactionalCache.remove("stats-test12");
        transactionalCache.remove("stats-test13");

        // Perform some clears
        transactionalCache.clear();
        transactionalCache.clear();

        // Check nothing has changed yet - changes not written through until commit or rollback
        assertEquals(hitsAtStart, cacheStats.count("transactionalCache", OpType.GET_HIT));
        assertEquals(missesAtStart, cacheStats.count("transactionalCache", OpType.GET_MISS));
        assertEquals(putsAtStart, cacheStats.count("transactionalCache", OpType.PUT));
        assertEquals(removesAtStart, cacheStats.count("transactionalCache", OpType.REMOVE));
        assertEquals(clearsAtStart, cacheStats.count("transactionalCache", OpType.CLEAR));

        // commit the transaction
        txn.commit();

        assertEquals(clearsAtStart + 2, cacheStats.count("transactionalCache", OpType.CLEAR));
        // There are no removes or puts propagated to the shared cache, as a result of the clears.
        assertEquals(removesAtStart + 0, cacheStats.count("transactionalCache", OpType.REMOVE));
        assertEquals(putsAtStart + 0, cacheStats.count("transactionalCache", OpType.PUT));
        assertEquals(hitsAtStart + 3, cacheStats.count("transactionalCache", OpType.GET_HIT));
        assertEquals(missesAtStart + 4, cacheStats.count("transactionalCache", OpType.GET_MISS));
    } catch (Throwable e) {
        if (txn.getStatus() == Status.STATUS_ACTIVE) {
            txn.rollback();
        }
        throw e;
    }
}

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 ww.j a  va2  s  .  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.alfresco.repo.transaction.RetryingTransactionHelperTest.java

/**
 * Check that the transaction state can be fetched in and around the transaction.
 * This also checks that any mischievous attempts to manipulate the transaction
 * (other than setRollback) are detected. 
 *//*from   w w  w.ja  va 2  s .  c om*/
public void testUserTransactionStatus() {
    UserTransaction txnBefore = RetryingTransactionHelper.getActiveUserTransaction();
    assertNull("Did not expect to get an active UserTransaction", txnBefore);

    RetryingTransactionCallback<Long> callbackOuter = new RetryingTransactionCallback<Long>() {
        public Long execute() throws Throwable {
            final UserTransaction txnOuter = RetryingTransactionHelper.getActiveUserTransaction();
            assertNotNull("Expected an active UserTransaction", txnOuter);
            assertEquals("Should be read-write txn", TxnReadState.TXN_READ_WRITE,
                    AlfrescoTransactionSupport.getTransactionReadState());
            assertEquals("Expected state is active", Status.STATUS_ACTIVE, txnOuter.getStatus());
            RetryingTransactionCallback<Long> callbackInner = new RetryingTransactionCallback<Long>() {
                public Long execute() throws Throwable {
                    UserTransaction txnInner = RetryingTransactionHelper.getActiveUserTransaction();
                    assertNotNull("Expected an active UserTransaction", txnInner);
                    assertEquals("Should be read-only txn", TxnReadState.TXN_READ_ONLY,
                            AlfrescoTransactionSupport.getTransactionReadState());
                    assertEquals("Expected state is active", Status.STATUS_ACTIVE, txnInner.getStatus());
                    // Check blow up
                    try {
                        txnInner.commit();
                        fail("Should not be able to commit the UserTransaction.  It is for info only.");
                    } catch (Throwable e) {
                        // Expected
                    }
                    // Force a rollback
                    txnInner.setRollbackOnly();
                    // Done
                    return null;
                }
            };
            return txnHelper.doInTransaction(callbackInner, true, true);
        }
    };
    txnHelper.doInTransaction(callbackOuter);

    UserTransaction txnAfter = RetryingTransactionHelper.getActiveUserTransaction();
    assertNull("Did not expect to get an active UserTransaction", txnAfter);
}

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

/**
 * Execute the transaction work in a user transaction of a specified type
 * /*ww  w.ja va 2  s  . c  om*/
 * @param transactionService the transaction service
 * @param transactionWork the transaction work
 * @param nonPropagatingUserTransaction indicates whether the transaction
 *        should be non propigating or not
 * @param readOnly true if the transaction should be read-only
 * 
 * @throws java.lang.RuntimeException if the transaction was rolled back
 */
private static <R> R executeInTransaction(TransactionService transactionService,
        TransactionWork<R> transactionWork, boolean nonPropagatingUserTransaction, boolean readOnly) {
    ParameterCheck.mandatory("transactionWork", transactionWork);

    R result = null;

    // Get the right type of user transaction
    UserTransaction txn = null;
    if (nonPropagatingUserTransaction == true) {
        txn = transactionService.getNonPropagatingUserTransaction();
    } else {
        txn = transactionService.getUserTransaction(readOnly);
    }

    try {
        // Begin the transaction, do the work and then commit the
        // transaction
        txn.begin();
        result = transactionWork.doWork();
        // rollback or commit
        if (txn.getStatus() == Status.STATUS_MARKED_ROLLBACK) {
            // something caused the transaction to be marked for rollback
            txn.rollback();
        } else {
            // transaction should still commit
            txn.commit();
        }
    } catch (RollbackException exception) {
        // commit failed
        throw new AlfrescoRuntimeException("Unexpected rollback exception: \n" + exception.getMessage(),
                exception);
    } catch (Throwable exception) {
        try {
            // Roll back the exception
            txn.rollback();
        } catch (Throwable rollbackException) {
            // just dump the exception - we are already in a failure state
            logger.error("Error rolling back transaction", rollbackException);
        }

        // Re-throw the exception
        if (exception instanceof RuntimeException) {
            throw (RuntimeException) exception;
        } else {
            throw new RuntimeException("Error during execution of transaction.", exception);
        }
    }

    return result;
}

From source file:org.alfresco.repo.web.scripts.person.UserCSVUploadPost.java

/**
 * @see DeclarativeWebScript#executeImpl(org.springframework.extensions.webscripts.WebScriptRequest, org.springframework.extensions.webscripts.Status)
 *//*from  ww w .ja  va2  s.  c  om*/
@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status) {
    final List<Map<QName, String>> users = new ArrayList<Map<QName, String>>();
    final ResourceBundle rb = getResources();

    // Try to load the user details from the upload
    FormData form = (FormData) req.parseContent();
    if (form == null || !form.getIsMultiPart()) {
        throw new ResourceBundleWebScriptException(Status.STATUS_BAD_REQUEST, rb, ERROR_BAD_FORM);
    }

    boolean processed = false;
    for (FormData.FormField field : form.getFields()) {
        if (field.getIsFile()) {
            processUpload(field.getInputStream(), field.getFilename(), users);
            processed = true;
            break;
        }
    }

    if (!processed) {
        throw new ResourceBundleWebScriptException(Status.STATUS_BAD_REQUEST, rb, ERROR_NO_FILE);
    }

    // Should we send emails?
    boolean sendEmails = true;
    if (req.getParameter("email") != null) {
        sendEmails = Boolean.parseBoolean(req.getParameter("email"));
    }

    if (form.hasField("email")) {
        sendEmails = Boolean.parseBoolean(form.getParameters().get("email")[0]);
    }

    // Now process the users
    final MutableInt totalUsers = new MutableInt(0);
    final MutableInt addedUsers = new MutableInt(0);
    final Map<String, String> results = new HashMap<String, String>();
    final boolean doSendEmails = sendEmails;

    // Do the work in a new transaction, so that if we hit a problem
    //  during the commit stage (eg too many users) then we get to
    //  hear about it, and handle it ourselves.
    // Otherwise, commit exceptions occur deep inside RepositoryContainer
    //  and we can't control the status code
    RetryingTransactionCallback<Void> work = new RetryingTransactionCallback<Void>() {
        public Void execute() throws Throwable {
            try {
                doAddUsers(totalUsers, addedUsers, results, users, rb, doSendEmails);
                return null;
            } catch (Throwable t) {
                // Make sure we rollback from this
                UserTransaction userTrx = RetryingTransactionHelper.getActiveUserTransaction();
                if (userTrx != null && userTrx.getStatus() != javax.transaction.Status.STATUS_MARKED_ROLLBACK) {
                    try {
                        userTrx.setRollbackOnly();
                    } catch (Throwable t2) {
                    }
                }
                // Report the problem further down
                throw t;
            }
        }
    };

    try {
        retryingTransactionHelper.doInTransaction(work);
    } catch (Throwable t) {
        // Tell the client of the problem
        if (t instanceof WebScriptException) {
            // We've already wrapped it properly, all good
            throw (WebScriptException) t;
        } else {
            // Something unexpected has ripped up
            // Return the details with a 200, so that Share does the right thing
            throw new ResourceBundleWebScriptException(Status.STATUS_OK, rb, ERROR_GENERAL, t);
        }
    }

    // If we get here, then adding the users didn't throw any exceptions,
    //  so tell the client which users went in and which didn't
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("totalUsers", totalUsers);
    model.put("addedUsers", addedUsers);
    model.put("users", results);

    return model;
}

From source file:org.alfresco.repo.web.scripts.RepositoryContainer.java

/**
 * Execute script within required level of transaction
 * /*ww w.j  a v  a 2 s .  com*/
 * @param script WebScript
 * @param scriptReq WebScriptRequest
 * @param scriptRes WebScriptResponse
 * @throws IOException
 */
protected void transactionedExecute(final WebScript script, final WebScriptRequest scriptReq,
        final WebScriptResponse scriptRes) throws IOException {
    try {
        final Description description = script.getDescription();
        if (description.getRequiredTransaction() == RequiredTransaction.none) {
            script.execute(scriptReq, scriptRes);
        } else {
            final BufferedRequest bufferedReq;
            final BufferedResponse bufferedRes;
            RequiredTransactionParameters trxParams = description.getRequiredTransactionParameters();
            if (trxParams.getCapability() == TransactionCapability.readwrite) {
                if (trxParams.getBufferSize() > 0) {
                    if (logger.isDebugEnabled())
                        logger.debug("Creating Transactional Response for ReadWrite transaction; buffersize="
                                + trxParams.getBufferSize());

                    // create buffered request and response that allow transaction retrying
                    bufferedReq = new BufferedRequest(scriptReq, streamFactory);
                    bufferedRes = new BufferedResponse(scriptRes, trxParams.getBufferSize());
                } else {
                    if (logger.isDebugEnabled())
                        logger.debug("Transactional Response bypassed for ReadWrite - buffersize=0");
                    bufferedReq = null;
                    bufferedRes = null;
                }
            } else {
                bufferedReq = null;
                bufferedRes = null;
            }

            // encapsulate script within transaction
            RetryingTransactionCallback<Object> work = new RetryingTransactionCallback<Object>() {
                public Object execute() throws Exception {
                    try {
                        if (logger.isDebugEnabled())
                            logger.debug("Begin retry transaction block: "
                                    + description.getRequiredTransaction() + ","
                                    + description.getRequiredTransactionParameters().getCapability());

                        if (bufferedRes == null) {
                            script.execute(scriptReq, scriptRes);
                        } else {
                            // Reset the request and response in case of a transaction retry
                            bufferedReq.reset();
                            bufferedRes.reset();
                            script.execute(bufferedReq, bufferedRes);
                        }
                    } catch (Exception e) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Transaction exception: " + description.getRequiredTransaction() + ": "
                                    + e.getMessage());
                            // Note: user transaction shouldn't be null, but just in case inside this exception handler
                            UserTransaction userTrx = RetryingTransactionHelper.getActiveUserTransaction();
                            if (userTrx != null) {
                                logger.debug("Transaction status: " + userTrx.getStatus());
                            }
                        }

                        UserTransaction userTrx = RetryingTransactionHelper.getActiveUserTransaction();
                        if (userTrx != null) {
                            if (userTrx.getStatus() != Status.STATUS_MARKED_ROLLBACK) {
                                if (logger.isDebugEnabled())
                                    logger.debug("Marking web script transaction for rollback");
                                try {
                                    userTrx.setRollbackOnly();
                                } catch (Throwable re) {
                                    if (logger.isDebugEnabled())
                                        logger.debug(
                                                "Caught and ignoring exception during marking for rollback: "
                                                        + re.getMessage());
                                }
                            }
                        }

                        // re-throw original exception for retry
                        throw e;
                    } finally {
                        if (logger.isDebugEnabled())
                            logger.debug("End retry transaction block: " + description.getRequiredTransaction()
                                    + "," + description.getRequiredTransactionParameters().getCapability());
                    }

                    return null;
                }
            };

            boolean readonly = description.getRequiredTransactionParameters()
                    .getCapability() == TransactionCapability.readonly;
            boolean requiresNew = description.getRequiredTransaction() == RequiredTransaction.requiresnew;

            // log a warning if we detect a GET webscript being run in a readwrite transaction, GET calls should
            // NOT have any side effects so this scenario as a warning sign something maybe amiss, see ALF-10179.
            if (logger.isDebugEnabled() && !readonly && "GET".equalsIgnoreCase(description.getMethod())) {
                logger.debug("Webscript with URL '" + scriptReq.getURL()
                        + "' is a GET request but it's descriptor has declared a readwrite transaction is required");
            }

            try {
                RetryingTransactionHelper transactionHelper = transactionService.getRetryingTransactionHelper();
                if (script instanceof LoginPost) {
                    //login script requires read-write transaction because of authorization intercepter
                    transactionHelper.setForceWritable(true);
                }
                transactionHelper.doInTransaction(work, readonly, requiresNew);
            } catch (TooBusyException e) {
                // Map TooBusyException to a 503 status code
                throw new WebScriptException(HttpServletResponse.SC_SERVICE_UNAVAILABLE, e.getMessage(), e);
            } finally {
                // Get rid of any temporary files
                if (bufferedReq != null) {
                    bufferedReq.close();
                }
            }

            // Ensure a response is always flushed after successful execution
            if (bufferedRes != null) {
                bufferedRes.writeResponse();
            }

        }
    } catch (IOException ioe) {
        Throwable socketException = ExceptionStackUtil.getCause(ioe, SocketException.class);
        Class<?> clientAbortException = null;
        try {
            clientAbortException = Class.forName("org.apache.catalina.connector.ClientAbortException");
        } catch (ClassNotFoundException e) {
            // do nothing
        }
        // Note: if you need to look for more exceptions in the stack, then create a static array and pass it in
        if ((socketException != null && socketException.getMessage().contains("Broken pipe"))
                || (clientAbortException != null
                        && ExceptionStackUtil.getCause(ioe, clientAbortException) != null)) {
            if (logger.isDebugEnabled()) {
                logger.warn("Client has cut off communication", ioe);
            } else {
                logger.info("Client has cut off communication");
            }
        } else {
            throw ioe;
        }
    }
}

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
 * //from  w  w w .ja v  a2s  .c o  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.ode.daohib.JotmTransactionFactory.java

/**
 * {@inheritDoc}/*from ww  w .j ava 2s  .  c o  m*/
 */
public boolean isTransactionInProgress(JDBCContext jdbcContext, Context transactionContext,
        Transaction transaction) {
    try {
        // Essentially:
        // 1) If we have a local (Hibernate) transaction in progress
        //      and it already has the UserTransaction cached, use that
        //      UserTransaction to determine the status.
        // 2) If a transaction manager has been located, use
        //      that transaction manager to determine the status.
        // 3) Finally, as the last resort, try to lookup the
        //      UserTransaction via JNDI and use that to determine the
        //      status.
        if (transaction != null) {
            UserTransaction ut = ((JotmTransaction) transaction).getUserTransaction();
            if (ut != null) {
                return JTAHelper.isInProgress(ut.getStatus());
            }
        }

        if (jdbcContext.getFactory().getTransactionManager() != null) {
            return JTAHelper.isInProgress(jdbcContext.getFactory().getTransactionManager().getStatus());
        } else {
            UserTransaction ut = getUserTransaction();
            return ut != null && JTAHelper.isInProgress(ut.getStatus());
        }
    } catch (SystemException se) {
        throw new TransactionException("Unable to check transaction status", se);
    }
}

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

/** Begins a transaction in the current thread IF transactions are available; only
 * tries if the current transaction status is ACTIVE, if not active it returns false.
 * If and on only if it begins a transaction it will return true. In other words, if
 * a transaction is already in place it will return false and do nothing.
 *//*from w  w  w  . ja v  a 2 s . c o m*/
public static boolean begin(int timeout) throws GenericTransactionException {
    UserTransaction ut = TransactionFactoryLoader.getInstance().getUserTransaction();
    if (ut != null) {
        try {
            int currentStatus = ut.getStatus();
            if (Debug.verboseOn()) {
                Debug.logVerbose("Current status : " + getTransactionStateString(currentStatus), module);
            }
            if (currentStatus == Status.STATUS_ACTIVE) {
                if (Debug.verboseOn()) {
                    Debug.logVerbose("Active transaction in place, so no transaction begun", module);
                }
                return false;
            } else if (currentStatus == Status.STATUS_MARKED_ROLLBACK) {
                Exception e = getTransactionBeginStack();
                if (e != null) {
                    Debug.logWarning(e,
                            "Active transaction marked for rollback in place, so no transaction begun; this stack trace shows when the exception began: ",
                            module);
                } else {
                    Debug.logWarning("Active transaction marked for rollback in place, so no transaction begun",
                            module);
                }

                RollbackOnlyCause roc = getSetRollbackOnlyCause();
                // do we have a cause? if so, throw special exception
                if (UtilValidate.isNotEmpty(roc)) {
                    throw new GenericTransactionException(
                            "The current transaction is marked for rollback, not beginning a new transaction and aborting current operation; the rollbackOnly was caused by: "
                                    + roc.getCauseMessage(),
                            roc.getCauseThrowable());
                } else {
                    return false;
                }
            }

            internalBegin(ut, timeout);

            // reset the transaction stamps, just in case...
            clearTransactionStamps();
            // initialize the start stamp
            getTransactionStartStamp();
            // set the tx begin stack placeholder
            setTransactionBeginStack();

            // initialize the debug resource
            if (debugResources()) {
                DebugXaResource dxa = new DebugXaResource();
                try {
                    dxa.enlist();
                } catch (XAException e) {
                    Debug.logError(e, module);
                }
            }

            return true;
        } catch (NotSupportedException e) {
            throw new GenericTransactionException(
                    "Not Supported error, could not begin transaction (probably a nesting problem)", e);
        } catch (SystemException e) {
            throw new GenericTransactionException("System error, could not begin transaction", e);
        }
    } else {
        if (Debug.infoOn())
            Debug.logInfo("No user transaction, so no transaction begun", module);
        return false;
    }
}