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.ms123.common.ea.BaseEAServiceImpl.java

private Map importZipcodes(String storeId, String basedir) {
    StoreDesc sdesc = StoreDesc.get(storeId);
    PersistenceManager pm = m_nucleusService.getPersistenceManagerFactory(sdesc).getPersistenceManager();
    UserTransaction ut = m_nucleusService.getUserTransaction();
    Class _company = m_nucleusService.getClass(sdesc, "Company");
    Class _contact = m_nucleusService.getClass(sdesc, "Contact");
    Map mapping = initZipcodes();
    try {//  w  w w  .j  a va2  s  . co m
        LabeledCSVParser lp = new LabeledCSVParser(
                getCSVParser(new FileInputStream(new File(basedir, "zipcodes.csv"))));
        System.out.println("Persisting zipcodes");
        int num = 0;
        while (lp.getLine() != null) {
            if (ut.getStatus() != Status.STATUS_ACTIVE) {
                ut.begin();
            }
            // Zipcode zipcode = new Zipcode(); 
            Object zipcode = m_nucleusService.getClass(sdesc, "Zipcode").newInstance();

            String gemeindekennziffer = lp.getValueByLabel("Gemeindekennziffer");
            String ortname = lp.getValueByLabel("ORTNAME");
            String plz = lp.getValueByLabel("PLZ");
            String lkz = lp.getValueByLabel("LKZ");
            PropertyUtils.setProperty(zipcode, "lkz", lkz);
            PropertyUtils.setProperty(zipcode, "plz", plz);
            PropertyUtils.setProperty(zipcode, "ortname", ortname);
            PropertyUtils.setProperty(zipcode, "gemeindekennziffer", gemeindekennziffer);

            Collection cl = getContactList(pm, _company, plz);
            if (cl != null) {
                for (Object cx : cl) {
                    PropertyUtils.setProperty(cx, "zipcode", zipcode);
                    PropertyUtils.setProperty(cx, "lkz", lkz);
                }
            }
            cl = getContactList(pm, _contact, plz);
            if (cl != null) {
                for (Object cx : cl) {
                    PropertyUtils.setProperty(cx, "zipcode", zipcode);
                    PropertyUtils.setProperty(cx, "lkz", lkz);
                }
            }
            pm.makePersistent(zipcode);
            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.EACompanyContactImporter.java

private void doImport() throws Exception {
    LabeledCSVParser lp = new LabeledCSVParser(
            new ExcelCSVParser(new FileInputStream(new File(m_basedir, "ea.csv"))));
    int status;/*  w w  w.  j a  va  2s .  co m*/
    PersistenceManager pm = m_nucleusService.getPersistenceManagerFactory(m_storeDesc).getPersistenceManager();
    UserTransaction ut = m_nucleusService.getUserTransaction();
    int num = 0;
    Object company = null;
    String lastCompanyId = null;
    while (lp.getLine() != null) {
        String type = lp.getValueByLabel("type");
        String companyId = lp.getValueByLabel("companyId");
        if (type.startsWith("nok"))
            continue;
        if (ut.getStatus() != Status.STATUS_ACTIVE) {
            ut.begin();
        }
        String s[] = getStateAndEntity(type);
        Object obj = populate(lp, s[0], s[1]);

        if (!isEmpty(companyId)) {
            if (!companyId.equals(lastCompanyId)) {
                company = obj;
                lastCompanyId = companyId;
            }
            if (s[0].equals("contact")) {
                Set cl = (Set) PropertyUtils.getProperty(company, "contact_list");
                if (cl == null) {
                    cl = new HashSet();
                    PropertyUtils.setProperty(company, "contact_list", cl);
                }
                cl.add(obj);
            }
        }
        pm.makePersistent(obj);
        if ((num % 1000) == 1) {
            System.out.println(num + ":\t" + new Date().getTime());
            ut.commit();
        }
        num++;
    }
    if (ut.getStatus() == Status.STATUS_ACTIVE) {
        ut.commit();
    }
}

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

private void persistObject(Object o) throws Exception {
    UserTransaction ut = m_nucleusService.getUserTransaction();
    PersistenceManager pm = m_sessionContext.getPM();
    try {//from  w  ww  . j a  v  a  2s  .com
        ut.begin();
        pm.makePersistent(o);
        //m_sessionContext.makePersistent(o);
        ut.commit();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
    }
}

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

private Map _createOrUpdateContact(String email, Map data, Map communication, List<String> teams)
        throws Exception {
    Map ret = null;/*  w  ww.ja  va 2  s  . com*/
    StoreDesc sdesc = StoreDesc.get("ea_data");
    SessionContext sc = m_dataLayer.getSessionContext(sdesc);
    sc.setProperty("bypassTrigger", true);
    Map c = _getContactByEmail(sc, email);
    List<Map> teamList = new ArrayList();

    for (String tn : teams) {
        String teamid = teamIdExists(sc, tn);
        if (teamid == null)
            throw new RuntimeException("createOrUpdateUser:(teamid:" + tn + ") not found");
        Map m = new HashMap();
        m.put("teamid", teamid);
        m.put("value", teamid);
        teamList.add(m);
    }
    data.put("_team_list", teamList);
    data.put("email", email);

    if (communication == null) {
        communication = new HashMap();
    }

    UserTransaction ut = m_nucleusService.getUserTransaction();
    ut.begin();
    try {
        if (c != null) {
            c.putAll(data);
            Object comm = c.remove(COMMUNICATION_ENTITY);
            String commId = (String) PropertyUtils.getProperty(comm, "id");
            System.out.println("commId:" + commId);
            ret = m_dataLayer.updateObject(sc, c, CONTACT_ENTITY, (String) c.get("id"));
            if (communication.size() > 0) {
                m_dataLayer.updateObject(sc, communication, COMMUNICATION_ENTITY, commId);
            }
        } else {
            ret = m_dataLayer.insertObject(sc, data, CONTACT_ENTITY);
            //            communication.put("mail1", email);
            Map r = m_dataLayer.insertObject(sc, communication, COMMUNICATION_ENTITY, CONTACT_ENTITY,
                    (String) ret.get("id"));
        }
        ut.commit();
    } catch (Exception e) {
        sc.handleException(e);
    }
    return ret;
}

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

protected List<Map> persistObjects(SessionContext sc, Object obj, Map settings, int max) {
    List<Map> retList = new ArrayList();
    UserTransaction ut = sc.getUserTransaction();
    String mainEntity = null;// ww w. ja v  a  2s  .  c o  m
    Collection<Object> resultList = null;
    if (obj instanceof Collection) {
        resultList = (Collection) obj;
    } else {
        resultList = new ArrayList();
        resultList.add(obj);
    }
    Map outputTree = (Map) settings.get("output");
    Map<String, String> persistenceSpecification = (Map) outputTree.get("persistenceSpecification");
    System.out
            .println("persistObjects:" + resultList + ",persistenceSpecification:" + persistenceSpecification);
    String parentFieldName = null;
    Class parentClazz = null;
    String parentQuery = null;
    String updateQuery = null;
    PersistenceManager pm = sc.getPM();
    GroovyShell groovyShell = null;
    if (persistenceSpecification != null) {
        String parentLookup = persistenceSpecification.get("lookupRelationObjectExpr");
        String relation = persistenceSpecification.get("relation");
        if (!isEmpty(parentLookup) && !isEmpty(relation)) {
            String s[] = relation.split(",");
            parentClazz = sc.getClass(getBaseName(s[0]));
            parentFieldName = s[1];
            if (parentLookup.matches(FIELDNAME_REGEX)) {
                String q = isString(parentClazz, parentLookup) ? "'" : "";
                parentQuery = parentLookup + " == " + q + "${" + parentLookup + "}" + q;
            } else if (parentLookup.matches(FIELDNAME_REGEX + "," + FIELDNAME_REGEX)) {
                s = parentLookup.split(",");
                String q = isString(parentClazz, s[1]) ? "'" : "";
                parentQuery = s[0] + " == " + q + "${" + s[1] + "}" + q;
            } else {
                parentQuery = parentLookup;
            }
            groovyShell = new GroovyShell(this.getClass().getClassLoader(), new Binding(),
                    new CompilerConfiguration());
        }
        String updateLookup = persistenceSpecification.get("lookupUpdateObjectExpr");
        Class mainClass = null;
        if (resultList.size() > 0) {
            mainClass = resultList.iterator().next().getClass();
        }
        if (!isEmpty(updateLookup) && mainClass != null) {
            if (updateLookup.matches(FIELDNAME_REGEX)) {
                String q = isString(mainClass, updateLookup) ? "'" : "";
                updateQuery = updateLookup + " == " + q + "${" + updateLookup + "}" + q;
            } else {
                updateQuery = updateLookup;
            }
        }
    }
    try {
        int num = 0;
        if (resultList.size() > 0) {
            Class clazz = resultList.iterator().next().getClass();
            mainEntity = m_inflector.getEntityName(clazz.getSimpleName());
            String pk = getPrimaryKey(clazz);
            sc.setPrimaryKey(pk);
        }
        for (Object object : resultList) {
            if (max != -1 && num >= max) {
                break;
            }
            Map m = SojoObjectFilter.getObjectGraph(object, sc, 2);
            retList.add(m);
            ut.begin();
            Object origObject = null;
            if (updateQuery != null) {
                origObject = getObjectByFilter(groovyShell, pm, object.getClass(), object, updateQuery);
                System.out.println("origObject:" + origObject);
                if (origObject != null) {
                    sc.populate(m, origObject);
                    object = origObject;
                }
            }
            if (origObject == null && parentClazz != null) {
                Object parentObject = getObjectByFilter(groovyShell, pm, parentClazz, object, parentQuery);
                m_dataLayer.insertIntoMaster(sc, object, mainEntity, parentObject, parentFieldName);
            }
            m_dataLayer.makePersistent(sc, object);
            System.out.println("\tpersist:" + m_js.serialize(object));
            ut.commit();
            num++;
        }
    } catch (Throwable e) {
        e.printStackTrace();
        sc.handleException(ut, e);
    } finally {
        sc.handleFinally(ut);
    }
    return retList;
}

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

protected Map doImport(StoreDesc data_sdesc, Map settings, byte[] content, boolean withoutSave, int max)
        throws Exception {
    List<Map> mappings = null;
    List<Map> defaults = null;
    Map sourceSetup = null;/*from  w  w  w  . ja  v  a  2s.com*/
    String mainEntity = null;
    Smooks smooks = m_smooksFactory.createInstance();
    try {
        mappings = getListParameter(settings, MAPPING, false);
        defaults = getListParameter(settings, DEFAULTS, true);
        sourceSetup = getMapParameter(settings, SOURCE_SETUP, false);
        mainEntity = getStringParameter(settings, MAIN_ENTITY, false);
        SessionContext sessionContext = m_dataLayer.getSessionContext(data_sdesc);
        UserTransaction ut = sessionContext.getUserTransaction();
        try {
            String ftype = detectFileType(content);
            if (ftype == null) {
                throw new RuntimeException("BaseImportingServiceImpl.doImport:no Filecontent");
            }

            boolean isCsv = false;
            if ("text/plain".equals(ftype)) {
                isCsv = true;
            }
            Collection<Object> resultList = null;
            if (isCsv) {
                Map result = csvImport(sessionContext, mappings, defaults, sourceSetup, mainEntity, content);
                resultList = (Set) result.get("result");
            } else {
                Map entityTree = m_entityService.getEntityTree(data_sdesc, mainEntity, 3, null, null, true);
                XmlImporter xim = new XmlImporter();
                xim.setUserName(getUserName());
                xim.setModuleTree(entityTree);
                xim.setMax(max);
                xim.setDefaults(defaults);
                xim.setMainEntityName(mainEntity);
                xim.setSessionContext(sessionContext);
                Map<String, String> shortestMapping = getShortestMapping(mappings);
                if (shortestMapping == null) {
                    throw new RuntimeException("ImportingServiceImpl.xmlImport:invalid mapping");
                }
                removeSelectorPrefixFromMappings(mappings, shortestMapping.get("source"));
                xim.setMappings(mappings);
                String target = shortestMapping.get("target");
                if (!m_inflector.getClassName(target).equals(m_inflector.getClassName(mainEntity))) {
                    throw new RuntimeException("ImportingServiceImpl.xmlImport:wrong main mapping:"
                            + shortestMapping + "/mainEntity:" + mainEntity);
                }
                System.out.println("shortest_mapping:" + shortestMapping);
                smooks.addVisitor(xim, shortestMapping.get("source"));
                ExecutionContext executionContext = smooks.createExecutionContext();
                ByteArrayInputStream is = new ByteArrayInputStream(content);
                JavaResult result = new JavaResult();
                smooks.filterSource(executionContext, new StreamSource(is), result);
                resultList = xim.getResultList();
            }
            List<Map> retList = new ArrayList();
            int num = 0;
            if (resultList.size() > 0) {
                String pk = getPrimaryKey(resultList.iterator().next().getClass());
                sessionContext.setPrimaryKey(pk);
            }
            for (Object o : resultList) {
                if (max != -1 && num >= max)
                    break;
                Map m = SojoObjectFilter.getObjectGraph(o, sessionContext, 2);
                retList.add(m);
                List cv = sessionContext.validateObject(m, mainEntity);
                if (cv == null && m.get("_duplicated_id_") == null) {
                    if (!withoutSave) {
                        ut.begin();
                        m_dataLayer.makePersistent(sessionContext, o);
                        ut.commit();
                    }
                } else {
                    m.put("constraintViolations", cv);
                }
                num++;
                if ((num % 1000) == 0) {
                    System.out.println("commit1++++++++:" + num);
                }
            }
            String[] dbfields = getFieldsFromMapping(mappings);
            Map ret = new HashMap();
            ret.put("fields", dbfields);
            ret.put("result", retList);
            return ret;
        } catch (Throwable e) {
            e.printStackTrace();
            sessionContext.handleException(ut, e);
        } finally {
            sessionContext.handleFinally(ut);
        }
    } finally {
        smooks.close();
    }
    return new HashMap();
}

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  . ja v a2  s.c  o  m
        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);
    }
}

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 . ja  v  a 2  s  .  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 {//from   w w  w . jav a  2 s . c o  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  w w .  j  a  va  2 s . c  o m*/
    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");
}