Example usage for javax.transaction UserTransaction getStatus

List of usage examples for javax.transaction UserTransaction getStatus

Introduction

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

Prototype

int getStatus() throws SystemException;

Source Link

Document

Obtain the status of the transaction associated with the current thread.

Usage

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

/**
 * Makes a rollback the only possible outcome of the transaction in the
 * current thread IF transactions are available
 *//*from   w w w . j  a v a 2s.  c  om*/
public static void setRollbackOnly(String causeMessage, Throwable causeThrowable)
        throws GenericTransactionException {
    UserTransaction ut = TransactionFactory.getUserTransaction();
    if (ut != null) {
        try {
            int status = ut.getStatus();
            logger.debug(
                    "[TransactionUtil.setRollbackOnly] current code : " + getTransactionStateString(status));

            if (status != STATUS_NO_TRANSACTION) {
                if (status != STATUS_MARKED_ROLLBACK) {
                    if (logger.isWarnEnabled()) {
                        logger.warn(
                                "[TransactionUtil.setRollbackOnly] Calling transaction setRollbackOnly; this stack trace shows where this is happening:",
                                new Exception(causeMessage));
                    }
                    ut.setRollbackOnly();
                    setSetRollbackOnlyCause(causeMessage, causeThrowable);
                } else {
                    logger.info(
                            "[TransactionUtil.setRollbackOnly] transaction rollback only not set, rollback only is already set.");
                }
            } else {
                logger.warn(
                        "[TransactionUtil.setRollbackOnly] transaction rollback only not set, status is STATUS_NO_TRANSACTION");
            }
        } catch (IllegalStateException e) {
            Throwable t = e.getCause() == null ? e : e.getCause();
            throw new GenericTransactionException(
                    "Could not set rollback only on transaction, IllegalStateException exception: "
                            + t.toString(),
                    t);
        } catch (SystemException e) {
            Throwable t = e.getCause() == null ? e : e.getCause();
            throw new GenericTransactionException(
                    "System error, could not set rollback only on transaction: " + t.toString(), t);
        }
    } else {
        logger.info("[TransactionUtil.setRollbackOnly] No UserTransaction, transaction rollback only not set");
    }
}

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

public int getStatus() {

    try {/*from   w ww.java2  s  . c  o m*/
        UserTransaction userTransaction = TransactionUtil.getUserTransaction();
        return userTransaction.getStatus();
    } catch (Exception e) {
        throw new InfrastructureException(e);
    }
}

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

/**
 * //from w  w  w  .j a va2s. co m
 * 
 */
public void begin() {
    log.debug("begin");
    try {
        UserTransaction userTransaction = TransactionUtil.getUserTransaction();
        if (userTransaction.getStatus() == Status.STATUS_NO_TRANSACTION) {
            userTransaction.begin();
            log.debug("JTA transaction started");
        }

    } catch (Exception e) {
        log.error("cannot begin transaction");

        throw new InfrastructureException(e);
    }

}

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

public void commit() {

    try {//from ww w.j av  a 2 s. c o  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.firstopen.singularity.util.TransactionManager.java

public void rollback() {
    log.debug("rollback()");
    try {/*from  w  w  w .j  a  va  2  s  .  c o 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.hibernate.transaction.JTATransactionFactory.java

/**
 * {@inheritDoc}// w  ww  .j  a v  a 2 s  .co m
 */
public boolean isTransactionInProgress(JDBCContext jdbcContext, Context transactionContext,
        Transaction transaction) {
    try {
        // Essentially:
        // 1) If we have a local (Hibernate) transaction in progress
        //      and it already has the UserTransaction cached, use that
        //      UserTransaction to determine the status.
        // 2) If a transaction manager has been located, use
        //      that transaction manager to determine the status.
        // 3) Finally, as the last resort, try to lookup the
        //      UserTransaction via JNDI and use that to determine the
        //      status.
        if (transaction != null) {
            UserTransaction ut = ((JTATransaction) transaction).getUserTransaction();
            if (ut != null) {
                return JTAHelper.isInProgress(ut.getStatus());
            }
        }

        if (jdbcContext.getFactory().getTransactionManager() != null) {
            return JTAHelper.isInProgress(jdbcContext.getFactory().getTransactionManager().getStatus());
        } else {
            UserTransaction ut = getUserTransaction();
            return ut != null && JTAHelper.isInProgress(ut.getStatus());
        }
    } catch (SystemException se) {
        throw new TransactionException("Unable to check transaction status", se);
    }
}

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

public String execute() {
    String rtnVal = SUCCESS;//from   w  w  w .j  a 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.ms123.common.ea.BaseEAServiceImpl.java

private Map importActivities(String storeId, String basedir) throws Exception {
    String json = readFileToString(new File(basedir, "idmap.map"));
    Map<String, String> idmap = (Map) m_ds.deserialize(json);
    Calendar high_cal = Calendar.getInstance();
    high_cal.set(Calendar.YEAR, 2050);
    high_cal.set(Calendar.MONTH, 11);
    high_cal.set(Calendar.DAY_OF_MONTH, 31);

    Calendar low_cal = Calendar.getInstance();
    low_cal.set(Calendar.YEAR, 2012);
    low_cal.set(Calendar.MONTH, 11);
    low_cal.set(Calendar.DAY_OF_MONTH, 12);
    StoreDesc sdesc = StoreDesc.get(storeId);
    PersistenceManager pm = m_nucleusService.getPersistenceManagerFactory(sdesc).getPersistenceManager();
    UserTransaction ut = m_nucleusService.getUserTransaction();
    Map mapping = initActivities();
    try {/* www . ja  v a 2s.  co m*/
        LabeledCSVParser lp = new LabeledCSVParser(
                new ExcelCSVParser(new FileInputStream(new File(basedir, "Kontakte.csv"))));
        System.out.println("Persisting activities");
        int num = 0;
        Class _contact = m_nucleusService.getClass(sdesc, "Contact");
        Class _teamIntern = m_nucleusService.getClass(sdesc, "Teamintern");
        while (lp.getLine() != null) {
            String nummer = lp.getValueByLabel("Nummer");
            String merkmal = lp.getValueByLabel("Merkmal");
            Object c = getObject(pm, _contact, nummer);
            if (c == null) {
                continue;
            }
            if (ut.getStatus() != Status.STATUS_ACTIVE) {
                ut.begin();
            }
            String teamid = idmap.get(merkmal);
            Object activity = m_nucleusService.getClass(sdesc, "Activity").newInstance();
            if (teamid != null) {
                Object team = m_nucleusService.getClass(sdesc, "Team").newInstance();
                Object teamintern = getTeamintern(pm, _teamIntern, teamid);
                PropertyUtils.setProperty(team, "teamintern", teamintern);
                PropertyUtils.setProperty(team, "teamid", teamid);
                PropertyUtils.setProperty(team, "description",
                        PropertyUtils.getProperty(teamintern, "description"));
                PropertyUtils.setProperty(team, "validFrom", low_cal.getTime());
                PropertyUtils.setProperty(team, "validTo", high_cal.getTime());
                PropertyUtils.setProperty(team, "disabled", false);
                Collection l = (Collection) PropertyUtils.getProperty(activity, "_team_list");
                if (l == null) {
                    l = new HashSet();
                    PropertyUtils.setProperty(activity, "_team_list", l);
                }
                l.add(team);
            }
            Iterator it = mapping.keySet().iterator();
            while (it.hasNext()) {
                String key = (String) it.next();
                if (key.equals("traits")) {
                    continue;
                }
                String[] m1 = (String[]) mapping.get(key);
                String field = m1[0];
                String type = m1[1];
                String val = lp.getValueByLabel(key).trim();
                if (type.equals("date")) {
                    Date d = getDate(val);
                    if (d != null) {
                        BeanUtils.setProperty(activity, field, d);
                    }
                } else if (type.equals("boolean")) {
                    Boolean b = false;
                    if ("J".equals(val)) {
                        b = true;
                    }
                    BeanUtils.setProperty(activity, field, b);
                } else {
                    if (val != null) {
                        BeanUtils.setProperty(activity, field, val);
                    }
                }
            }
            Collection l = (Collection) PropertyUtils.getProperty(c, "activity_list");
            l.add(activity);
            PropertyUtils.setProperty(activity, "contact", c);
            pm.makePersistent(activity);
            //LuceneSession luceneSession = m_luceneService.createSession(sdesc);
            //m_luceneService.addToIndex(luceneSession, activity);
            //m_luceneService.commit(luceneSession);
            if ((num % 1000) == 1) {
                System.out.println(num + ":\t" + new Date().getTime());
                ut.commit();
            }
            num++;
        }
        if (ut.getStatus() == Status.STATUS_ACTIVE) {
            ut.commit();
        }
        System.out.println("Contact and Book have been persisted");
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        pm.close();
    }
    return null;
}

From source file:org.ms123.common.ea.BaseEAServiceImpl.java

private Map importTeams(String storeId, String basedir) throws Exception {
    Calendar high_cal = Calendar.getInstance();
    high_cal.set(Calendar.YEAR, 2050);
    high_cal.set(Calendar.MONTH, 11);
    high_cal.set(Calendar.DAY_OF_MONTH, 31);

    Calendar low_cal = Calendar.getInstance();
    low_cal.set(Calendar.YEAR, 2012);
    low_cal.set(Calendar.MONTH, 11);
    low_cal.set(Calendar.DAY_OF_MONTH, 12);

    String json = readFileToString(new File(basedir, "idmap.map"));
    Map<String, String> idmap = (Map) m_ds.deserialize(json);
    StoreDesc sdesc = StoreDesc.get(storeId);
    PersistenceManager pm = m_nucleusService.getPersistenceManagerFactory(sdesc).getPersistenceManager();
    UserTransaction ut = m_nucleusService.getUserTransaction();
    try {//w  w  w . j a  va2 s  .c  o  m
        LabeledCSVParser lp = new LabeledCSVParser(
                new ExcelCSVParser(new FileInputStream(new File(basedir, "Merkmale.csv"))));
        System.out.println("Persisting teams");
        int num = 0;
        Class _contact = m_nucleusService.getClass(sdesc, "Contact");
        Class _company = m_nucleusService.getClass(sdesc, "Company");
        Class _teamIntern = m_nucleusService.getClass(sdesc, "Teamintern");
        while (lp.getLine() != null) {
            String nummer = lp.getValueByLabel("Nummer");
            String merkmal = lp.getValueByLabel("Merkmal");
            String beginn = lp.getValueByLabel("Beginn");
            String ende = lp.getValueByLabel("Ende");
            String status = lp.getValueByLabel("Status");
            String teamid = idmap.get(merkmal);
            if (teamid == null) {
                System.out.println("Teamid not found:" + merkmal);
                continue;
            }
            Object c = getObject(pm, _contact, _company, nummer);
            if (c == null) {
                System.out.println("No contact/company:" + nummer);
                continue;
            }
            if (ut.getStatus() != Status.STATUS_ACTIVE) {
                ut.begin();
            }
            Object team = m_nucleusService.getClass(sdesc, "Team").newInstance();
            Object teamintern = getTeamintern(pm, _teamIntern, teamid);
            PropertyUtils.setProperty(team, "teamintern", teamintern);
            PropertyUtils.setProperty(team, "teamid", teamid);
            PropertyUtils.setProperty(team, "description",
                    PropertyUtils.getProperty(teamintern, "description"));

            Boolean active = isActive(status);
            Date validFrom = getTeamDate(beginn);
            Date validTo = getTeamDate(ende);
            if (active != null && validFrom != null && validTo != null) {
                PropertyUtils.setProperty(team, "validFrom", validFrom);
                PropertyUtils.setProperty(team, "validTo", validTo);
                PropertyUtils.setProperty(team, "disabled", !active);
            }
            if (active == null && validFrom == null && validTo == null) {
                PropertyUtils.setProperty(team, "validFrom", low_cal.getTime());
                PropertyUtils.setProperty(team, "validTo", high_cal.getTime());
                PropertyUtils.setProperty(team, "disabled", false);
            }
            if (active != null && validFrom != null && validTo == null) {
                PropertyUtils.setProperty(team, "validFrom", validFrom);
                PropertyUtils.setProperty(team, "validTo", high_cal.getTime());
                PropertyUtils.setProperty(team, "disabled", !active);
            }
            PropertyUtils.setProperty(team, "property1", lp.getValueByLabel("Nutzer"));
            PropertyUtils.setProperty(team, "property2", lp.getValueByLabel("Passwort"));

            Collection l = (Collection) PropertyUtils.getProperty(c, "_team_list");
            if (l == null) {
                l = new HashSet();
                PropertyUtils.setProperty(c, "_team_list", l);
            }
            l.add(team);
            pm.makePersistent(team);
            if ((num % 1000) == 1) {
                System.out.println(num + ":\t" + new Date().getTime());
                ut.commit();
            }
            num++;
        }
        if (ut.getStatus() == Status.STATUS_ACTIVE) {
            ut.commit();
        }
        System.out.println("Contact and Book have been persisted");
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        pm.close();
    }
    return null;
}

From source file:org.ms123.common.ea.BaseEAServiceImpl.java

private Map importCommunications(String storeId, String basedir) {
    StoreDesc sdesc = StoreDesc.get(storeId);
    PersistenceManager pm = m_nucleusService.getPersistenceManagerFactory(sdesc).getPersistenceManager();
    UserTransaction ut = m_nucleusService.getUserTransaction();
    Map mapping = initCommunication();
    try {//  w  w w  . j  av a  2  s. co m
        LabeledCSVParser lp = new LabeledCSVParser(
                new ExcelCSVParser(new FileInputStream(new File(basedir, "Kommunikation.csv"))));
        System.out.println("Persisting communication");
        int num = 0;
        Class _contact = m_nucleusService.getClass(sdesc, "Contact");
        Class _company = m_nucleusService.getClass(sdesc, "Company");
        while (lp.getLine() != null) {
            String nummer = lp.getValueByLabel("Nummer");
            Object c = getObject(pm, _contact, nummer);
            if (c == null) {
                c = getObject(pm, _company, nummer);
                if (c == null) {
                    continue;
                }
            }
            if (ut.getStatus() != Status.STATUS_ACTIVE) {
                ut.begin();
            }
            String typ = lp.getValueByLabel("Typ");
            typ = typ.toLowerCase();
            String adresse = lp.getValueByLabel("Adresse");
            Object comm = PropertyUtils.getProperty(c, "communication");
            if (comm == null) {
                comm = m_nucleusService.getClass(sdesc, "Communication").newInstance();
                PropertyUtils.setProperty(c, "communication", comm);
                pm.makePersistent(comm);
            }
            String[] m1 = (String[]) mapping.get(typ);
            if (m1 == null) {
                System.out.println("typ(" + typ + "): not found");
                continue;
            }
            String field = m1[0];
            BeanUtils.setProperty(comm, field, adresse);
            pm.makePersistent(comm);
            if ((num % 1000) == 1) {
                System.out.println(num + ":\t" + new Date().getTime());
                ut.commit();
            }
            num++;
        }
        if (ut.getStatus() == Status.STATUS_ACTIVE) {
            ut.commit();
        }
        System.out.println("Communication have been persisted");
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        pm.close();
    }
    return null;
}