Example usage for javax.persistence EntityTransaction begin

List of usage examples for javax.persistence EntityTransaction begin

Introduction

In this page you can find the example usage for javax.persistence EntityTransaction begin.

Prototype

public void begin();

Source Link

Document

Start a resource transaction.

Usage

From source file:com.busimu.core.dao.impl.UserMngDaoPolicyJpaImpl.java

/**
 * {@inheritDoc}//from  w ww.  j  a  va 2  s.  c om
 */
@Override
public void storeLicenses(Set<License> licenses) {
    EntityManager em = ((EntityManagerHolder) TransactionSynchronizationManager.getResource(emf))
            .getEntityManager();
    EntityTransaction tx = em.getTransaction();
    if (!tx.isActive()) {
        tx.begin();
    }
    for (License l : licenses) {
        em.persist(l);
    }
    tx.commit();
}

From source file:de.iai.ilcd.model.dao.AbstractDao.java

/**
 * Default remove: bring back to persistence context if required and delete
 * /*  w  ww. j a v a2 s  .  co  m*/
 * @param objs
 *            objects to remove
 * @return removed objects
 * @throws Exception
 *             on errors (transaction is being rolled back)
 */
public Collection<T> remove(Collection<T> objs) throws Exception {
    if (objs == null || objs.isEmpty()) {
        return null;
    }
    Collection<T> res = new ArrayList<T>();
    EntityManager em = PersistenceUtil.getEntityManager();
    EntityTransaction t = em.getTransaction();

    try {
        t.begin();
        for (T obj : objs) {
            T tmp = em.contains(obj) ? obj : em.merge(obj);
            em.remove(tmp);
            res.add(tmp);
        }
        t.commit();
        return res;
    } catch (Exception e) {
        t.rollback();
        throw e;
    }
}

From source file:kirchnerei.note.model.DataService.java

public boolean removeNote(Long id) {
    if (NumberUtils.isEmpty(id)) {
        return false;
    }//w  w w  .j a v a 2  s . c o  m
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = entityService.get();
        tx = em.getTransaction();
        tx.begin();
        Note note = em.find(Note.class, id);
        if (note == null) {
            return false;
        }
        Category category = note.getCategory();
        category.getNotes().remove(note);
        note.setCategory(null);
        em.remove(note);
        if (category.getNotes().isEmpty()) {
            LogUtils.debug(log, "empty category '%s', then remove it", category.getTitle());
            em.remove(category);
        }
        EntityService.commit(tx);
        return true;
    } catch (Exception e) {
        EntityService.rollback(tx);
        return false;
    } finally {
        EntityService.close(em);
    }
}

From source file:org.apache.juddi.api.impl.UDDIv2PublishImpl.java

private String getUsername(String authinfo) {
    String user = "N/A";

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*w  ww  .  j av  a2s.  com*/

        tx.begin();
        user = publishService.getEntityPublisher(em, authinfo).getAuthorizedName();
        tx.commit();
    } catch (Exception ex) {
        logger.error(ex);
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
    return user;
}

From source file:org.sakaiproject.kernel.authz.simple.SubjectPermissionListener.java

/**
 * {@inheritDoc}//from ww  w . j  a v a  2s . c o m
 *
 * @see org.sakaiproject.kernel.jcr.api.JcrContentListener#onEvent(int,
 *      java.lang.String, java.lang.String, java.lang.String)
 */
public void onEvent(int type, String userID, String filePath, String fileName) {
    if (fileName.equals(KernelConstants.GROUP_FILE_NAME)) {
        InputStream in = null;
        try {
            in = jcrNodeFactoryService.getInputStream(filePath);
            String groupBody = IOUtils.readFully(in, "UTF-8");
            if (groupBody != null && groupBody.length() > 0) {
                EntityTransaction transaction = entityManager.getTransaction();

                if (!transaction.isActive()) {
                    transaction.begin();
                }
                // update the index for subjects and groups
                updateSubjectPermissionIndex(groupBody);

                // update the index used for searching sites
                updateSiteIndex(groupBody, filePath);

                transaction.commit();
            }
        } catch (UnsupportedEncodingException e) {
            LOG.error(e);
        } catch (IOException e) {
            LOG.warn("Failed to read userenv " + filePath + " cause :" + e.getMessage());
            if (debug)
                LOG.debug(e);
        } catch (RepositoryException e) {
            LOG.warn("Failed to read userenv for " + filePath + " cause :" + e.getMessage());
            if (debug)
                LOG.debug(e);
        } catch (JCRNodeFactoryServiceException e) {
            LOG.warn("Failed to read userenv for " + filePath + " cause :" + e.getMessage());
            if (debug)
                LOG.debug(e);
        } finally {
            try {
                in.close();
            } catch (Exception ex) {// not interested in this
            }

        }
    }

}

From source file:kirchnerei.note.model.DataService.java

public Long storeNote(NoteData noteData) {
    EntityManager em = null;//from w  ww . jav  a  2s .c o m
    EntityTransaction tx = null;
    try {
        em = entityService.get();
        tx = em.getTransaction();
        tx.begin();
        // search for category
        String category = noteData.getCategory();
        if (StringUtils.isEmpty(category)) {
            LogUtils.warn(log, "note without category is not allow [%s]", noteData);
            return null;
        }
        TypedQuery<Category> q = em.createNamedQuery("findCategory", Category.class);
        q.setParameter("category", category);
        Category cat = getSingleResult(q);
        if (cat == null) {
            // a new category
            cat = new Category();
            cat.setTitle(category);
            em.persist(cat);
        }
        final Note note;
        if (NumberUtils.isEmpty(noteData.getId())) {
            // create a new note
            note = beanCopy.copy(noteData, Note.class, noteProperties);
            note.setCategory(cat);
            cat.getNotes().add(note);
        } else {
            // update an existed note
            note = em.find(Note.class, noteData.getId());
            beanCopy.copy(noteData, note, noteProperties);
            if (!NumberUtils.compare(note.getCategory().getId(), cat.getId())) {
                // move to other category
                note.getCategory().getNotes().remove(note);
                cat.getNotes().add(note);
                note.setCategory(cat);
            }
        }
        EntityService.commit(tx);
        return note.getId();
    } catch (Exception e) {
        EntityService.rollback(tx);
        return null;
    } finally {
        EntityService.close(em);
    }
}

From source file:com.espirit.moddev.examples.uxbridge.newswidget.test.CommandITCase.java

/**
 * Before test./*from www  .  j  a  v a  2 s .c o  m*/
 *
 * @throws Exception the exception
 */
@Before
public void beforeTest() throws Exception {
    EntityManager em = emf.createEntityManager();

    EntityTransaction tx = em.getTransaction();
    tx.begin();
    em.createQuery("DELETE FROM article").executeUpdate();
    tx.commit();
    em.close();
}

From source file:org.apache.james.user.jpa.JPAUsersRepository.java

/**
 * Removes a user from the repository// w ww  .  ja va  2  s  .  c o  m
 * 
 * @param name
 *            the user to remove from the repository
 * @throws UsersRepositoryException
 */
public void removeUser(String name) throws UsersRepositoryException {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    final EntityTransaction transaction = entityManager.getTransaction();
    try {
        transaction.begin();
        if (entityManager.createNamedQuery("deleteUserByName").setParameter("name", name).executeUpdate() < 1) {
            transaction.commit();
            throw new UsersRepositoryException("User " + name + " does not exist");
        } else {
            transaction.commit();
        }
    } catch (PersistenceException e) {
        getLogger().debug("Failed to remove user", e);
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw new UsersRepositoryException("Failed to remove user " + name, e);
    } finally {
        entityManager.close();
    }
}

From source file:org.apache.james.user.jpa.JPAUsersRepository.java

/**
 * @see/*from w w w.  j a v  a  2 s .  c o m*/
 * org.apache.james.user.lib.AbstractUsersRepository#doAddUser(java.lang.String, java.lang.String)
 */
protected void doAddUser(String username, String password) throws UsersRepositoryException {
    String lowerCasedUsername = username.toLowerCase();
    if (contains(lowerCasedUsername)) {
        throw new UsersRepositoryException(lowerCasedUsername + " already exists.");
    }
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    final EntityTransaction transaction = entityManager.getTransaction();
    try {
        transaction.begin();
        JPAUser user = new JPAUser(lowerCasedUsername, password, algo);
        entityManager.persist(user);
        transaction.commit();
    } catch (PersistenceException e) {
        getLogger().debug("Failed to save user", e);
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw new UsersRepositoryException("Failed to add user" + username, e);
    } finally {
        entityManager.close();
    }
}

From source file:org.sakaiproject.kernel.authz.simple.UserEnvironmentListener.java

/**
 * {@inheritDoc}//from  w w w  .  j a va 2 s . c om
 *
 * @see org.sakaiproject.kernel.jcr.api.JcrContentListener#onEvent(int,
 *      java.lang.String, java.lang.String, java.lang.String)
 */
public void onEvent(int type, String userID, String filePath, String fileName) {
    if (filePath.startsWith(userEnvironmentBase)) {
        if (fileName.equals(KernelConstants.USERENV)) {
            String userEnvBody = null;
            try {
                userEnvBody = IOUtils.readFully(jcrNodeFactoryService.getInputStream(filePath), "UTF-8");
                if (userEnvBody != null && userEnvBody.length() > 0) {
                    UserEnvironmentBean ue = beanConverter.convertToObject(userEnvBody,
                            UserEnvironmentBean.class);
                    ue.seal();

                    userEnvironmentResolverService.expire(ue.getUser().getUuid());

                    // the user environment bean contains a list of
                    // subjects, which the
                    // users membership of groups
                    Query query = entityManager.createNamedQuery(GroupMembershipBean.FINDBY_USER);
                    query.setParameter(GroupMembershipBean.USER_PARAM, ue.getUser().getUuid());
                    List<?> membershipList = query.getResultList();
                    List<GroupMembershipBean> toAdd = new ArrayList<GroupMembershipBean>();
                    List<GroupMembershipBean> toRemove = new ArrayList<GroupMembershipBean>();

                    for (Object o : membershipList) {
                        GroupMembershipBean groupMembershipBean = (GroupMembershipBean) o;
                        String subjectToken = groupMembershipBean.getSubjectToken();
                        boolean found = false;
                        for (String subject : ue.getSubjects()) {
                            if (subjectToken.equals(subject)) {
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            toRemove.add(groupMembershipBean);
                        }
                    }

                    for (String subject : ue.getSubjects()) {
                        boolean found = false;
                        for (Object o : membershipList) {
                            GroupMembershipBean groupMembershipBean = (GroupMembershipBean) o;
                            String subjectToken = groupMembershipBean.getSubjectToken();
                            if (subject.equals(subjectToken)) {
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            toAdd.add(new GroupMembershipBean(ue.getUser().getUuid(), subject));
                        }
                    }

                    UserBean u = ue.getUserBean();

                    Query userQuery = entityManager.createNamedQuery(UserBean.FINDBY_UID);
                    userQuery.setParameter(UserBean.UID_PARAM, u.getUuid());
                    List<?> userBeansByUID = userQuery.getResultList();

                    Query userQuery2 = entityManager.createNamedQuery(UserBean.FINDBY_EID);
                    userQuery2.setParameter(UserBean.EID_PARAM, u.getEid());
                    List<?> userBeansByEID = userQuery.getResultList();
                    boolean foundUserBean = false;
                    List<UserBean> toRemoveUserBeans = new ArrayList<UserBean>();
                    for (Object o : userBeansByUID) {
                        UserBean ub = (UserBean) o;
                        if (!u.getUuid().equals(ub.getUuid()) || !u.getEid().equals(ub.getEid())) {
                            if (!toRemoveUserBeans.contains(ub)) {
                                toRemoveUserBeans.add(ub);
                            }
                        } else {
                            foundUserBean = true;
                        }
                    }
                    for (Object o : userBeansByEID) {
                        UserBean ub = (UserBean) o;
                        if (!u.getUuid().equals(ub.getUuid()) || !u.getEid().equals(ub.getEid())) {
                            if (!toRemoveUserBeans.contains(ub)) {
                                toRemoveUserBeans.add(ub);
                            }
                        } else {
                            foundUserBean = true;
                        }
                    }

                    EntityTransaction transaction = entityManager.getTransaction();
                    transaction.begin();
                    if (!foundUserBean) {
                        UserBean ub = new UserBean(u.getUuid(), u.getEid());
                        entityManager.persist(ub);
                    }
                    for (UserBean ub : toRemoveUserBeans) {
                        entityManager.remove(ub);
                    }
                    for (GroupMembershipBean gm : toRemove) {
                        entityManager.remove(gm);
                    }
                    for (GroupMembershipBean gm : toAdd) {
                        entityManager.persist(gm);
                    }
                    transaction.commit();
                }

            } catch (UnsupportedEncodingException e) {
                LOG.error(e);
            } catch (IOException e) {
                LOG.warn("Failed to read userenv " + filePath + " cause :" + e.getMessage());
                if (debug)
                    LOG.debug(e);
            } catch (RepositoryException e) {
                LOG.warn("Failed to read userenv for " + filePath + " cause :" + e.getMessage());
                if (debug)
                    LOG.debug(e);
            } catch (JCRNodeFactoryServiceException e) {
                LOG.warn("Failed to read userenv for " + filePath + " cause :" + e.getMessage());
                if (debug)
                    LOG.debug(e);
            }
        }
    }
}