Example usage for org.springframework.transaction TransactionStatus isRollbackOnly

List of usage examples for org.springframework.transaction TransactionStatus isRollbackOnly

Introduction

In this page you can find the example usage for org.springframework.transaction TransactionStatus isRollbackOnly.

Prototype

boolean isRollbackOnly();

Source Link

Document

Return whether the transaction has been marked as rollback-only (either by the application or by the transaction infrastructure).

Usage

From source file:org.caratarse.auth.services.plugins.transactions.OpenTransactionPlugin.java

@Override
public void process(Request request, Response response) {
    TransactionStatus status = transaction.get();
    if (!status.isRollbackOnly()) {
        if (!status.isCompleted()) {
            transactionManager.commit(status);
        }/* w  ww  .  j  a  va  2  s. co m*/
    } else {
        if (!status.isCompleted()) {
            transactionManager.rollback(status);
        }
    }
}

From source file:org.nabucco.alfresco.enhScriptEnv.repo.script.batch.RepositoryExecuteBatchWorker.java

/**
 * //from w  ww .  j  a v  a2s.c  om
 * {@inheritDoc}
 */
@Override
public void process(final Object entry) throws Throwable {
    try {
        try {
            super.doProcess(entry);
        } catch (final WrappedException ex) {
            // super should already handle unwrap runtime exceptions
            final Throwable wrappedException = ex.getWrappedException();
            if (wrappedException instanceof RuntimeException) {
                // super should have handled this
                throw (RuntimeException) wrappedException;
            }
            throw new AlfrescoRuntimeException(wrappedException.getMessage(), wrappedException);
        } catch (final Throwable ex) {
            throw new AlfrescoRuntimeException(ex.getMessage(), ex);
        }
    } catch (final Throwable ex) {
        /*
         * The TxnCallback does not propagate non-retryable exceptions to the retrying transaction handler. Some exceptions may be
         * caused by execution of the provided script callback without passing through a service with its transaction interceptor which
         * would mark the transaction for rollback. We have to mark the transaction for rollback manually otherwise we end up with
         * commits of partial changes from the batch. (rollback on any exception is the default behaviour of Alfresco
         * SpringAwareUserTransaction)
         */

        final RuleBasedTransactionAttribute transactionAttribute = new RuleBasedTransactionAttribute();
        transactionAttribute.setReadOnly(true);
        transactionAttribute.setPropagationBehavior(TransactionDefinition.PROPAGATION_MANDATORY);

        final TransactionStatus transaction = this.txnManager.getTransaction(transactionAttribute);
        if (!transaction.isRollbackOnly()) {
            LOGGER.debug("Marking transaction as rollback-only due to exception during batch processing", ex);
            transaction.setRollbackOnly();
        }

        throw ex;
    }
}

From source file:org.nabucco.alfresco.enhScriptEnv.repo.script.batch.RepositoryExecuteBatchWorker.java

/**
 * // w w  w  . ja v  a 2s.c om
 * {@inheritDoc}
 */
@Override
public void afterProcess() throws Throwable {
    try {
        try {
            super.doAfterProcess();
        } catch (final WrappedException ex) {
            // super should already handle unwrap runtime exceptions
            final Throwable wrappedException = ex.getWrappedException();
            if (wrappedException instanceof RuntimeException) {
                // super should have handled this
                throw (RuntimeException) wrappedException;
            }
            throw new AlfrescoRuntimeException(wrappedException.getMessage(), wrappedException);
        } catch (final Throwable ex) {
            throw new AlfrescoRuntimeException(ex.getMessage(), ex);
        } finally {
            // cleanup execution context
            AuthenticationUtil.clearCurrentSecurityContext();
            AuthenticationUtil.popAuthentication();

            I18NUtil.setLocale(null);
            I18NUtil.setContentLocale(null);
        }
    } catch (final Throwable ex) {
        /*
         * The TxnCallback does not propagate non-retryable exceptions to the retrying transaction handler. Some exceptions may be
         * caused by execution of the provided script callback without passing through a service with its transaction interceptor which
         * would mark the transaction for rollback. We have to mark the transaction for rollback manually otherwise we end up with
         * commits of partial changes from the batch. (rollback on any exception is the default behaviour of Alfresco
         * SpringAwareUserTransaction)
         */

        final RuleBasedTransactionAttribute transactionAttribute = new RuleBasedTransactionAttribute();
        transactionAttribute.setReadOnly(true);
        transactionAttribute.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);

        // this never creates a new "real" transaction due to our propagation behavior
        final TransactionStatus transaction = this.txnManager.getTransaction(transactionAttribute);
        try {
            if (!transaction.isRollbackOnly()) {
                LOGGER.debug("Marking transaction as rollback-only due to exception during batch processing",
                        ex);
                transaction.setRollbackOnly();
            }
        } finally {
            // this never actually commits a "real" transaction - it just clears transaction synchronizations
            this.txnManager.commit(transaction);
        }

        throw ex;
    }
}

From source file:org.nabucco.alfresco.enhScriptEnv.repo.script.batch.RepositoryExecuteBatchWorker.java

/**
 * //from  www.  j  a  v  a  2  s.co  m
 * {@inheritDoc}
 */
@Override
public void beforeProcess() throws Throwable {
    // prepare execution context
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(this.fullyAuthenticatedUser);
    if (this.runAsUser != null && !this.runAsUser.equals(this.fullyAuthenticatedUser)) {
        AuthenticationUtil.setRunAsUser(this.runAsUser);
    }

    I18NUtil.setLocale(this.locale);
    if (this.contentLocale != null) {
        I18NUtil.setContentLocale(this.contentLocale);
    }

    try {
        try {
            super.doBeforeProcess();
        } catch (final WrappedException ex) {
            // super should already handle unwrap runtime exceptions
            final Throwable wrappedException = ex.getWrappedException();
            if (wrappedException instanceof RuntimeException) {
                // super should have handled this
                throw (RuntimeException) wrappedException;
            }
            throw new AlfrescoRuntimeException(wrappedException.getMessage(), wrappedException);
        } catch (final Throwable ex) {
            throw new AlfrescoRuntimeException(ex.getMessage(), ex);
        }
    } catch (final Throwable ex) {
        /*
         * The TxnCallback does not propagate non-retryable exceptions to the retrying transaction handler. Some exceptions may be
         * caused by execution of the provided script callback without passing through a service with its transaction interceptor which
         * would mark the transaction for rollback. We have to mark the transaction for rollback manually otherwise we end up with
         * commits of partial changes from the batch. (rollback on any exception is the default behaviour of Alfresco
         * SpringAwareUserTransaction)
         */

        final RuleBasedTransactionAttribute transactionAttribute = new RuleBasedTransactionAttribute();
        transactionAttribute.setReadOnly(true);
        transactionAttribute.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);

        // this never creates a new "real" transaction due to our propagation behavior
        final TransactionStatus transaction = this.txnManager.getTransaction(transactionAttribute);
        try {
            if (!transaction.isRollbackOnly()) {
                LOGGER.debug("Marking transaction as rollback-only due to exception during batch processing",
                        ex);
                transaction.setRollbackOnly();
            }
        } finally {
            // this never actually commits a "real" transaction - it just clears transaction synchronizations
            this.txnManager.commit(transaction);
        }

        throw ex;
    }
}

From source file:org.brixcms.rmiserver.boot.Bootstrapper.java

public void bootstrap() throws Exception {
    logger.info("Bootstrapper executing");

    // create schema if necessary
    Session session = sessionFactory.openSession();
    try {//  w w w .j  ava2  s . c  om
        session.createCriteria(User.class).setMaxResults(1).list();
        logger.info("Bootstrapper found schema, skipping schema creation");
    } catch (HibernateException e) {
        logger.info("Bootstrapper did not find schema");

        TransactionStatus txn = transactionManager.getTransaction(new DefaultTransactionDefinition());
        try {
            logger.info("creating schema...");
            bootstrapSchema();
            logger.info("creating default admin user...");
            bootstrapUsers();
        } finally {
            if (txn.isRollbackOnly()) {
                transactionManager.rollback(txn);
            } else {
                transactionManager.commit(txn);
            }
        }
    } finally {
        session.close();
    }

    logger.info("Bootstrapper execution completed");
}

From source file:com.eclecticlogic.pedal.impl.TransactionImpl.java

public <R> R _exec(Function<Context, R> runner) {
    TransactionStatus status = null;
    try {/*from  w  w  w . ja  va2  s .  com*/
        status = getPlatformTransactionManager().getTransaction(getTransactionDefinition());
        logger.trace("start: new = {}", status.isNewTransaction() ? "yes" : "no");

        Context context = new ContextImpl();

        R retval = runner.apply(context);

        if (status.isRollbackOnly()) {
            getPlatformTransactionManager().rollback(status);
            logger.trace("rollback");
        } else {
            getPlatformTransactionManager().commit(status);
            logger.trace("commit");
        }

        return retval;
    } catch (RuntimeException e) {
        if (status != null && status.isCompleted() == false) {
            getPlatformTransactionManager().rollback(status);
            logger.trace("rollback");
        }
        throw e;
    }
}

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

/**
 * This status is a combination of the internal status, as recorded during explicit operations,
 * and the status provided by the Spring support.
 * /*from  www .  j  av  a 2s.co  m*/
 * @see Status
 */
public synchronized int getStatus() throws SystemException {
    TransactionInfo txnInfo = getTransactionInfo();

    // if the txn info is null, then we are outside a transaction
    if (txnInfo == null) {
        return internalStatus; // this is checked in getTransactionInfo
    }

    // normally the internal status is correct, but we only need to double check
    // for the case where the transaction was marked for rollback, or rolledback
    // in a deeper transaction
    TransactionStatus txnStatus = txnInfo.getTransactionStatus();
    if (internalStatus == Status.STATUS_ROLLEDBACK) {
        // explicitly rolled back at some point
        return internalStatus;
    } else if (txnStatus.isRollbackOnly()) {
        // marked for rollback at some point in the stack
        return Status.STATUS_MARKED_ROLLBACK;
    } else {
        // just rely on the internal status
        return internalStatus;
    }
}

From source file:org.ambraproject.struts2.TransactionInterceptor.java

public String intercept(final ActionInvocation actionInvocation) throws Exception {

    final Action action = (Action) actionInvocation.getAction();
    final ActionProxy actionProxy = actionInvocation.getProxy();
    final String methodName = actionProxy.getMethod();

    if (getAnnotation(action.getClass(), methodName, ManualTransactionManagement.class) != null) {
        //Method is annotated tellling us not to manage a transaction for it
        log.debug(/*  w  ww. j  a v a  2 s.  c om*/
                "Not managing transaction for " + action.getClass().getSimpleName() + "." + methodName + "()");
        return actionInvocation.invoke();
    }

    if (log.isDebugEnabled()) {
        log.debug("Intercepted " + action.getClass().getSimpleName() + "." + methodName + "()");
    }

    final Transactional transactionalAnnotation = getAnnotation(action.getClass(), methodName,
            Transactional.class);
    TransactionTemplate txTemplate = new TransactionTemplate(transactionManager);
    if (transactionalAnnotation != null) {
        txTemplate.setReadOnly(transactionalAnnotation.readOnly());
        txTemplate.setTimeout(transactionalAnnotation.timeout());
        txTemplate.setIsolationLevel(transactionalAnnotation.isolation().value());
        txTemplate.setPropagationBehavior(transactionalAnnotation.propagation().value());
    }

    CallbackResult callbackResult = (CallbackResult) txTemplate.execute(new TransactionCallback() {
        public CallbackResult doInTransaction(TransactionStatus transactionStatus) {
            CallbackResult result = new CallbackResult();
            try {
                String actionResult = actionInvocation.invoke();
                result.setResult(actionResult);
                //Rollback for Action responses indicating failure
                for (String response : new String[] { Action.ERROR, Action.INPUT, Action.LOGIN }) {
                    if (response.equalsIgnoreCase(actionResult) && !transactionStatus.isRollbackOnly()) {
                        log.debug("Rolling back action " + action.getClass().getSimpleName()
                                + " due to result: " + actionResult);
                        transactionStatus.setRollbackOnly();
                        break;
                    }
                }
            } catch (Exception e) {
                /*
                * Callback does not throw exception. We need to pass Exception object in the return
                * parameter so we can throw it in the calling method.
                */
                boolean noRollback = false;

                if (transactionalAnnotation != null && transactionalAnnotation.noRollbackFor() != null) {
                    for (Class<? extends Throwable> exception : transactionalAnnotation.noRollbackFor()) {
                        if (exception.isInstance(e)) {
                            noRollback = true;
                            break;
                        }
                    }
                }

                if (!noRollback && transactionalAnnotation != null
                        && transactionalAnnotation.rollbackFor() != null) {
                    for (Class<? extends Throwable> exception : transactionalAnnotation.rollbackFor()) {
                        if (exception.isInstance(e)) {
                            log.debug("Caught exception, rolling back action invocation "
                                    + action.getClass().getSimpleName());
                            transactionStatus.setRollbackOnly();
                            break;
                        }
                    }
                }
                result.setException(e);
            }
            return result;
        }
    });

    if (callbackResult.getException() != null)
        throw callbackResult.getException();

    return callbackResult.getResult();
}

From source file:com.opensymphony.able.filter.SimpleTransactionServletFilter.java

public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {
    // TODO we could get clever and figure out what URIs are read only transactions etc
    final TransactionTemplate transactionTemplate = (TransactionTemplate) context
            .getBean("transactionTemplate");
    transactionTemplate.setReadOnly(false);

    if (log.isDebugEnabled()) {
        log.debug("Starting a transaction");
    }/*from  w  ww. ja  v a 2 s. co m*/

    try {
        Exception e = (Exception) transactionTemplate.execute(new TransactionCallback() {

            public Object doInTransaction(TransactionStatus status) {
                try {
                    TransactionOutcome outcome = new TransactionOutcome(status, transactionTemplate);
                    TransactionOutcome.setTransactionOutcome(outcome);
                    filterChain.doFilter(request, response);

                    if (outcome.isRollbackOnly()) {
                        log.debug("Outcome is rollback");
                        status.setRollbackOnly();
                    }

                    if (log.isDebugEnabled()) {
                        log.debug("Completing a transaction with rollback: " + status.isRollbackOnly());
                    }
                    return null;
                } catch (RuntimeException e) {
                    throw e;
                } catch (Exception e) {
                    return e;
                }
            }
        });

        if (log.isDebugEnabled()) {
            log.debug("End transaction with exception: " + e);
        }

        if (e instanceof IOException) {
            throw (IOException) e;
        } else if (e instanceof ServletException) {
            throw (ServletException) e;
        } else if (e != null) {
            throw new ServletException(e);
        }
    } catch (TransactionException e) {
        Throwable cause = e.getCause();
        if (cause.getCause() != null) {
            cause = cause.getCause();
        }
        ;
        if (cause instanceof JDBCException) {
            JDBCException jdbcException = (JDBCException) cause;
            SQLException sqlException = jdbcException.getSQLException();
            throw new ServletException("Failed to execute: " + jdbcException.getSQL() + ": error: "
                    + sqlException.getSQLState() + ". Reason: " + sqlException, sqlException);
        }
        throw new ServletException(cause);
    } finally {
        TransactionOutcome.setTransactionOutcome(null);
    }
}

From source file:com.opensymphony.able.filter.TransactionServletFilter.java

public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {
    // TODO we could get clever and figure out what URIs are read only transactions etc
    TransactionTemplate transactionTemplate = (TransactionTemplate) context.getBean("transactionTemplate");
    transactionTemplate.setReadOnly(false);

    if (log.isDebugEnabled()) {
        log.debug("Starting a transaction");
    }//from w  w  w . j  a  v  a  2  s.c o  m

    PlatformTransactionManager transactionManager = transactionTemplate.getTransactionManager();
    TransactionStatus status = transactionManager.getTransaction(transactionTemplate);
    TransactionOutcome outcome = new TransactionOutcome(status, transactionTemplate);
    request.setAttribute(TRANSACTION_OUTCOME, outcome);

    Exception exception = null;
    try {
        filterChain.doFilter(request, response);
        status = transactionManager.getTransaction(transactionTemplate);
    } catch (Exception e) {
        exception = e;
        log.warn("Caught: " + e, e);
    }

    if (outcome.isRollbackOnly() || exception != null) {
        status.setRollbackOnly();
    }

    try {
        if (status.isRollbackOnly()) {
            log.debug("Rolling back transaction");
            transactionManager.rollback(status);
        } else {
            log.debug("Committing transaction");
            transactionManager.commit(status);
        }
    } catch (TransactionException e) {
        if (exception == null) {
            exception = e;
        } else {
            log.debug("Failed to rollback transaction: " + e, e);
        }
    }

    if (exception instanceof IOException) {
        throw (IOException) exception;
    } else if (exception instanceof ServletException) {
        throw (ServletException) exception;
    } else if (exception != null) {
        throw new ServletException(exception);
    }
}