Example usage for javax.transaction UserTransaction setRollbackOnly

List of usage examples for javax.transaction UserTransaction setRollbackOnly

Introduction

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

Prototype

void setRollbackOnly() throws IllegalStateException, SystemException;

Source Link

Document

Modify the transaction associated with the current thread such that the only possible outcome of the transaction is to roll back the transaction.

Usage

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. 
 *///  www  . j ava 2 s. c o  m
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.transfer.AbstractManifestProcessorBase.java

private void handleException(TransferManifestNode node, Throwable ex) {
    try {/*w  w  w . j  a  va  2s  . com*/
        UserTransaction tx = RetryingTransactionHelper.getActiveUserTransaction();
        if (tx != null) {
            tx.setRollbackOnly();
            log.debug("Successfully marked transaction for rollback.");
        }
    } catch (Throwable e) {
        //Nothing really to be done here
        log.warn("Failed to mark transaction as rollback-only in response to an error", e);
    }

    try {
        TransferProgressMonitor monitor = receiver.getProgressMonitor();
        String message = (node != null) ? "Error while processing incoming node " + node.getNodeRef()
                : "Error processing commit";

        monitor.logException(transferId, message, ex);
    } catch (Throwable t) {
        //Nothing really to be done here
        log.warn("Failed to record exception in transfer log due to an exception", t);
    }

    //Any non-fatal transfer exception is logged and then skipped - the transfer continues 
    //(albeit with a guaranteed rollback at the end).
    //A fatal transfer exception is rethrown and causes the transfer to end immediately.
    //Any non-transfer exception is assumed to be fatal, so is wrapped in a fatal exception
    //and thrown.
    if (TransferFatalException.class.isAssignableFrom(ex.getClass())) {
        callLocalExceptionHandler(node, ex);
        throw (TransferFatalException) ex;
    } else if (!TransferException.class.isAssignableFrom(ex.getClass())) {
        callLocalExceptionHandler(node, ex);
        throw new TransferFatalException(MSG_ERROR_WHILE_COMMITTING_TRANSFER, ex);
    }
}

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 .  j a v a2  s  .co m*/
@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
 * /*from  w  w  w.j  a v a2s.  co m*/
 * @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.apache.ofbiz.entity.transaction.TransactionUtil.java

/** Makes a rollback the only possible outcome of the transaction in the current thread IF transactions are available */
public static void setRollbackOnly(String causeMessage, Throwable causeThrowable)
        throws GenericTransactionException {
    UserTransaction ut = TransactionFactoryLoader.getInstance().getUserTransaction();
    if (ut != null) {
        try {//from   ww  w  . j  a  va2  s .  c  om
            int status = ut.getStatus();
            Debug.logVerbose("Current code : " + getTransactionStateString(status), module);

            if (status != STATUS_NO_TRANSACTION) {
                if (status != STATUS_MARKED_ROLLBACK) {
                    if (Debug.warningOn()) {
                        Debug.logWarning(new Exception(causeMessage),
                                "Calling transaction setRollbackOnly; this stack trace shows where this is happening:",
                                module);
                    }
                    ut.setRollbackOnly();
                    setSetRollbackOnlyCause(causeMessage, causeThrowable);
                } else {
                    Debug.logInfo("Transaction rollback only not set, rollback only is already set.", module);
                }
            } else {
                Debug.logWarning("Transaction rollback only not set, status is STATUS_NO_TRANSACTION", module);
            }
        } catch (IllegalStateException e) {
            Throwable t = e.getCause() == null ? e : e.getCause();
            throw new GenericTransactionException(
                    "Could not set rollback only on transaction, IllegalStateException exception: "
                            + t.toString(),
                    t);
        } catch (SystemException e) {
            Throwable t = e.getCause() == null ? e : e.getCause();
            throw new GenericTransactionException(
                    "System error, could not set rollback only on transaction: " + t.toString(), t);
        }
    } else {
        Debug.logInfo("No UserTransaction, transaction rollback only not set", module);
    }
}

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

/**
 * Makes a rollback the only possible outcome of the transaction in the
 * current thread IF transactions are available
 *//*from  w  ww.ja va  2  s  .c o  m*/
public static void setRollbackOnly(String causeMessage, Throwable causeThrowable)
        throws GenericTransactionException {
    UserTransaction ut = TransactionFactory.getUserTransaction();
    if (ut != null) {
        try {
            int status = ut.getStatus();
            logger.debug(
                    "[TransactionUtil.setRollbackOnly] current code : " + getTransactionStateString(status));

            if (status != STATUS_NO_TRANSACTION) {
                if (status != STATUS_MARKED_ROLLBACK) {
                    if (logger.isWarnEnabled()) {
                        logger.warn(
                                "[TransactionUtil.setRollbackOnly] Calling transaction setRollbackOnly; this stack trace shows where this is happening:",
                                new Exception(causeMessage));
                    }
                    ut.setRollbackOnly();
                    setSetRollbackOnlyCause(causeMessage, causeThrowable);
                } else {
                    logger.info(
                            "[TransactionUtil.setRollbackOnly] transaction rollback only not set, rollback only is already set.");
                }
            } else {
                logger.warn(
                        "[TransactionUtil.setRollbackOnly] transaction rollback only not set, status is STATUS_NO_TRANSACTION");
            }
        } catch (IllegalStateException e) {
            Throwable t = e.getCause() == null ? e : e.getCause();
            throw new GenericTransactionException(
                    "Could not set rollback only on transaction, IllegalStateException exception: "
                            + t.toString(),
                    t);
        } catch (SystemException e) {
            Throwable t = e.getCause() == null ? e : e.getCause();
            throw new GenericTransactionException(
                    "System error, could not set rollback only on transaction: " + t.toString(), t);
        }
    } else {
        logger.info("[TransactionUtil.setRollbackOnly] No UserTransaction, transaction rollback only not set");
    }
}

From source file:org.nuxeo.runtime.transaction.TransactionHelper.java

/**
 * Sets the current User Transaction as rollback only.
 *
 * @return {@code true} if the transaction was successfully marked rollback only, {@code false} otherwise
 *//*from   w w w.j a v  a  2 s  . co m*/
public static boolean setTransactionRollbackOnly() {
    if (log.isDebugEnabled()) {
        log.debug("Setting transaction as rollback only");
        if (log.isTraceEnabled()) {
            log.trace("Rollback stack trace", new Throwable("Rollback stack trace"));
        }
    }
    UserTransaction ut = NuxeoContainer.getUserTransaction();
    if (ut == null) {
        return false;
    }
    try {
        ut.setRollbackOnly();
        return true;
    } catch (IllegalStateException | SystemException cause) {
        log.error("Could not mark transaction as rollback only", cause);
    }
    return false;
}