Example usage for javax.transaction UserTransaction rollback

List of usage examples for javax.transaction UserTransaction rollback

Introduction

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

Prototype

void rollback() throws IllegalStateException, SecurityException, SystemException;

Source Link

Document

Roll back the transaction associated with the current thread.

Usage

From source file:org.nuxeo.apidoc.browse.Distribution.java

@POST
@Path("save")
@Produces("text/html")
public Object doSave() throws NamingException, NotSupportedException, SystemException, RollbackException,
        HeuristicMixedException, HeuristicRollbackException, ParseException {
    if (!canAddDocumentation()) {
        return null;
    }// ww w .j a va2  s  . c  om
    FormData formData = getContext().getForm();
    String distribLabel = formData.getString("name");

    log.info("Start Snapshot...");
    boolean startedTx = false;
    UserTransaction tx = TransactionHelper.lookupUserTransaction();
    if (tx != null && !TransactionHelper.isTransactionActiveOrMarkedRollback()) {
        tx.begin();
        startedTx = true;
    }

    Map<String, Serializable> otherProperties = readFormData(formData);
    try {
        getSnapshotManager().persistRuntimeSnapshot(getContext().getCoreSession(), distribLabel,
                otherProperties);

    } catch (NuxeoException e) {
        log.error("Error during storage", e);
        if (tx != null) {
            tx.rollback();
        }
        return getView("savedKO").arg("message", e.getMessage());
    }
    log.info("Snapshot saved.");
    if (tx != null && startedTx) {
        tx.commit();
    }

    String redirectUrl = getContext().getBaseURL() + getPath();
    log.debug("Path => " + redirectUrl);
    return getView("saved");
}

From source file:org.nuxeo.apidoc.browse.Distribution.java

@POST
@Path("saveExtended")
@Produces("text/html")
public Object doSaveExtended() throws NamingException, NotSupportedException, SystemException,
        SecurityException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
    if (!canAddDocumentation()) {
        return null;
    }//from  w w  w .j  ava2  s. c  o  m

    FormData formData = getContext().getForm();

    String distribLabel = formData.getString("name");
    String bundleList = formData.getString("bundles");
    String pkgList = formData.getString("packages");
    SnapshotFilter filter = new SnapshotFilter(distribLabel);

    if (bundleList != null) {
        String[] bundles = bundleList.split("\n");
        for (String bundleId : bundles) {
            filter.addBundlePrefix(bundleId);
        }
    }

    if (pkgList != null) {
        String[] packages = pkgList.split("\\r?\\n");
        for (String pkg : packages) {
            filter.addPackagesPrefix(pkg);
        }
    }

    Map<String, Serializable> otherProperties = readFormData(formData);

    log.info("Start Snapshot...");
    boolean startedTx = false;
    UserTransaction tx = TransactionHelper.lookupUserTransaction();
    if (tx != null && !TransactionHelper.isTransactionActiveOrMarkedRollback()) {
        tx.begin();
        startedTx = true;
    }
    try {
        getSnapshotManager().persistRuntimeSnapshot(getContext().getCoreSession(), distribLabel,
                otherProperties, filter);
    } catch (NuxeoException e) {
        log.error("Error during storage", e);
        if (tx != null) {
            tx.rollback();
        }
        return getView("savedKO").arg("message", e.getMessage());
    }
    log.info("Snapshot saved.");
    if (tx != null && startedTx) {
        tx.commit();
    }
    return getView("saved");
}

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

/**
 * Commits or rolls back the User Transaction depending on the transaction status.
 *//*from   w  w  w .j a va2s.co  m*/
public static void commitOrRollbackTransaction() {
    UserTransaction ut = NuxeoContainer.getUserTransaction();
    if (ut == null) {
        return;
    }
    try {
        int status = ut.getStatus();
        if (status == Status.STATUS_ACTIVE) {
            if (log.isDebugEnabled()) {
                log.debug("Commiting transaction");
            }
            ut.commit();
        } else if (status == Status.STATUS_MARKED_ROLLBACK) {
            if (log.isDebugEnabled()) {
                log.debug("Cannot commit transaction because it is marked rollback only");
            }
            ut.rollback();
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Cannot commit transaction with unknown status: " + status);
            }
        }
    } catch (SystemException | RollbackException | HeuristicMixedException | HeuristicRollbackException
            | IllegalStateException | SecurityException e) {
        String msg = "Unable to commit/rollback";
        String message = e.getMessage();
        if (e instanceof RollbackException) {
            switch (message) {
            case "Unable to commit: transaction marked for rollback":
                // don't log as error, this happens if there's a ConcurrentModificationException
                // at transaction end inside VCS
            case "Unable to commit: Transaction timeout":
                // don't log either
                log.debug(msg, e);
                break;
            default:
                log.error(msg, e);
            }
        } else {
            log.error(msg, e);
        }
        throw new TransactionRuntimeException(msg + ": " + message, e);
    }
}

From source file:org.quartz.plugins.SchedulerPluginWithUserTransactionSupport.java

/**
 * If the given UserTransaction is not null, it is committed/rolledback,
 * and then returned to the UserTransactionHelper.
 *//*from ww w.j  av  a  2  s .  c  o  m*/
private void resolveUserTransaction(UserTransaction userTransaction) {
    if (userTransaction != null) {
        try {
            if (userTransaction.getStatus() == Status.STATUS_MARKED_ROLLBACK) {
                userTransaction.rollback();
            } else {
                userTransaction.commit();
            }
        } catch (Throwable t) {
            getLog().error("Failed to resolve UserTransaction for plugin: " + getName(), t);
        } finally {
            UserTransactionHelper.returnUserTransaction(userTransaction);
        }
    }
}

From source file:org.tolven.web.servlet.InternalErrorHandleServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //check if a transaction is already started, if not redirect to the servlet
    UserTransaction ut = null;
    try {//from   w ww  .  j av a 2 s  .com
        ut = (UserTransaction) ctx.lookup("UserTransaction");
        if (ut.getStatus() != Status.STATUS_ACTIVE) {
            ut.begin();
        }
        //check if the error.email is configured. If found send an email
        Object accountUser = TolvenRequest.getInstance().getAccountUser();
        if (accountUser != null) {
            String errorEmail = ((AccountUser) accountUser).getAccount().getProperty()
                    .get("org.tolven.error.email.to");
            if (!StringUtils.isBlank(errorEmail)) {
                System.out.println("Send an email to " + errorEmail);
            }
        }
        if (ut != null) {
            ut.commit();
        }
        RequestDispatcher dispatcher = this.config.getServletContext().getRequestDispatcher("/error.jsp");
        if (dispatcher != null)
            dispatcher.forward(req, resp);
    } catch (Exception e) {
        throw new ServletException("Exception thrown in InternalErrorHandleServlet", e);
    } finally {
        if (ut != null) {
            try {
                ut.rollback();
            } catch (Exception e) {
                throw new ServletException("Exception thrown in InternalErrorHandleServlet", e);
            }
        }
    }
}

From source file:org.wso2.carbon.bpmn.extensions.jms.JMSMessageSender.java

/**
 * Perform actual send of JMS message to the Destination selected
 *
 * @param message the JMS message//ww w  .j a  v  a 2 s . c  o m
 */
public void send(Message message, MessageContext msgCtx) {

    Boolean jtaCommit = null;
    Boolean rollbackOnly = null;
    Boolean persistent = null;
    Integer priority = null;
    Integer timeToLive = null;
    if (msgCtx != null) {

        jtaCommit = getBooleanProperty(msgCtx, BaseConstants.JTA_COMMIT_AFTER_SEND);
        rollbackOnly = getBooleanProperty(msgCtx, BaseConstants.SET_ROLLBACK_ONLY);
        persistent = getBooleanProperty(msgCtx, JMSConstants.JMS_DELIVERY_MODE);
        priority = getIntegerProperty(msgCtx, JMSConstants.JMS_PRIORITY);
        timeToLive = getIntegerProperty(msgCtx, JMSConstants.JMS_TIME_TO_LIVE);

    }
    // Do not commit, if message is marked for rollback
    if (rollbackOnly != null && rollbackOnly) {
        jtaCommit = Boolean.FALSE;
    }

    if (persistent != null) {
        try {
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        } catch (JMSException e) {
            log.error("Error setting JMS Producer for PERSISTENT delivery", e);
        }
    }
    if (priority != null) {
        try {
            producer.setPriority(priority);
        } catch (JMSException e) {
            log.error("Error setting JMS Producer priority to : " + priority, e);
        }
    }
    if (timeToLive != null) {
        try {
            producer.setTimeToLive(timeToLive);
        } catch (JMSException e) {
            log.error("Error setting JMS Producer TTL to : " + timeToLive, e);
        }
    }

    boolean sendingSuccessful = false;
    // perform actual message sending
    log.info("sending JMS message..");
    try {
        if (isQueue == null) {
            producer.send(message);

        } else {
            if (isQueue) {
                try {
                    ((QueueSender) producer).send(message);
                } catch (JMSException e) {
                    createTempQueueConsumer();
                    ((QueueSender) producer).send(message);
                }

            } else {
                try {
                    ((TopicPublisher) producer).publish(message);
                } catch (JMSException e) {
                    createTempTopicSubscriber();
                    ((TopicPublisher) producer).publish(message);
                }
            }
        }

        // set the actual MessageID to the message context for use by any others down the line
        //String msgId = null;
        //            try {
        //                msgId = message.getJMSMessageID();
        //                if (msgId != null) {
        //                    msgCtx.setProperty(JMSConstants.JMS_MESSAGE_ID, msgId);
        //                }
        //            } catch (JMSException ignore) {}

        sendingSuccessful = true;
        log.info("Message sent");

        //            if (log.isDebugEnabled()) {
        //                log.debug("Sent Message Context ID : " + msgCtx.getMessageID() +
        //                        " with JMS Message ID : " + msgId +
        //                        " to destination : " + producer.getDestination());
        //            }

    } catch (JMSException e) {
        log.error("Error sending message to destination : " + destination, e);

    } finally {

        if (jtaCommit != null) {

            UserTransaction ut = (UserTransaction) msgCtx.getProperty(BaseConstants.USER_TRANSACTION);
            if (ut != null) {

                try {
                    if (sendingSuccessful && jtaCommit) {
                        ut.commit();
                    } else {
                        ut.rollback();
                    }
                    msgCtx.removeProperty(BaseConstants.USER_TRANSACTION);

                    if (log.isDebugEnabled()) {
                        log.debug((sendingSuccessful ? "Committed" : "Rolled back") + " JTA Transaction");
                    }

                } catch (Exception e) {
                    log.error("Error committing/rolling back JTA transaction after "
                            + "sending of message with MessageContext ID : " + msgCtx.getMessageID()
                            + " to destination : " + destination, e);
                }
            }

        } else {
            try {
                if (session.getTransacted()) {
                    if (sendingSuccessful && (rollbackOnly == null || !rollbackOnly)) {
                        session.commit();
                    } else {
                        session.rollback();
                    }
                }

                if (log.isDebugEnabled()) {
                    log.debug((sendingSuccessful ? "Committed" : "Rolled back")
                            + " local (JMS Session) Transaction");
                }

            } catch (JMSException e) {
                log.error("Error committing/rolling back local (i.e. session) "
                        + "transaction after sending of message with MessageContext ID : "
                        + msgCtx.getMessageID() + " to destination : " + destination, e);
            }
        }
    }
}

From source file:org.xchain.namespaces.jta.TransactionCommand.java

public boolean execute(JXPathContext context) throws Exception {
    boolean managingTransaction = false;
    boolean result = false;
    UserTransaction transaction = ContainerContext.getJtaLookupStrategy().getUserTransaction();

    if (transaction != null) {
        try {/* w ww. j a v  a2 s . c  om*/
            // if there is not a transaction running, then start one.
            if (Status.STATUS_ACTIVE != transaction.getStatus()) {
                managingTransaction = true;
                transaction.setTransactionTimeout(this.getTimeout(context));
                transaction.begin();
            }

            // put the transaction into the context.
            ((ScopedQNameVariables) context.getVariables()).declareVariable(getResult(context), transaction,
                    Scope.execution);

            // execute the chain 
            result = super.execute(context);

            // roll back the transaction.
            if (managingTransaction) {
                transaction.commit();
            }
        } catch (Exception e) {
            if (managingTransaction) {
                if (transaction.getStatus() != Status.STATUS_NO_TRANSACTION) {
                    transaction.rollback();
                }
            }
            throw e;
        } finally {
            // TODO: If we defined the transaction variable, then we should remove it.
        }
    } else {
        // TODO: Should this throw an IllegalStateException?  Returning true seems like the wrong behavior.
        result = true;
    }
    return result;
}