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.ms123.common.importing.ImportingServiceImpl.java

public Map upload(@PName(StoreDesc.STORE_ID) String storeId, @PName(IMPORTING_ID) @POptional String importingid,
        @PName(FILE_CONTENT) @POptional String fileContent, @PName(FILE_MAP) @POptional Map fileMap,
        @PName(SETTINGS) @POptional Map settings,
        @PName("withoutImport") @POptional @PDefaultBool(false) Boolean withoutImport) throws RpcException {

    if (fileMap == null && fileContent == null) {
        throw new RuntimeException("fileMap or fileContent is needed");
    }/*from w  w  w  .  j a va  2s.co  m*/
    StoreDesc data_sdesc = StoreDesc.get(storeId);
    StoreDesc aid_sdesc = getStoreDesc(data_sdesc.getNamespace());
    SessionContext sessionContext = m_dataLayer.getSessionContext(aid_sdesc);
    PersistenceManager pm = sessionContext.getPM();
    UserTransaction ut = sessionContext.getUserTransaction();
    try {
        ut.begin();
        System.out.println("upload:" + data_sdesc + "/" + fileMap);
        String className = m_inflector.getClassName(IMPORTING_ENTITY);
        Class clazz = sessionContext.getClass(className);
        Object obj = sessionContext.getObjectById(clazz, importingid);
        if (obj == null) {
            obj = sessionContext.createObject(IMPORTING_ENTITY);
            setProperty(obj, IMPORTING_ID, importingid);
            sessionContext.makePersistent(obj);
        }
        byte[] bytes = null;
        if (fileMap != null) {
            Map importFile = (Map) fileMap.get("importfile");
            String storeLocation = (String) importFile.get("storeLocation");
            InputStream is = new FileInputStream(new File(storeLocation));
            bytes = toByteArray(is);
            is.close();
        } else if (fileContent != null && fileContent.startsWith("data:")) {
            int ind = fileContent.indexOf(";base64,");
            bytes = Base64.decode(fileContent.substring(ind + 8));
        }
        bytes = convertToUTF8(bytes);
        setProperty(obj, USER, getUserName());
        setProperty(obj, CONTENT, bytes);
        if (settings != null) {
            setProperty(obj, JSON_BODY, m_js.deepSerialize(settings));
        }
        ut.commit();
        Map ret = null;
        if (settings != null && !withoutImport) {
            ret = doImport(data_sdesc, settings, bytes, false, -1);
        }
        return ret;
    } catch (Throwable e) {
        throw new RpcException(ERROR_FROM_METHOD, INTERNAL_SERVER_ERROR, "ImportingServiceImpl.upload:", e);
    } finally {
        sessionContext.handleFinally(ut);
    }
}

From source file:org.ms123.common.team.BaseTeamServiceImpl.java

protected void _deleteTeam(StoreDesc sdesc, String teamid) throws Exception {
    List<String> ret = new ArrayList();
    String filter = "teamid == '" + getParentTeamid(teamid) + "'";
    Class clazz = m_nucleusService.getClass(sdesc, m_inflector.getClassName("teamintern"));
    PersistenceManager pm = m_nucleusService.getPersistenceManagerFactory(sdesc).getPersistenceManager();
    Extent e = pm.getExtent(clazz, true);
    Query q = pm.newQuery(e, filter);
    UserTransaction ut = m_nucleusService.getUserTransaction();
    try {// ww  w. jav  a 2 s .co  m
        Collection coll = (Collection) q.execute();
        Iterator iter = coll.iterator();
        if (iter.hasNext()) {
            Object obj = iter.next();
            Set children = (Set) PropertyUtils.getProperty(obj, "children");
            ut.begin();
            for (Object c : children) {
                String _teamid = (String) PropertyUtils.getProperty(c, "teamid");
                System.out.println("Team._teamid:" + _teamid);
                if (teamid.equals(_teamid)) {
                    System.out.println("\tfoundTeam:" + teamid);
                    children.remove(c);
                    pm.deletePersistent(c);
                }
            }
            ut.commit();
        }
    } finally {
        q.closeAll();
        pm.close();
    }
}

From source file:org.nuxeo.apidoc.browse.Distribution.java

@POST
@Path("save")
@Produces("text/html")
public Object doSave() throws NamingException, NotSupportedException, SystemException, RollbackException,
        HeuristicMixedException, HeuristicRollbackException, ParseException {
    if (!canAddDocumentation()) {
        return null;
    }//from   w  ww .  j  a  va  2  s. c  om
    FormData formData = getContext().getForm();
    String distribLabel = formData.getString("name");

    log.info("Start Snapshot...");
    boolean startedTx = false;
    UserTransaction tx = TransactionHelper.lookupUserTransaction();
    if (tx != null && !TransactionHelper.isTransactionActiveOrMarkedRollback()) {
        tx.begin();
        startedTx = true;
    }

    Map<String, Serializable> otherProperties = readFormData(formData);
    try {
        getSnapshotManager().persistRuntimeSnapshot(getContext().getCoreSession(), distribLabel,
                otherProperties);

    } catch (NuxeoException e) {
        log.error("Error during storage", e);
        if (tx != null) {
            tx.rollback();
        }
        return getView("savedKO").arg("message", e.getMessage());
    }
    log.info("Snapshot saved.");
    if (tx != null && startedTx) {
        tx.commit();
    }

    String redirectUrl = getContext().getBaseURL() + getPath();
    log.debug("Path => " + redirectUrl);
    return getView("saved");
}

From source file:org.nuxeo.apidoc.browse.Distribution.java

@POST
@Path("saveExtended")
@Produces("text/html")
public Object doSaveExtended() throws NamingException, NotSupportedException, SystemException,
        SecurityException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
    if (!canAddDocumentation()) {
        return null;
    }/*from   w w  w . jav a 2  s .  c  o  m*/

    FormData formData = getContext().getForm();

    String distribLabel = formData.getString("name");
    String bundleList = formData.getString("bundles");
    String pkgList = formData.getString("packages");
    SnapshotFilter filter = new SnapshotFilter(distribLabel);

    if (bundleList != null) {
        String[] bundles = bundleList.split("\n");
        for (String bundleId : bundles) {
            filter.addBundlePrefix(bundleId);
        }
    }

    if (pkgList != null) {
        String[] packages = pkgList.split("\\r?\\n");
        for (String pkg : packages) {
            filter.addPackagesPrefix(pkg);
        }
    }

    Map<String, Serializable> otherProperties = readFormData(formData);

    log.info("Start Snapshot...");
    boolean startedTx = false;
    UserTransaction tx = TransactionHelper.lookupUserTransaction();
    if (tx != null && !TransactionHelper.isTransactionActiveOrMarkedRollback()) {
        tx.begin();
        startedTx = true;
    }
    try {
        getSnapshotManager().persistRuntimeSnapshot(getContext().getCoreSession(), distribLabel,
                otherProperties, filter);
    } catch (NuxeoException e) {
        log.error("Error during storage", e);
        if (tx != null) {
            tx.rollback();
        }
        return getView("savedKO").arg("message", e.getMessage());
    }
    log.info("Snapshot saved.");
    if (tx != null && startedTx) {
        tx.commit();
    }
    return getView("saved");
}

From source file:org.nuxeo.runtime.transaction.TransactionHelper.java

/**
 * Starts a new User Transaction./*from   w  w w.  j a v  a2 s .c om*/
 *
 * @return {@code true} if the transaction was successfully started, {@code false} otherwise
 */
public static boolean startTransaction() {
    UserTransaction ut = NuxeoContainer.getUserTransaction();
    if (ut == null) {
        return false;
    }
    try {
        if (log.isDebugEnabled()) {
            log.debug("Starting transaction");
        }
        ut.begin();
        return true;
    } catch (NotSupportedException | SystemException e) {
        log.error("Unable to start transaction", e);
    }
    return false;
}

From source file:org.obm.push.backend.obm22.mail.EmailCacheStorage.java

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

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

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

    PreparedStatement del = null;
    PreparedStatement insert = null;

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

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

From source file:org.quartz.plugins.SchedulerPluginWithUserTransactionSupport.java

/**
 * If <em>wrapInUserTransaction</em> is true, starts a new UserTransaction 
 * and returns it. Otherwise, or if establishing the transaction fail, it 
 * will return null.//w  ww. j av  a  2 s.co m
 */
private UserTransaction startUserTransaction() {
    if (wrapInUserTransaction == false) {
        return null;
    }

    UserTransaction userTransaction = null;
    try {
        userTransaction = UserTransactionHelper.lookupUserTransaction();
        userTransaction.begin();
    } catch (Throwable t) {
        UserTransactionHelper.returnUserTransaction(userTransaction);
        userTransaction = null;
        getLog().error("Failed to start UserTransaction for plugin: " + getName(), t);
    }

    return userTransaction;
}

From source file:org.tolven.web.servlet.InternalErrorHandleServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //check if a transaction is already started, if not redirect to the servlet
    UserTransaction ut = null;
    try {//from  ww  w  . j  a v  a  2  s .c om
        ut = (UserTransaction) ctx.lookup("UserTransaction");
        if (ut.getStatus() != Status.STATUS_ACTIVE) {
            ut.begin();
        }
        //check if the error.email is configured. If found send an email
        Object accountUser = TolvenRequest.getInstance().getAccountUser();
        if (accountUser != null) {
            String errorEmail = ((AccountUser) accountUser).getAccount().getProperty()
                    .get("org.tolven.error.email.to");
            if (!StringUtils.isBlank(errorEmail)) {
                System.out.println("Send an email to " + errorEmail);
            }
        }
        if (ut != null) {
            ut.commit();
        }
        RequestDispatcher dispatcher = this.config.getServletContext().getRequestDispatcher("/error.jsp");
        if (dispatcher != null)
            dispatcher.forward(req, resp);
    } catch (Exception e) {
        throw new ServletException("Exception thrown in InternalErrorHandleServlet", e);
    } finally {
        if (ut != null) {
            try {
                ut.rollback();
            } catch (Exception e) {
                throw new ServletException("Exception thrown in InternalErrorHandleServlet", e);
            }
        }
    }
}

From source file:org.wso2.carbon.rssmanager.core.dao.util.EntityManager.java

public synchronized boolean beginTransaction() throws RSSManagerException {
    if (log.isDebugEnabled()) {
        log.debug("beginTransaction()");
    }//from  ww w .ja va  2s.co m

    if (this.isInTransaction()) {
        return false;
    }

    if (activeNestedTransactions.get() == 0) {
        //this.getRSSTransactionManager().begin();

        UserTransaction utx = transactions.get();
        if (utx == null) {
            utx = getUserTransaction();
            if (utx == null) {
                throw new RSSManagerException(" Can't obtain UserTransaction ");
            }
            transactions.set(utx);
        }
        try {
            utx.begin();
            //getTransactionManager().begin();
        } catch (Exception e) {
            throw new RSSManagerException(e);
        }
    }
    activeNestedTransactions.set(activeNestedTransactions.get() + 1);
    return true;
}

From source file:org.wso2.carbon.rssmanager.core.dao.util.EntityManager.java

public synchronized boolean beginTransactionOnly() throws RSSManagerException {
    if (log.isDebugEnabled()) {
        log.debug("beginTransaction()");
    }/*  ww w .  j  a v  a2 s.  c om*/

    UserTransaction utx = transactions.get();
    try {
        utx.begin();
    } catch (Exception e) {
        throw new RSSManagerException(e);
    }

    return true;
}