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.craftercms.cstudio.alfresco.dm.util.impl.DmImportServiceImpl.java

/**
 * submit imported items to go live/*from  www.  j  a va  2  s  .  co m*/
 * 
 * @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.eclipse.ecr.core.event.tx.EventBundleTransactionHandler.java

protected UserTransaction createUT(Integer transactionTimeout, boolean retry) {
    try {/*  www.  j  a  va  2s.c o m*/
        new InitialContext();
    } catch (Exception e) {
        disabled = true;
        return null;
    }

    UserTransaction ut;
    try {
        ut = TransactionHelper.lookupUserTransaction();
    } catch (NamingException e) {
        disabled = true;
        return null;
    }

    try {
        int txStatus = ut.getStatus();
        if (txStatus != Status.STATUS_NO_TRANSACTION && !retry) {
            // if previous tx in this thread aborted in TimeOut
            // Ajuna may have failed to dissociate tx from thread context
            // => force rollback to avoid reusing a dead tx
            log.warn(
                    "Transaction was not properly cleanup up from thread context, rolling back before getting a new tx");
            try {
                ut.rollback();
            } catch (Throwable t) {
                log.warn("error during tx rollback", t);
            }
            return createUT(transactionTimeout, true);
        }
    } catch (Exception se) {
        log.warn("Error while getting TX status", se);
    }

    if (transactionTimeout != null) {
        try {
            ut.setTransactionTimeout(transactionTimeout);
        } catch (SystemException e) {
            log.error("Error while setting transaction timeout to " + transactionTimeout, e);
        }
    }
    return ut;
}

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

/**
 * Commits or rolls back the User Transaction depending on the transaction
 * status./*from  www . jav  a 2 s .c om*/
 *
 * @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

/** Rolls back transaction in the current thread IF transactions are available */
public static void rollback(Throwable causeThrowable) throws GenericTransactionException {
    UserTransaction ut = TransactionFactory.getUserTransaction();

    if (ut != null) {
        try {/*  ww  w  .  j  a va2s.  c  o  m*/
            int status = ut.getStatus();
            logger.debug("[TransactionUtil.rollback] current status : " + getTransactionStateString(status));

            if (status != STATUS_NO_TRANSACTION) {
                // if (Debug.infoOn()) Thread.dumpStack();
                if (causeThrowable == null && logger.isInfoEnabled()) {
                    Exception newE = new Exception("Stack Trace");
                    logger.error("[TransactionUtil.rollback]");
                }

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

                ut.rollback();
                logger.info("[TransactionUtil.rollback] transaction rolled back");
            } else {
                logger.warn(
                        "[TransactionUtil.rollback] transaction not rolled back, status is STATUS_NO_TRANSACTION");
            }
        } catch (IllegalStateException e) {
            Throwable t = e.getCause() == null ? e : e.getCause();
            throw new GenericTransactionException(
                    "Could not rollback transaction, IllegalStateException exception: " + t.toString(), t);
        } catch (SystemException e) {
            Throwable t = e.getCause() == null ? e : e.getCause();
            throw new GenericTransactionException(
                    "System error, could not rollback transaction: " + t.toString(), t);
        }
    } else {
        logger.info("[TransactionUtil.rollback] No UserTransaction, transaction not rolled back");
    }
}

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

public void rollback() {
    log.debug("rollback()");
    try {// w  ww  .j  ava 2s  .co m
        UserTransaction userTransaction = TransactionUtil.getUserTransaction();
        int status = userTransaction.getStatus();
        if (status != Status.STATUS_COMMITTED && status != Status.STATUS_ROLLEDBACK) {
            userTransaction.rollback();
        }
    } catch (Exception e) {

        log.error("rollback failed!");
        throw new InfrastructureException(e);
    }
}

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

public String execute() {
    String rtnVal = SUCCESS;/*from  w ww.  j a  v  a2  s  .co  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 {/*www . jav a 2 s  .  c o  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.ms123.common.data.JdoLayerImpl.java

public Map insertObject(Map dataMap, Map filterMap, Map hintsMap, StoreDesc sdesc, String entityName,
        String entityNameParent, String idParent) {
    debug("insertObject:" + dataMap + ",filterMap:" + filterMap + ",entity:" + entityName + "/entityNameParent:"
            + entityNameParent + "/idParent:" + idParent);
    Map retMap = new HashMap();
    // initialize 
    SessionContext sessionContext = getSessionContext(sdesc);
    UserTransaction ut = m_nucleusService.getUserTransaction();
    try {//from  w  w w . j ava  2  s . c o m
        ut.begin();
        retMap = insertObject(sessionContext, dataMap, filterMap, hintsMap, entityName, entityNameParent,
                idParent);
        if (retMap.get("constraintViolations") == null) {
            ut.commit();
        } else {
            ut.rollback();
        }
    } catch (Throwable e) {
        sessionContext.handleException(ut, e);
    } finally {
        sessionContext.handleFinally(ut);
    }
    return retMap;
}

From source file:org.ms123.common.data.JdoLayerImpl.java

public Map updateObject(Map dataMap, Map filterMap, Map hintsMap, StoreDesc sdesc, String entityName, String id,
        String entityNameParent, String idParent) {
    m_logger.info("updateObject:" + dataMap + ",filterMap:" + filterMap + ",module:" + entityName);
    debug("updateObject:" + dataMap + ",filterMap:" + filterMap + ",module:" + entityName + ",id:" + id
            + ",moduleNameParent:" + entityNameParent + ",idParent:" + idParent);
    Map retMap = new HashMap();
    SessionContext sessionContext = getSessionContext(sdesc);
    UserTransaction ut = m_nucleusService.getUserTransaction();
    try {/*www  .  j  a v  a 2 s  .com*/
        ut.begin();
        retMap = updateObject(sessionContext, dataMap, filterMap, hintsMap, entityName, id, entityNameParent,
                idParent);
        if (retMap.get("constraintViolations") == null) {
            ut.commit();
        } else {
            ut.rollback();
        }
    } catch (Exception e) {
        sessionContext.handleException(ut, e);
    } finally {
        sessionContext.handleFinally(ut);
    }
    return retMap;
}

From source file:org.ms123.common.importing.ImportingServiceImpl.java

public Object doImport(@PName(StoreDesc.STORE_ID) String storeId,
        @PName(IMPORTING_ID) @POptional String importingid,
        @PName("withoutSave") @POptional @PDefaultBool(false) Boolean withoutSave,
        @PName("max") @POptional @PDefaultInt(-1) Integer max) throws RpcException {
    StoreDesc data_sdesc = StoreDesc.get(storeId);
    StoreDesc aid_sdesc = getStoreDesc(data_sdesc.getNamespace());
    SessionContext sessionContext = m_dataLayer.getSessionContext(aid_sdesc);
    try {//from w  w  w. jav a  2  s.com
        String className = m_inflector.getClassName(IMPORTING_ENTITY);
        Class clazz = sessionContext.getClass(className);
        Object obj = sessionContext.getObjectById(clazz, importingid);
        if (obj == null) {
            throw new RuntimeException(
                    "ImportingServiceImpl.doImport:importingid:\"" + importingid + "\" not found");
        }
        Map settings = (Map) m_ds.deserialize((String) getProperty(obj, JSON_BODY));
        byte[] content = (byte[]) getProperty(obj, CONTENT);
        if (settings.get("input") != null) {
            System.out.println("doImport:" + settings);
            System.out.println("doImport:" + m_datamapper + "/" + data_sdesc + "/" + content);
            sessionContext = m_dataLayer.getSessionContext(data_sdesc);
            BeanFactory bf = new BeanFactory(sessionContext, settings);
            Object ret = m_datamapper.transform(data_sdesc.getNamespace(), settings, null, new String(content),
                    bf);
            if (withoutSave)
                return ret;
            UserTransaction ut = sessionContext.getUserTransaction();
            try {
                ut.begin();
                Map outputTree = (Map) settings.get("output");
                Map<String, Object> persistenceSpecification = (Map) outputTree.get("persistenceSpecification");
                Object o = org.ms123.common.data.MultiOperations.persistObjects(sessionContext, ret,
                        persistenceSpecification, -1);
                ut.commit();
                return o;
            } catch (Exception e) {
                ut.rollback();
                throw e;
            }
        } else {
            return doImport(data_sdesc, settings, content, withoutSave, max);
        }
    } catch (Throwable e) {
        throw new RpcException(ERROR_FROM_METHOD, INTERNAL_SERVER_ERROR, "ImportingServiceImpl.doImport:", e);
    } finally {
        sessionContext.handleFinally(null);
    }
}