Example usage for javax.persistence EntityManager find

List of usage examples for javax.persistence EntityManager find

Introduction

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

Prototype

public <T> T find(Class<T> entityClass, Object primaryKey);

Source Link

Document

Find by primary key.

Usage

From source file:net.anthonychaves.bookmarks.service.TokenService.java

public String setupNewLoginToken(User user) {
    PersistentLoginToken token = new PersistentLoginToken();
    EntityManager em = emf.createEntityManager();

    em.getTransaction().begin();/* ww w  .  ja  v a 2 s  .  co m*/
    User u = em.find(User.class, user.getId());
    token.setUser(u);
    em.persist(token);
    em.getTransaction().commit();

    return token.getId();
}

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

public static void getRelatedBusinesses(EntityManager em, Direction direction, String focalKey,
        org.uddi.api_v3.KeyedReference keyedRef, org.uddi.api_v3.RelatedBusinessInfos relatedBusinessInfos,
        Date modifiedAfter, Date modifiedBefore) throws DispositionReportFaultMessage {
    if (relatedBusinessInfos == null)
        relatedBusinessInfos = new org.uddi.api_v3.RelatedBusinessInfos();
    org.apache.juddi.model.BusinessEntity focalBusiness = null;
    try {//from  w w w  .  j  a v  a2 s  .  com
        focalBusiness = em.find(org.apache.juddi.model.BusinessEntity.class, focalKey);
    } catch (ClassCastException e) {
    }
    if (focalBusiness == null)
        throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.BusinessNotFound", focalKey));

    List<org.apache.juddi.model.PublisherAssertion> pubAssertList = null;
    if (direction == Direction.FROM_KEY)
        pubAssertList = focalBusiness.getPublisherAssertionsForFromKey();
    else
        pubAssertList = focalBusiness.getPublisherAssertionsForToKey();

    if (pubAssertList != null) {
        for (org.apache.juddi.model.PublisherAssertion modelPublisherAssertion : pubAssertList) {
            if ("true".equalsIgnoreCase(modelPublisherAssertion.getFromCheck())
                    && "true".equalsIgnoreCase(modelPublisherAssertion.getToCheck())) {
                if (keyedRef != null) {
                    if (!keyedRef.getTModelKey().equals(modelPublisherAssertion.getTmodelKey())
                            || !keyedRef.getKeyName().equals(modelPublisherAssertion.getKeyName())
                            || !keyedRef.getKeyValue().equals(modelPublisherAssertion.getKeyValue())) {
                        continue;
                    }
                }

                org.apache.juddi.model.BusinessEntity modelRelatedBusiness = null;
                if (direction == Direction.FROM_KEY)
                    modelRelatedBusiness = em.find(org.apache.juddi.model.BusinessEntity.class,
                            modelPublisherAssertion.getId().getToKey());
                else
                    modelRelatedBusiness = em.find(org.apache.juddi.model.BusinessEntity.class,
                            modelPublisherAssertion.getId().getFromKey());

                if (modifiedAfter != null
                        && modifiedAfter.after(modelRelatedBusiness.getModifiedIncludingChildren()))
                    continue;

                if (modifiedBefore != null
                        && modifiedBefore.before(modelRelatedBusiness.getModifiedIncludingChildren()))
                    continue;

                org.uddi.api_v3.RelatedBusinessInfo apiRelatedBusinessInfo = new org.uddi.api_v3.RelatedBusinessInfo();

                MappingModelToApi.mapRelatedBusinessInfo(modelPublisherAssertion, modelRelatedBusiness,
                        direction, apiRelatedBusinessInfo);

                relatedBusinessInfos.getRelatedBusinessInfo().add(apiRelatedBusinessInfo);
            }
        }
    }

}

From source file:com.sixsq.slipstream.persistence.Run.java

public static Run load(String resourceUri) {
    EntityManager em = PersistenceUtil.createEntityManager();
    Run run = em.find(Run.class, resourceUri);
    em.close();//from  w w  w. ja v  a2s.c  o m
    return run;
}

From source file:de.berlios.jhelpdesk.dao.jpa.UserDAOJpa.java

@Transactional(readOnly = false)
public void updatePasswordAndSalt(final User user, final String password) {
    this.jpaTemplate.execute(new JpaCallback<Object>() {
        public Object doInJpa(EntityManager em) throws PersistenceException {
            User u = em.find(User.class, user.getUserId());
            if (u != null) {
                u.setPassword(password); // TODO: zbada czy to ma sens (vide moppee)
                em.merge(u);/*from   w  ww . j  a va2 s .  c om*/
            }
            return null;
        }
    });
}

From source file:org.eclipse.jubula.client.core.businessprocess.ComponentNamesBP.java

/**
 * Lock the TC if it is reused for the first time. This prevents deletion of
 * the TC while the editor is not saved.
 * /*ww w .  ja v a2 s  .  c  om*/
 * @param sess
 *            DB session for locking purposes
 * @param refCompName
 *            Component Name to be used as a reference.
 * @param isReferencedByThisAction
 *            tells if there was a reference created by the current action,
 *            i.e. there is one references even if no other TC in the db
 *            references this one.
 * @throws PMAlreadyLockedException
 *             if the TC is locked by someone else
 * @throws PMDirtyVersionException
 *             if the TC was modified outside this instance of the
 *             application.
 * @throws PMObjectDeletedException
 *             if the po as deleted by another concurrently working user
 */
public static void handleFirstReference(EntityManager sess, IComponentNamePO refCompName,
        boolean isReferencedByThisAction)
        throws PMDirtyVersionException, PMObjectDeletedException, PMAlreadyLockedException {

    IComponentNamePO name = refCompName;
    if (name.getId() != null) {
        int minSize = 0;
        if (isReferencedByThisAction) {
            minSize = 1;
        }

        if (CompNamePM.getNumReuseInstances(sess, GeneralStorage.getInstance().getProject().getId(),
                name.getGuid()) <= minSize) {

            final EntityManager lockSession = sess;
            // make sure there is no old version
            // in the session cache
            try {
                lockSession.detach(refCompName);
                name = lockSession.find(name.getClass(), name.getId());
            } catch (PersistenceException he) {
                // Continue since we are just refreshing the cache
                log.error(Messages.StrayPersistenceException + StringConstants.DOT + StringConstants.DOT, he);
            }
            if (!LockManager.instance().lockPO(lockSession, name, false)) {
                throw new PMAlreadyLockedException(name, Messages.OrginalTestcaseLocked + StringConstants.DOT,
                        MessageIDs.E_OBJECT_IN_USE);
            }
        }
    }
}

From source file:net.anthonychaves.bookmarks.service.BookmarkService.java

public Object[] updateTags(User user, int id, String tags) {
    String cleanTags = cleanTags(tags);

    EntityManager em = emf.createEntityManager();

    em.getTransaction().begin();//from  w  ww .ja  v a2s . c  om
    User u = em.find(User.class, user.getId());
    Bookmark b = em.find(Bookmark.class, id);
    if (b.getUser().getId() != u.getId()) {
        throw new RuntimeException("Please don't try to delete bookmarks that aren't yours.");
    }

    String originalTags = b.getTags();
    b.setTags(cleanTags);
    em.getTransaction().commit();

    List<String> diffTags = diffTags(originalTags, cleanTags);

    return new Object[] { u, b, diffTags };
}

From source file:org.croodie.resource.UserServerResource.java

@Delete
public Representation deleteUser(Representation entity) {
    Form form = new Form(entity);
    String id = form.getFirstValue("id");
    EntityManagerFactory emf = EMF.get();
    EntityManager em = emf.createEntityManager();
    try {/*  w  w  w .  j av a2s. com*/
        User user = em.find(User.class, id);
        em.remove(user);
    } finally {
        em.close();
    }
    return null;
}

From source file:net.anthonychaves.bookmarks.service.TagService.java

public List<BookmarkDetail> findBookmarksByTag(String tag, User user) {
    List<byte[]> bookmarkIds = new ArrayList<byte[]>();
    try {/*from w w w . j a  v  a 2s  .c  o  m*/
        bookmarkIds = jredis.lrange(tag, 0, 50000);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    User u = em.find(User.class, user.getId());
    javax.persistence.Query query = em.createQuery(
            "select new net.anthonychaves.bookmarks.models.BookmarkDetail(b.id, b.title, b.url, b.tags) from Bookmark b where b.id in (:ids) and b.user = :user order by b.id desc")
            .setParameter("ids", bookmarkIds).setParameter("user", u);
    List<BookmarkDetail> bookmarks = (List<BookmarkDetail>) query.getResultList();
    em.getTransaction().rollback();

    return bookmarks;
}

From source file:net.anthonychaves.bookmarks.service.TokenService.java

public User loginWithToken(String tokenId) {
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();/* w w w  .  j  a v a  2  s .  c  o  m*/
    PersistentLoginToken token = (PersistentLoginToken) em.find(PersistentLoginToken.class, tokenId);

    User user = null;
    if (token != null) {
        user = token.getUser();
        em.remove(token);
        em.getTransaction().commit();
    } else {
        em.getTransaction().rollback();
        //TODO this is a forgery attempt
        throw new RuntimeException("Attempted login token cookie forgery");
    }
    return user;
}

From source file:io.coala.bind.LocalId.java

@Override
public LocalIdDao persist(final EntityManager em) {
    if (this.pk != null)
        return em.find(LocalIdDao.class, this.pk); // cached?
    final LocalIdDao result = JPAUtil.<LocalIdDao>findOrCreate(em, () -> LocalIdDao.find(em, this),
            () -> LocalIdDao.create(em, this));
    this.pk = result.pk;
    return result;
}