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.apache.axis2.transport.jms.JMSMessageSender.java

/**
 * Perform actual send of JMS message to the Destination selected
 *
 * @param message the JMS message//  w w  w  . jav a2  s  .  c  o m
 * @param msgCtx the Axis2 MessageContext
 */
public void send(Message message, MessageContext msgCtx) {

    Boolean jtaCommit = getBooleanProperty(msgCtx, BaseConstants.JTA_COMMIT_AFTER_SEND);
    Boolean rollbackOnly = getBooleanProperty(msgCtx, BaseConstants.SET_ROLLBACK_ONLY);
    Boolean persistent = getBooleanProperty(msgCtx, JMSConstants.JMS_DELIVERY_MODE);
    Integer priority = getIntegerProperty(msgCtx, JMSConstants.JMS_PRIORITY);
    Integer 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) {
            handleException("Error setting JMS Producer for PERSISTENT delivery", e);
        }
    }
    if (priority != null) {
        try {
            producer.setPriority(priority);
        } catch (JMSException e) {
            handleException("Error setting JMS Producer priority to : " + priority, e);
        }
    }
    if (timeToLive != null) {
        try {
            producer.setTimeToLive(timeToLive);
        } catch (JMSException e) {
            handleException("Error setting JMS Producer TTL to : " + timeToLive, e);
        }
    }

    boolean sendingSuccessful = false;
    // perform actual message sending
    try {
        if (jmsSpec11 || isQueue == null) {
            producer.send(message);

        } else {
            if (isQueue) {
                ((QueueSender) producer).send(message);

            } else {
                ((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;

        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 with MessageContext ID : " + msgCtx.getMessageID()
                + " 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) {
                    handleException("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) {
                handleException("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.apache.ofbiz.entity.transaction.TransactionUtil.java

/** Commits the transaction in the current thread IF transactions are available */
public static void commit() throws GenericTransactionException {
    UserTransaction ut = TransactionFactoryLoader.getInstance().getUserTransaction();

    if (ut != null) {
        try {/* w ww. j a  va  2  s. c  o m*/
            int status = ut.getStatus();
            Debug.logVerbose("Current status : " + getTransactionStateString(status), module);

            if (status != STATUS_NO_TRANSACTION && status != STATUS_COMMITTING && status != STATUS_COMMITTED
                    && status != STATUS_ROLLING_BACK && status != STATUS_ROLLEDBACK) {
                ut.commit();

                // clear out the stamps to keep it clean
                clearTransactionStamps();
                // clear out the stack too
                clearTransactionBeginStack();
                clearSetRollbackOnlyCause();

                Debug.logVerbose("Transaction committed", module);
            } else {
                Debug.logWarning("Not committing transaction, status is " + getStatusString(), module);
            }
        } catch (RollbackException e) {
            RollbackOnlyCause rollbackOnlyCause = getSetRollbackOnlyCause();

            if (rollbackOnlyCause != null) {
                // the transaction is now definitely over, so clear stuff as normal now that we have the info from it that we want
                clearTransactionStamps();
                clearTransactionBeginStack();
                clearSetRollbackOnlyCause();

                Debug.logError(e,
                        "Rollback Only was set when trying to commit transaction here; throwing rollbackOnly cause exception",
                        module);
                throw new GenericTransactionException(
                        "Roll back error, could not commit transaction, was rolled back instead because of: "
                                + rollbackOnlyCause.getCauseMessage(),
                        rollbackOnlyCause.getCauseThrowable());
            } else {
                Throwable t = e.getCause() == null ? e : e.getCause();
                throw new GenericTransactionException(
                        "Roll back error (with no rollbackOnly cause found), could not commit transaction, was rolled back instead: "
                                + t.toString(),
                        t);
            }
        } catch (IllegalStateException e) {
            Throwable t = e.getCause() == null ? e : e.getCause();
            throw new GenericTransactionException(
                    "Could not commit transaction, IllegalStateException exception: " + t.toString(), t);
        } catch (HeuristicMixedException e) {
            Throwable t = e.getCause() == null ? e : e.getCause();
            throw new GenericTransactionException(
                    "Could not commit transaction, HeuristicMixed exception: " + t.toString(), t);
        } catch (HeuristicRollbackException e) {
            Throwable t = e.getCause() == null ? e : e.getCause();
            throw new GenericTransactionException(
                    "Could not commit transaction, HeuristicRollback exception: " + t.toString(), t);
        } catch (SystemException e) {
            Throwable t = e.getCause() == null ? e : e.getCause();
            throw new GenericTransactionException("System error, could not commit transaction: " + t.toString(),
                    t);
        }
    } else {
        Debug.logInfo("UserTransaction is null, not committing", module);
    }
}

From source file:org.craftercms.cstudio.alfresco.dm.util.impl.DmImportServiceImpl.java

/**
 * submit imported items to go live//from  w  w  w.ja  v a 2  s.c  om
 * 
 * @param site
 * @param publishChannelGroup
 * @param importedFullPaths
 */
protected void submitToGoLive(String site, String publishChannelGroup, List<String> importedFullPaths) {
    DmTransactionService transaction = getService(DmTransactionService.class);
    UserTransaction tnx = transaction.getNonPropagatingUserTransaction();
    try {
        tnx.begin();
        MultiChannelPublishingContext mcpContext = new MultiChannelPublishingContext(publishChannelGroup, "",
                "Import Service");
        DmPublishService publishService = getService(DmPublishService.class);
        publishService.publish(site, importedFullPaths, null, mcpContext);
        LOGGER.info("All files have been submitted to be publish");
        tnx.commit();
    } catch (Exception ex) {
        LOGGER.error("Unable to publish files due a error ", ex);
        try {
            tnx.rollback();
        } catch (IllegalStateException e) {
            LOGGER.error("Unable to rollback Transaction");
        } catch (SecurityException e) {
            LOGGER.error("Unable to rollback Transaction");
        } catch (SystemException e) {
            LOGGER.error("Unable to rollback Transaction");
        }
    }
}

From source file:org.droolsjbpm.services.test.ci.SessionMGMTandCIBaseTest.java

protected void completeOperation(UserTransaction ut, EntityManager entityManager) {
    if (ut != null) {
        try {//from  w w w.  j av a  2s  .co  m
            ut.commit();
            if (entityManager != null) {
                entityManager.clear();
                entityManager.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.eclipse.ecr.runtime.transaction.TransactionHelper.java

/**
 * Commits or rolls back the User Transaction depending on the transaction
 * status./*from   ww  w.  j a v  a2  s .co m*/
 *
 * @throws SystemException
 * @throws HeuristicRollbackException
 * @throws HeuristicMixedException
 * @throws RollbackException
 * @throws IllegalStateException
 * @throws SecurityException
 */
public static void commitOrRollbackTransaction() {
    UserTransaction ut;
    try {
        ut = lookupUserTransaction();
    } catch (NamingException e) {
        log.warn("No user transaction", e);
        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();
        }
    } catch (Exception e) {
        String msg = "Unable to commit/rollback  " + ut;
        if (e instanceof RollbackException
                && "Unable to commit: transaction marked for rollback".equals(e.getMessage())) {
            // don't log as error, this happens if there's a
            // ConcurrentModificationException at transaction end inside VCS
            log.debug(msg, e);
        } else {
            log.error(msg, e);
        }
        throw new TransactionRuntimeException(msg, e);
    }
}

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

/**
 * Commits the transaction in the current thread IF transactions are available
 *///from   ww  w  .  java2s . c o m
public static void commit() throws GenericTransactionException {
    UserTransaction ut = TransactionFactory.getUserTransaction();

    if (ut != null) {
        try {
            int status = ut.getStatus();
            logger.debug("[TransactionUtil.commit] current status : " + getTransactionStateString(status));

            if (status != STATUS_NO_TRANSACTION && status != STATUS_COMMITTING && status != STATUS_COMMITTED
                    && status != STATUS_ROLLING_BACK && status != STATUS_ROLLEDBACK) {
                ut.commit();

                // clear out the stamps to keep it clean
                clearTransactionStamps();
                // clear out the stack too
                clearTransactionBeginStack();
                clearSetRollbackOnlyCause();

                logger.debug("[TransactionUtil.commit] transaction committed");
            } else {
                logger.warn(
                        "[TransactionUtil.commit] Not committing transaction, status is " + getStatusString());
            }
        } catch (RollbackException e) {
            RollbackOnlyCause rollbackOnlyCause = getSetRollbackOnlyCause();

            if (rollbackOnlyCause != null) {
                // the transaction is now definitely over, so clear stuff as normal
                // now that we have the info from it that we want
                clearTransactionStamps();
                clearTransactionBeginStack();
                clearSetRollbackOnlyCause();

                logger.error(
                        "Rollback Only was set when trying to commit transaction here; throwing rollbackOnly cause exception",
                        e);
                throw new GenericTransactionException(
                        "Roll back error, could not commit transaction, was rolled back instead because of: "
                                + rollbackOnlyCause.getCauseMessage(),
                        rollbackOnlyCause.getCauseThrowable());
            } else {
                Throwable t = e.getCause() == null ? e : e.getCause();
                throw new GenericTransactionException(
                        "Roll back error (with no rollbackOnly cause found), could not commit transaction, was rolled back instead: "
                                + t.toString(),
                        t);
            }
        } catch (IllegalStateException e) {
            Throwable t = e.getCause() == null ? e : e.getCause();
            throw new GenericTransactionException(
                    "Could not commit transaction, IllegalStateException exception: " + t.toString(), t);
        } catch (HeuristicMixedException e) {
            Throwable t = e.getCause() == null ? e : e.getCause();
            throw new GenericTransactionException(
                    "Could not commit transaction, HeuristicMixed exception: " + t.toString(), t);
        } catch (HeuristicRollbackException e) {
            Throwable t = e.getCause() == null ? e : e.getCause();
            throw new GenericTransactionException(
                    "Could not commit transaction, HeuristicRollback exception: " + t.toString(), t);
        } catch (SystemException e) {
            Throwable t = e.getCause() == null ? e : e.getCause();
            throw new GenericTransactionException("System error, could not commit transaction: " + t.toString(),
                    t);
        }
    } else {
        logger.info("[TransactionUtil.commit] UserTransaction is null, not commiting");
    }
}

From source file:org.firstopen.singularity.util.TransactionManager.java

public void commit() {

    try {// www.  ja v  a 2s.  co m
        /*
         * close any DAO Sessions related to this 
         * transaction.
         */
        DAOUtilFactory.close();

        UserTransaction userTransaction = TransactionUtil.getUserTransaction();
        if (userTransaction.getStatus() == Status.STATUS_ACTIVE) {
            userTransaction.commit();
            log.debug("transaction commit completed!");
        }
    } catch (Exception e) {
        log.error("commit failed!");
        // rollback();
        throw new InfrastructureException(e);
    }

}

From source file:org.jcvi.ometa.action.EventLoader.java

public String execute() {
    String rtnVal = SUCCESS;//from ww w . ja v a 2 s .  c  o  m
    UserTransaction tx = null;

    try {
        sampleName = sampleName != null && sampleName.equals("0") ? null : sampleName;

        if (jobType != null) {
            boolean isProjectRegistration = eventName.equals(Constants.EVENT_PROJECT_REGISTRATION);
            boolean isSampleRegistration = eventName.equals(Constants.EVENT_SAMPLE_REGISTRATION);

            if (projectName == null || projectName.equals("0") || eventName == null || eventName.equals("0"))
                throw new Exception("Project or Event type is not selected.");

            if (jobType.equals("insert")) { //loads single event
                tx = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
                tx.begin();
                psewt.loadAll(null,
                        this.createMultiLoadParameter(projectName, loadingProject, loadingSample, beanList));
                this.reset();
            } else if (jobType.equals("grid")) { //loads multiple events from grid view
                tx = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
                tx.begin();
                for (GridBean gBean : gridList) {
                    if (gBean != null) {
                        if (isProjectRegistration && gBean.getProjectName() != null
                                && gBean.getProjectPublic() != null) {
                            loadingProject = new Project();
                            loadingProject.setProjectName(gBean.getProjectName());
                            loadingProject.setIsPublic(Integer.valueOf(gBean.getProjectPublic()));
                        } else if (isSampleRegistration && gBean.getSampleName() != null
                                && gBean.getSamplePublic() != null) {
                            loadingSample = new Sample();
                            loadingSample.setSampleName(gBean.getSampleName());
                            loadingSample.setParentSampleName(gBean.getParentSampleName());
                            loadingSample.setIsPublic(Integer.valueOf(gBean.getSamplePublic()));
                        } else {
                            if (gBean.getSampleName() != null) {
                                this.sampleName = gBean.getSampleName();
                            }
                        }
                        List<FileReadAttributeBean> fBeanList = gBean.getBeanList();
                        if (fBeanList != null && fBeanList.size() > 0) {
                            psewt.loadAll(null, this.createMultiLoadParameter(projectName, loadingProject,
                                    loadingSample, fBeanList));
                        }
                    }
                }
                this.reset();

            } else if (jobType.equals("file")) { //loads data from a CSV file to grid view
                if (!this.uploadFile.canRead()) {
                    throw new Exception("Error in reading the file.");
                } else {
                    try {
                        CSVReader reader = new CSVReader(new FileReader(this.uploadFile));

                        int lineCount = 0;
                        List<String> columns = new ArrayList<String>();

                        String currProjectName = null;

                        gridList = new ArrayList<GridBean>();
                        boolean hasSampleName = false;
                        String[] line;
                        while ((line = reader.readNext()) != null) {
                            if (lineCount != 1) {
                                if (lineCount == 0) {
                                    Collections.addAll(columns, line);
                                    hasSampleName = columns.indexOf("SampleName") >= 0;
                                } else {
                                    int colIndex = 0;

                                    currProjectName = line[colIndex++];
                                    if (!isProjectRegistration && !currProjectName.equals(this.projectName)) {
                                        throw new Exception(MULTIPLE_SUBJECT_IN_FILE_MESSAGE);
                                    }

                                    GridBean gBean = new GridBean();
                                    gBean.setProjectName(currProjectName);

                                    if (hasSampleName) {
                                        gBean.setSampleName(line[(colIndex++)]);
                                    }

                                    if (isProjectRegistration) {
                                        gBean.setProjectName(currProjectName);
                                        gBean.setProjectPublic(line[(colIndex++)]);
                                    } else if (isSampleRegistration) {
                                        gBean.setParentSampleName(line[(colIndex++)]);
                                        gBean.setSamplePublic(line[(colIndex++)]);
                                    }

                                    gBean.setBeanList(new ArrayList<FileReadAttributeBean>());
                                    for (; colIndex < columns.size(); colIndex++) {
                                        FileReadAttributeBean fBean = new FileReadAttributeBean();
                                        fBean.setProjectName(
                                                isProjectRegistration ? currProjectName : this.projectName);
                                        fBean.setAttributeName(columns.get(colIndex));
                                        fBean.setAttributeValue(line[colIndex]);
                                        gBean.getBeanList().add(fBean);
                                    }
                                    this.gridList.add(gBean);
                                }
                            }
                            lineCount++;
                        }
                        jobType = "grid";
                    } catch (Exception ex) {
                        throw ex;
                    }
                }
            } else if (jobType.equals("template")) { //download template
                List<EventMetaAttribute> emaList = readPersister.getEventMetaAttributes(projectName, eventName);

                /*
                 * removing the sanity check on sample requirement since multiple sample support is in action
                 * by hkim 5/2/13
                ModelValidator validator = new ModelValidator();
                validator.validateEventTemplateSanity(emaList, projectName, sampleName, eventName);
                */

                TemplatePreProcessingUtils cvsUtils = new TemplatePreProcessingUtils();
                String templateType = jobType.substring(jobType.indexOf("_") + 1);
                downloadStream = cvsUtils.buildFileContent(templateType, emaList, projectName, sampleName,
                        eventName);
                downloadContentType = templateType.equals("c") ? "csv" : "vnd.ms-excel";
                rtnVal = Constants.FILE_DOWNLOAD_MSG;
            }
        }

    } catch (Exception ex) {
        logger.error("Exception in EventLoader : " + ex.toString());
        ex.printStackTrace();
        if (ex.getClass() == ForbiddenResourceException.class) {
            addActionError(Constants.DENIED_USER_EDIT_MESSAGE);
            return Constants.FORBIDDEN_ACTION_RESPONSE;
        } else if (ex.getClass() == ForbiddenResourceException.class) {
            addActionError(Constants.DENIED_USER_EDIT_MESSAGE);
            return LOGIN;
        } else if (ex.getClass() == ParseException.class)
            addActionError(Constants.INVALID_DATE_MESSAGE);
        else {
            addActionError(ex.toString());
        }

        //deletes uploaded files in event of error
        if (loadedFiles != null && loadedFiles.size() > 0) {
            for (String filePath : loadedFiles) {
                File tempFile = new File(fileStoragePath + filePath);
                if (tempFile.exists())
                    tempFile.delete();
            }
        }

        try {
            if (tx != null)
                tx.rollback();
        } catch (SystemException se) {
            addActionError(se.toString());
        }

        rtnVal = ERROR;
    } finally {
        try {
            //get project list for the drop down box
            List<String> projectNameList = new ArrayList<String>();
            if (projectNames == null || projectNames.equals("")) {
                projectNameList.add("ALL");
            } else if (projectNames.contains(",")) {
                projectNameList.addAll(Arrays.asList(projectNames.split(",")));
            } else {
                projectNameList.add(projectNames);
            }
            projectList = readPersister.getProjects(projectNameList);

            if (tx != null && tx.getStatus() != Status.STATUS_NO_TRANSACTION) {
                tx.commit();
            }

            if (jobType != null && jobType.equals("grid") && this.uploadFile != null) {
                this.uploadFile.delete();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    return rtnVal;
}

From source file:org.josso.alfresco.agent.AlfrescoSSOAgentFilter.java

protected void setAuthenticatedUser(final HttpServletRequest req, final HttpServletResponse res,
        final HttpSession httpSess, final String userName) {

    UserTransaction tx = serviceRegistry.getTransactionService().getUserTransaction();

    Subject.doAs(AlfrescoPrivilegdedActions.getAdminSubject(),
            AlfrescoPrivilegdedActions.clearCurrentSecurityContextAction(authComponent));
    ticketComponent.clearCurrentTicket();

    try {/*from w  w  w . ja  v a 2  s .co m*/
        tx.begin();
        Subject.doAs(AlfrescoPrivilegdedActions.getAdminSubject(),
                AlfrescoPrivilegdedActions.setCurrentUserAction(userName));
        Subject.doAs(AlfrescoPrivilegdedActions.getAdminSubject(),
                AlfrescoPrivilegdedActions.createUserAction(serviceRegistry, userName, httpSess));

        FacesHelper.getFacesContext(req, res, _ctx);
        FacesContext fc = FacesContext.getCurrentInstance();
        Map session = fc.getExternalContext().getSessionMap();
        session.remove(AuthenticationHelper.SESSION_INVALIDATED);
        tx.commit();
    } catch (Throwable ex) {
        logger.error(ex);
        try {
            tx.rollback();
        } catch (Exception ex2) {
            logger.error("Failed to rollback transaction", ex2);
        }

        if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        } else {
            throw new RuntimeException("Failed to execute transactional method", ex);
        }
    }
}

From source file:org.minig.cache.JDBCDataStore.java

@Override
public void resetCache(int cacheId) {
    Connection con = null;//from   www . j  a  v a  2s.  c om
    UserTransaction ut = getUserTransaction();
    try {
        ut.begin();
        con = getConnection();
        purgeUserCache(con, cacheId);
        ut.commit();
    } catch (Exception e) {
        logger.error("Error executing query creating cacheId", e);
        JDBCUtils.rollback(ut);
    } finally {
        JDBCUtils.closeConnection(con);
    }
}