Example usage for javax.transaction UserTransaction commit

List of usage examples for javax.transaction UserTransaction commit

Introduction

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

Prototype

void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException,
        IllegalStateException, SystemException;

Source Link

Document

Complete the transaction associated with the current thread.

Usage

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 . ja va  2s. c om

    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 ww  . j  av  a2 s.  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.obm.push.backend.obm22.mail.EmailCacheStorage.java

private void updateDbCache(BackendSession bs, Integer devId, Integer collectionId, final Set<Long> data)
        throws SQLException {
    Set<Long> toRemove = new HashSet<Long>();
    Set<Long> oldUids = loadMailFromDb(bs, devId, collectionId);
    if (oldUids != null) {
        toRemove.addAll(oldUids);//from www.  j  ava 2s .  c o m
        toRemove.removeAll(data);
    }

    Set<Long> toInsert = new HashSet<Long>();
    toInsert.addAll(data);
    if (oldUids != null) {
        toInsert.removeAll(oldUids);
    }

    if (toRemove.size() == 0 && toInsert.size() == 0) {
        return;
    }

    PreparedStatement del = null;
    PreparedStatement insert = null;

    if (logger.isDebugEnabled()) {
        logger.debug(debugName + " should run a batch with " + toRemove.size() + " deletions & "
                + toInsert.size() + " insertions.");
    }
    Connection con = null;
    UserTransaction ut = getUserTransaction();
    try {
        ut.begin();
        con = OBMPoolActivator.getDefault().getConnection();
        del = con.prepareStatement(
                "DELETE FROM opush_sync_mail WHERE collection_id=? AND device_id=? AND mail_uid=?");
        for (Long l : toRemove) {
            del.setInt(1, collectionId);
            del.setInt(2, devId);
            del.setInt(3, l.intValue());
            del.addBatch();
        }
        del.executeBatch();

        insert = con.prepareStatement(
                "INSERT INTO opush_sync_mail (collection_id, device_id, mail_uid) VALUES (?, ?, ?)");
        for (Long l : toInsert) {
            insert.setInt(1, collectionId);
            insert.setInt(2, devId);
            insert.setInt(3, l.intValue());
            insert.addBatch();
        }
        insert.executeBatch();
        ut.commit();
    } catch (Throwable e) {
        logger.error(e.getMessage(), e);
        JDBCUtils.rollback(con);
    } finally {
        JDBCUtils.cleanup(null, del, null);
        JDBCUtils.cleanup(con, insert, null);
    }
}

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.
 */// w w w  .  j  av a2  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 w w  . ja v  a2s. 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//from   w  w  w . j  a va 2  s.  c om
 */
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 {// ww w .j a va 2 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;
}

From source file:ru.runa.wfe.commons.logic.InitializerLogic.java

/**
 * Initialize database./*from w ww .ja v a2s . c o  m*/
 * 
 * @param daoHolder
 *            Helper object for getting DAO's.
 */
protected void initializeDatabase(UserTransaction transaction) {
    log.info("database is not initialized. initializing...");
    SchemaExport schemaExport = new SchemaExport(ApplicationContextFactory.getConfiguration());
    schemaExport.create(true, true);
    try {
        transaction.begin();
        insertInitialData();
        constantDAO.setDatabaseVersion(dbPatches.size());
        transaction.commit();
    } catch (Throwable th) {
        Utils.rollbackTransaction(transaction);
        throw Throwables.propagate(th);
    }
}

From source file:ru.runa.wfe.commons.logic.InitializerLogic.java

/**
 * Apply patches to initialized database.
 */// ww  w .java  2s.c  om
protected void applyPatches(UserTransaction transaction, int dbVersion) {
    log.info("Database version: " + dbVersion + ", code version: " + dbPatches.size());
    while (dbVersion < dbPatches.size()) {
        DBPatch patch = ApplicationContextFactory.createAutowiredBean(dbPatches.get(dbVersion));
        dbVersion++;
        log.info("Applying patch " + patch + " (" + dbVersion + ")");
        try {
            transaction.begin();
            patch.executeDDLBefore();
            patch.executeDML();
            patch.executeDDLAfter();
            constantDAO.setDatabaseVersion(dbVersion);
            transaction.commit();
            log.info("Patch " + patch.getClass().getName() + "(" + dbVersion
                    + ") is applied to database successfully.");
        } catch (Throwable th) {
            log.error("Can't apply patch " + patch.getClass().getName() + "(" + dbVersion + ").", th);
            Utils.rollbackTransaction(transaction);
            break;
        }
    }
}

From source file:ru.runa.wfe.service.impl.ReceiveMessageBean.java

@Override
public void onMessage(Message jmsMessage) {
    List<ReceiveMessageData> handlers = Lists.newArrayList();
    ObjectMessage message = (ObjectMessage) jmsMessage;
    String messageString = Utils.toString(message, false);
    UserTransaction transaction = context.getUserTransaction();
    ErrorEventData errorEventData = null;
    try {/*from   w w w.j a  v  a 2 s  .  co m*/
        log.debug("Received " + messageString);
        errorEventData = ErrorEventData.match(message);
        transaction.begin();
        List<Token> tokens;
        if (SystemProperties.isProcessExecutionMessagePredefinedSelectorEnabled()) {
            Map<String, String> routingData = getRoutingData(message);
            tokens = executionLogic.findTokensForMessageSelector(routingData);
            log.debug("Checking " + tokens.size() + " tokens by routingData = " + routingData);
        } else {
            tokens = tokenDao.findByNodeTypeAndExecutionStatusIsActive(NodeType.RECEIVE_MESSAGE);
            log.debug("Checking " + tokens.size() + " tokens");
        }
        for (Token token : tokens) {
            try {
                ProcessDefinition processDefinition = processDefinitionLoader
                        .getDefinition(token.getProcess().getDeployment().getId());
                BaseMessageNode receiveMessageNode = (BaseMessageNode) token.getNodeNotNull(processDefinition);
                ExecutionContext executionContext = new ExecutionContext(processDefinition, token);
                if (errorEventData != null) {
                    if (receiveMessageNode.getEventType() == MessageEventType.error
                            && receiveMessageNode.getParentElement() instanceof Node) {
                        Long processId = token.getProcess().getId();
                        String nodeId = ((Node) receiveMessageNode.getParentElement()).getNodeId();
                        if (processId.equals(errorEventData.processId)
                                && nodeId.equals(errorEventData.nodeId)) {
                            handlers.add(new ReceiveMessageData(executionContext, receiveMessageNode));
                            break;
                        }
                    }
                } else {
                    boolean suitable = true;
                    VariableProvider variableProvider = executionContext.getVariableProvider();
                    for (VariableMapping mapping : receiveMessageNode.getVariableMappings()) {
                        if (mapping.isPropertySelector()) {
                            String selectorValue = message.getStringProperty(mapping.getName());
                            String expectedValue = Utils.getMessageSelectorValue(variableProvider,
                                    receiveMessageNode, mapping);
                            if (!Objects.equal(expectedValue, selectorValue)) {
                                log.debug(message + " rejected in " + token + " due to diff in "
                                        + mapping.getName() + " (" + expectedValue + "!=" + selectorValue
                                        + ")");
                                suitable = false;
                                break;

                            }
                        }
                    }
                    if (suitable) {
                        handlers.add(new ReceiveMessageData(executionContext, receiveMessageNode));
                    }
                }
            } catch (Exception e) {
                log.error("Unable to handle " + token, e);
            }
        }
        transaction.commit();
    } catch (Exception e) {
        log.error("", e);
        Utils.rollbackTransaction(transaction);
        Throwables.propagate(e);
    }
    if (handlers.isEmpty()) {
        if (errorEventData != null) {
            String errorMessage = "Unexpected errorEvent in processId = " + errorEventData.processId
                    + ", nodeId = " + errorEventData.nodeId;
            log.error(errorMessage);
            Errors.addSystemError(new InternalApplicationException(errorMessage));
        } else {
            throw new MessagePostponedException(messageString);
        }
    }
    for (ReceiveMessageData data : handlers) {
        handleMessage(data, message);
    }
}