Example usage for javax.transaction UserTransaction begin

List of usage examples for javax.transaction UserTransaction begin

Introduction

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

Prototype

void begin() throws NotSupportedException, SystemException;

Source Link

Document

Create a new transaction and associate it with the current thread.

Usage

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

public String execute() {
    String rtnVal = SUCCESS;/* www .  jav a2 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 {/*ww  w  .  j  a  v  a2 s .  c  om*/
        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;//  w ww .  jav a 2 s.  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);
    }
}

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

@Override
public int getCacheId(String userId) {
    ResultSet rs = null;//from   ww  w. j  a  v a 2  s  . com
    PreparedStatement st = null;
    PreparedStatement st2 = null;
    Connection con = null;
    int cacheId = 0;

    UserTransaction ut = getUserTransaction();
    try {
        ut.begin();
        con = getConnection();
        st = con.prepareStatement("SELECT id FROM minig_cache WHERE user_id = ?");
        st.setString(1, userId);
        rs = st.executeQuery();
        if (rs.next()) {
            cacheId = rs.getInt(1);
        }

        if (cacheId == 0) {
            st2 = con.prepareStatement("INSERT INTO minig_cache (user_id) VALUES (?)");

            st2.setString(1, userId);
            st2.executeUpdate();
            cacheId = CacheActivator.get().generatedKey(con);
        }
        ut.commit();
    } catch (Exception e) {
        logger.error("Error executing query creating cacheId", e);
        JDBCUtils.rollback(ut);
    } finally {
        JDBCUtils.cleanup(null, st2, null);
        JDBCUtils.cleanup(con, st, rs);
    }
    return cacheId;
}

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   ww  w  .  j  ava2  s.com
        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 {//  ww  w  . ja va2 s .  c  o m
        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.data.JdoLayerImpl.java

public Map deleteObject(Map dataMap, StoreDesc sdesc, String entityName, String id) {
    info("deleteObject:" + dataMap + ",module:" + entityName);
    debug("deleteObject:" + dataMap + ",module:" + entityName + ",id:" + id);
    Map retMap = new HashMap();
    SessionContext sessionContext = getSessionContext(sdesc);
    UserTransaction ut = m_nucleusService.getUserTransaction();
    try {//from w  w  w.  jav a 2s .co  m
        ut.begin();
        retMap = deleteObject(sessionContext, dataMap, entityName, id);
        ut.commit();
    } catch (Exception e) {
        sessionContext.handleException(ut, e);
    } finally {
        sessionContext.handleFinally(ut);
    }
    return retMap;
}

From source file:org.ms123.common.data.quality.QualityBatch.java

protected synchronized List<Map> doCheckFromDb(String state, String id, boolean dry) throws Exception {
    SessionContext sc = getSessionContext();
    m_permittedFields = sc.getPermittedFields(m_entityName, "write");
    init();/*from www.j av a 2s  . co  m*/
    m_count = 0;
    m_dups = 0;
    UserTransaction ut = m_nucleusService.getUserTransaction();
    List<Map> dupList = new ArrayList();
    try {
        ut.begin();
        Class clazz = sc.getClass(getEntityName());
        Extent e = sc.getPM().getExtent(clazz, true);
        String filter = constructFilter(state, id);
        Query q = sc.getPM().newQuery(e, filter);
        q.setFilter(filter);
        List results = (List) q.execute();
        Iterator iter = results.iterator();
        while (iter.hasNext()) {
            Object cand = iter.next();
            Object refObj = compareToOKList(sc, cand, dry);
            if (refObj != null) {
                dupList.add(getOneResult(refObj, cand));
            }
        }
        ut.commit();
    } catch (Throwable e) {
        sc.handleException(ut, e);
    } finally {
        sc.handleFinally(ut);
    }
    info("dupList:" + m_js.deepSerialize(dupList));
    return dupList;
}

From source file:org.ms123.common.data.quality.QualityBatch.java

protected synchronized List<Map> doCheckFromData(List<Map> candidateData) throws Exception {
    SessionContext sc = getSessionContext();
    m_permittedFields = sc.getPermittedFields(m_entityName, "write");
    init();/*from w w  w  .j  a  v  a  2 s.c  om*/
    m_count = 0;
    UserTransaction ut = m_nucleusService.getUserTransaction();
    List<Map> dupList = new ArrayList();
    try {
        ut.begin();
        Iterator<Map> iter = candidateData.iterator();
        while (iter.hasNext()) {
            Map cand = iter.next();
            setRelatedObjects(sc, cand);
            debug("candidateData:" + cand);
            Object refObj = compareToOKList(sc, cand, true);
            if (refObj != null) {
                dupList.add(getOneResult(refObj, cand));
            }
        }
        ut.commit();
    } catch (Throwable e) {
        sc.handleException(ut, e);
    } finally {
        sc.handleFinally(ut);
    }
    return dupList;
}

From source file:org.ms123.common.data.quality.QualityBatch.java

private void train() {
    UserTransaction ut = m_nucleusService.getUserTransaction();
    SessionContext sc = getSessionContext();
    List corbus = new ArrayList();
    try {//  w  w w  .j a  v  a 2  s. co m
        ut.begin();
        Class clazz = sc.getClass(getEntityName());
        Extent e = sc.getPM().getExtent(clazz, true);
        Query q = sc.getPM().newQuery(e);
        List results = (List) q.execute();
        Iterator iter = results.iterator();
        List<Map> fields = getFields();
        List<Map> fieldsets = getFieldsets();
        int count = 0;
        while (iter.hasNext()) {
            Object obj = iter.next();
            if ((count++ % 1000) == 1) {
                info("train.num:" + count);
            }
            for (Map field : fields) {
                if (field.get(COMPARE) instanceof FuzzyCompare) {
                    FuzzyCompare fc = (FuzzyCompare) field.get(COMPARE);
                    fc.addTrainValue((String) PropertyUtils.getProperty(obj, (String) field.get(NAME)));
                }
            }
            for (Map fieldset : fieldsets) {
                if (!isEmpty(fieldset.get(EXPRESSION))) {
                    for (Map cmpUnit : (List<Map>) fieldset.get(COMPARE_UNITS)) {
                        Compare c = (Compare) cmpUnit.get(COMPARE);
                        if (c instanceof FuzzyCompare) {
                            FuzzyCompare fc = (FuzzyCompare) c;
                            List fs = (List) cmpUnit.get(FIELDS);
                            String value = getFieldsetValue(obj, fs);
                            fc.addTrainValue(value);
                        }
                    }
                } else {
                    FuzzyCompare fc = (FuzzyCompare) fieldset.get(COMPARE);
                    String value = getFieldsetValue(obj, fieldset);
                    fc.addTrainValue(value);
                }
            }
        }
        ut.commit();
    } catch (Throwable e) {
        sc.handleException(ut, e);
    } finally {
        sc.handleFinally(ut);
    }
}