Example usage for javax.persistence EntityManager getTransaction

List of usage examples for javax.persistence EntityManager getTransaction

Introduction

In this page you can find the example usage for javax.persistence EntityManager getTransaction.

Prototype

public EntityTransaction getTransaction();

Source Link

Document

Return the resource-level EntityTransaction object.

Usage

From source file:edu.csueb.cs6320.utils.UserService.java

/**
 * doesnt set password!//from  w w  w .  j  ava 2s .  c  o  m
 * @param alteredUser
 */
public boolean updateUser(long userid, User alteredUser) {
    EntityManager em = Persistence.createEntityManagerFactory("TestPU").createEntityManager();
    User u = em.find(User.class, userid);
    if (u == null) {
        return false;
    }

    em.getTransaction().begin();
    u.setEmail(alteredUser.getEmail());
    u.setFirstName(alteredUser.getFirstName());
    u.setLastName(alteredUser.getLastName());
    u.setRole(alteredUser.getRole());
    em.getTransaction().commit();
    em.close();

    return true;
}

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

/**
 * {@inheritDoc}/*from w w  w. j a  v a 2s . co  m*/
 */
@Override
public void saveUser(User user) {
    EntityManager em = ((EntityManagerHolder) TransactionSynchronizationManager.getResource(emf))
            .getEntityManager();
    EntityTransaction tx = em.getTransaction();
    if (!tx.isActive()) {
        tx.begin();
    }
    em.persist(user);
    tx.commit();
}

From source file:controllers.modules.SetCoverBuilder.java

@BodyParser.Of(play.mvc.BodyParser.Json.class)
public static Result update(final UUID corpus, UUID setcover) {
    DocumentCorpus corpusObj = null;/* www. j  a v a2  s  .co m*/
    if (corpus != null) {
        corpusObj = fetchResource(corpus, DocumentCorpus.class);
    }

    // make sure we have the right combination.
    DocumentSetCover setCoverObj = null;
    if (setcover != null) {
        setCoverObj = fetchResource(setcover, DocumentSetCover.class);
        if (corpusObj == null) {
            corpusObj = setCoverObj.getBaseCorpus();
        } else if (ObjectUtils.notEqual(corpusObj, setCoverObj.getBaseCorpus())) {
            throw new IllegalArgumentException();
        }
    } else if (corpusObj == null) {
        throw new IllegalArgumentException();
    }

    JsonNode jsonBody = request().body().asJson();
    if (jsonBody == null && setcover != null) {
        throw new IllegalArgumentException();
    }
    if (jsonBody == null) {
        jsonBody = JsonNodeFactory.instance.objectNode();
    }

    DocumentSetCoverModel setCoverVM = null;
    setCoverVM = Json.fromJson(jsonBody, DocumentSetCoverModel.class);
    final SetCoverFactory factory = (SetCoverFactory) setCoverVM.toFactory().setOwnerId(getUsername());

    // set the default title.
    if (setcover == null && StringUtils.isEmpty(factory.getTitle())) {
        factory.setTitle("Optimized " + corpusObj.getTitle());
    }

    SetCoverFactory tmpFactory = (SetCoverFactory) new SetCoverFactory().setStore(corpusObj)
            .setTitle(factory.getTitle()).setDescription(factory.getDescription())
            .setOwnerId(factory.getOwnerId());

    // make basic creation/updation first.
    if (setcover == null) {
        setCoverObj = tmpFactory.create();
        em().persist(setCoverObj);
        setCoverVM = (DocumentSetCoverModel) createViewModel(setCoverObj);

        // if this is a simple change, just return from here.
        if (ObjectUtils.equals(
                ObjectUtils.defaultIfNull(factory.getTokenizingOptions(), new TokenizingOptions()),
                new TokenizingOptions())
                && factory.getWeightCoverage() == SetCoverFactory.DEFAULT_WEIGHT_COVERAGE) {
            return created(setCoverVM.asJson());
        }
        setcover = setCoverObj.getIdentifier();
    } else if (!StringUtils.equals(StringUtils.defaultString(tmpFactory.getTitle(), setCoverObj.getTitle()),
            setCoverObj.getTitle())
            || !StringUtils.equals(
                    StringUtils.defaultString(tmpFactory.getDescription(), setCoverObj.getDescription()),
                    setCoverObj.getDescription())) {

        tmpFactory.setEm(em()).setExistingId(setcover);
        setCoverObj = tmpFactory.create();
        em().merge(setCoverObj);
        setCoverVM = (DocumentSetCoverModel) createViewModel(setCoverObj);
        setCoverVM.populateSize(em(), setCoverObj);

        // if this is a simple change, just return from here.
        if (ObjectUtils.equals(
                ObjectUtils.defaultIfNull(factory.getTokenizingOptions(), new TokenizingOptions()),
                ObjectUtils.defaultIfNull(setCoverObj.getTokenizingOptions(), new TokenizingOptions()))
                && ObjectUtils.equals(factory.getWeightCoverage(), ObjectUtils.defaultIfNull(
                        setCoverObj.getWeightCoverage(), SetCoverFactory.DEFAULT_WEIGHT_COVERAGE))) {
            return ok(setCoverVM.asJson());
        }
    }

    // get rid of any old progress observer tokens and create a new one.
    finalizeProgress(setCoverObj.getId());
    createProgressObserverToken(setCoverObj.getId());
    watchProgress(factory, "create", setCoverObj.getId());

    final Context ctx = Context.current();
    final UUID setCoverId = setcover;

    Akka.future(new Callable<DocumentSetCover>() {
        @Override
        public DocumentSetCover call() throws Exception {
            try {
                return execute(new SareTxRunnable<DocumentSetCover>() {
                    @Override
                    public DocumentSetCover run(EntityManager em) throws Throwable {
                        bindEntityManager(em);
                        Context.current.set(ctx);

                        DocumentSetCover setCoverObj = null;
                        UUID corpusId = corpus;
                        if (corpusId == null) {
                            setCoverObj = fetchResource(setCoverId, DocumentSetCover.class);
                            corpusId = setCoverObj.getBaseCorpus().getIdentifier();
                        }

                        factory.setStore(fetchResource(corpusId, DocumentCorpus.class))
                                .setExistingId(setCoverId).setEm(em);

                        List<SetCoverDocument> oldDocuments = Lists.newArrayList(setCoverObj.getAllDocuments());
                        setCoverObj = factory.create();

                        em.flush();
                        em.merge(setCoverObj);
                        em.getTransaction().commit();
                        em.clear();

                        em.getTransaction().begin();
                        for (SetCoverDocument oldDocument : oldDocuments) {
                            if (Iterables.find(setCoverObj.getAllDocuments(), Predicates.equalTo(oldDocument),
                                    null) == null) {
                                SetCoverDocument tmpDocument = em.find(SetCoverDocument.class,
                                        oldDocument.getId());
                                em.remove(tmpDocument);
                            }
                        }

                        return setCoverObj;
                    }
                }, ctx);
            } catch (Throwable e) {
                Logger.error(LoggedAction.getLogEntry(ctx, "failed to build set cover"), e);
                throw new IllegalArgumentException(e);
            } finally {
                setProgressFinished(UuidUtils.toBytes(setCoverId));
            }
        }
    });

    return ok(setCoverVM.asJson());
}

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

/**
 * {@inheritDoc}// w w w  .j  a va 2s  .com
 */
@Override
public LoginHistory addLoginHistory(User user, Date loginDate, Date logoutDate) {
    EntityManager em = ((EntityManagerHolder) TransactionSynchronizationManager.getResource(emf))
            .getEntityManager();
    EntityTransaction tx = em.getTransaction();
    if (!tx.isActive()) {
        tx.begin();
    }
    LoginHistory history = user.addLoginHistory(loginDate, logoutDate);
    tx.commit();
    return history;
}

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

/**
 * {@inheritDoc}/*from   ww w.ja va 2 s .  co m*/
 */
@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:edu.csueb.cs6320.utils.UserService.java

public boolean updatePassword(long userid, String newPassword) {
    EntityManager em = Persistence.createEntityManagerFactory("TestPU").createEntityManager();
    User u = em.find(User.class, userid);
    if (u == null) {
        return false;
    }//from  w  w  w. ja  v  a2  s. c o m

    em.getTransaction().begin();

    // TODO: This block of code really belongs in User.setPassword()
    String salt = Auth.getSalt();
    u.setSalt(salt);
    try {
        u.setSaltedHashedPassword(Auth.hashPassword(newPassword, salt));
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        em.getTransaction().rollback();
        return false;
    }
    em.getTransaction().commit();
    em.close();

    return true;
}

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

/**
 * {@inheritDoc}/*from w w w.ja v  a  2  s  .co  m*/
 */
@Override
public User activateUser(User user, String licenseCode) {
    EntityManager em = ((EntityManagerHolder) TransactionSynchronizationManager.getResource(emf))
            .getEntityManager();
    EntityTransaction tx = em.getTransaction();
    License l = getLicenseByCode(em, licenseCode);
    if (l != null) {
        if (!tx.isActive()) {
            tx.begin();
        }
        user.setType(User.Type.valueOf(l.getType().name()));
        user.setStatus(User.Status.ACTIVE);
        user = em.merge(user);
        em.remove(l);
        tx.commit();
    }
    return user;
}

From source file:com.epam.training.taranovski.web.project.repository.implementation.OfferBidRepositoryImplementation.java

@Override
public List<Vacancy> getOffersForEmployee(Employee employee) {
    EntityManager em = entityManagerFactory.createEntityManager();
    List<Vacancy> list = new LinkedList<>();
    try {/*from ww  w  .  j  a v  a 2  s . com*/
        em.getTransaction().begin();

        TypedQuery<Vacancy> query = em.createNamedQuery("OfferBid.findVacancyOffersForEmployee", Vacancy.class);
        query.setParameter("employee", employee);
        list = query.getResultList();

        em.getTransaction().commit();
    } catch (RuntimeException e) {
        Logger.getLogger(OfferBidRepositoryImplementation.class.getName()).info(e);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        em.close();
    }

    return list;
}

From source file:com.epam.training.taranovski.web.project.repository.implementation.OfferBidRepositoryImplementation.java

@Override
public List<Vacancy> getBidsForEmployee(Employee employee) {
    EntityManager em = entityManagerFactory.createEntityManager();
    List<Vacancy> list = new LinkedList<>();
    try {//from w w w  . j  a v a 2 s.  c  o m
        em.getTransaction().begin();

        TypedQuery<Vacancy> query = em.createNamedQuery("OfferBid.findVacancyBidsForEmployee", Vacancy.class);
        query.setParameter("employee", employee);
        list = query.getResultList();

        em.getTransaction().commit();
    } catch (RuntimeException e) {
        Logger.getLogger(OfferBidRepositoryImplementation.class.getName()).info(e);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        em.close();
    }

    return list;
}

From source file:com.epam.training.taranovski.web.project.repository.implementation.OfferBidRepositoryImplementation.java

@Override
public List<Employee> getBidsForVacancy(Vacancy vacancy) {
    EntityManager em = entityManagerFactory.createEntityManager();
    List<Employee> list = new LinkedList<>();
    try {/*from  ww w. ja  v  a2  s  .  c  o  m*/
        em.getTransaction().begin();

        TypedQuery<Employee> query = em.createNamedQuery("OfferBid.findEmployeeBidsForVacancy", Employee.class);
        query.setParameter("vacancy", vacancy);
        list = query.getResultList();

        em.getTransaction().commit();
    } catch (RuntimeException e) {
        Logger.getLogger(OfferBidRepositoryImplementation.class.getName()).info(e);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        em.close();
    }

    return list;
}