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:org.apache.juddi.api.impl.UDDICustodyTransferImpl.java

public void transferEntities(TransferEntities body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//w ww  . j  a v a 2s  .c o m
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidateCustodyTransfer(publisher).validateTransferEntities(em, body);

        // Once validated, the ownership transfer is as simple as switching the publisher
        KeyBag keyBag = body.getKeyBag();
        List<String> keyList = keyBag.getKey();
        for (String key : keyList) {
            UddiEntity uddiEntity = em.find(UddiEntity.class, key);
            uddiEntity.setAuthorizedName(publisher.getAuthorizedName());

            if (uddiEntity instanceof BusinessEntity) {
                BusinessEntity be = (BusinessEntity) uddiEntity;

                List<BusinessService> bsList = be.getBusinessServices();
                for (BusinessService bs : bsList) {
                    bs.setAuthorizedName(publisher.getAuthorizedName());

                    List<BindingTemplate> btList = bs.getBindingTemplates();
                    for (BindingTemplate bt : btList)
                        bt.setAuthorizedName(publisher.getAuthorizedName());
                }
            }
        }

        // After transfer is finished, the token can be removed
        org.uddi.custody_v3.TransferToken apiTransferToken = body.getTransferToken();
        String transferTokenId = new String(apiTransferToken.getOpaqueToken());
        org.apache.juddi.model.TransferToken modelTransferToken = em
                .find(org.apache.juddi.model.TransferToken.class, transferTokenId);
        em.remove(modelTransferToken);

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(CustodyTransferQuery.TRANSFER_ENTITIES, QueryStatus.SUCCESS, procTime);

    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }

}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public void deleteUser(int userid) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    BakerUser u = entityManager.find(BakerUser.class, userid);

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();/* w ww  . j  a  v a 2s  .com*/

    entityManager.remove(u);

    entityTransaction.commit();
}

From source file:info.dolezel.jarss.rest.v1.FeedsService.java

@GET
@Produces(MediaType.APPLICATION_JSON)// ww  w  .ja va  2s .  co m
@Path("{id}/headlines")
public Response getArticleHeadlines(@Context SecurityContext context, @PathParam("id") int feedId,
        @QueryParam("skip") int skip, @QueryParam("limit") int limit) {
    EntityManager em;
    List<Object[]> articles;
    Query query;
    ArticleHeadlineData[] result;
    Feed feed;
    User user;

    user = (User) context.getUserPrincipal();
    em = HibernateUtil.getEntityManager();

    try {

        feed = em.find(Feed.class, feedId);
        if (feed == null) {
            return Response.status(Response.Status.NOT_FOUND)
                    .entity(new ErrorDescription("Feed does not exist")).build();
        }
        if (!feed.getUser().equals(user)) {
            return Response.status(Response.Status.FORBIDDEN)
                    .entity(new ErrorDescription("Feed not owned by user")).build();
        }

        query = em.createQuery(
                "SELECT fid, fi from FeedItemData fid LEFT OUTER JOIN fid.feedItems AS fi where fid.feedData = :fd and (fi is null or fi.feed = :feed) order by fid.date desc",
                Object[].class).setParameter("fd", feed.getData()).setParameter("feed", feed)
                .setFirstResult(skip);

        if (limit > 0)
            query.setMaxResults(limit);

        articles = query.getResultList();

        result = new ArticleHeadlineData[articles.size()];
        for (int i = 0; i < articles.size(); i++) {
            FeedItemData article = (FeedItemData) articles.get(i)[0];
            FeedItem feedItem = (FeedItem) articles.get(i)[1];

            ArticleHeadlineData data = new ArticleHeadlineData();
            String text;

            data.setPublished(article.getDate().getTime());
            data.setTitle(article.getTitle());
            data.setId(article.getId());

            text = StringUtils.html2text(article.getText());

            if (text.length() > 130)
                text = text.substring(0, 130);

            data.setExcerpt(text);
            data.setLink(article.getLink());

            if (feedItem != null) {
                data.setRead(feedItem.isRead());
                data.setStarred(feedItem.isStarred());
            }

            result[i] = data;
        }

        return Response.ok(result).build();
    } finally {
        em.close();
    }
}

From source file:com.jada.admin.customAttribute.CustomAttributeGroupMaintAction.java

public ActionForward addCustomAttributeDetail(ActionMapping mapping, ActionForm actionForm,
        HttpServletRequest request, HttpServletResponse response) throws Throwable {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    CustomAttributeGroupMaintActionForm form = (CustomAttributeGroupMaintActionForm) actionForm;
    AdminBean adminBean = getAdminBean(request);

    JSONEscapeObject jsonResult = new JSONEscapeObject();
    jsonResult.put("status", Constants.WEBSERVICE_STATUS_SUCCESS);

    Long customAttribId = Format.getLong(form.getCustomAttribId());
    CustomAttribute customAttribute = (CustomAttribute) em.find(CustomAttribute.class, customAttribId);
    Long customAttribGroupId = Format.getLong(form.getCustomAttribGroupId());
    CustomAttributeGroup customAttributeGroup = (CustomAttributeGroup) em.find(CustomAttributeGroup.class,
            customAttribGroupId);//from  w w  w  .  j  a v a 2 s.  com
    int seqNum = 0;
    Iterator<?> iterator = customAttributeGroup.getCustomAttributeDetails().iterator();
    boolean found = false;
    while (iterator.hasNext()) {
        CustomAttributeDetail customAttributeDetail = (CustomAttributeDetail) iterator.next();
        if (customAttributeDetail.getCustomAttribute().getCustomAttribId()
                .equals(customAttribute.getCustomAttribId())) {
            found = true;
        }
        if (customAttributeDetail.getSeqNum().intValue() >= seqNum) {
            seqNum = customAttributeDetail.getSeqNum() + 1;
        }
    }

    if (!found) {
        CustomAttributeDetail customAttributeDetail = new CustomAttributeDetail();
        customAttributeDetail.setCustomAttribute(customAttribute);
        customAttributeDetail.setSeqNum(seqNum);
        customAttributeDetail.setRecUpdateBy(adminBean.getUser().getUserId());
        customAttributeDetail.setRecUpdateDatetime(new Date(System.currentTimeMillis()));
        customAttributeDetail.setRecCreateBy(adminBean.getUser().getUserId());
        customAttributeDetail.setRecCreateDatetime(new Date(System.currentTimeMillis()));
        customAttributeGroup.getCustomAttributeDetails().add(customAttributeDetail);
        em.persist(customAttributeDetail);
    }

    streamWebService(response, jsonResult.toHtmlString());
    return null;
}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public void deleteProperty(int propid) {

    EntityManager entityManager = entityManagerFactory.createEntityManager();
    BakerProperty c = entityManager.find(BakerProperty.class, propid);

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();/*from  w  w  w .j av a 2s  . c  o  m*/
    entityManager.remove(c);
    entityTransaction.commit();

}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public DeploymentDescriptor readDeploymentByID(int deploymentId) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    DeploymentDescriptor u = entityManager.find(DeploymentDescriptor.class, deploymentId);
    return u;// www.  ja va 2  s  .  c  o m
}

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;//from  w ww . j a  v a2  s  .  com
    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:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public void deleteSubscribedResource(int smId) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    SubscribedResource sm = entityManager.find(SubscribedResource.class, smId);

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();//from   w  ww .j av a 2 s. com
    entityManager.remove(sm);
    entityTransaction.commit();
}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public void deleteDeployment(int id) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    DeploymentDescriptor c = entityManager.find(DeploymentDescriptor.class, id);

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();//w  ww  .  java  2 s .c  o  m
    entityManager.remove(c);
    entityTransaction.commit();

}

From source file:org.opencastproject.adminui.usersettings.UserSettingsService.java

/**
 * Update a user setting that currently exists using its unique id to find it.
 * @param id The id for the user setting.
 * @param key The key for the user setting.
 * @param value The value for the user setting.
 * @return The updated {@link UserSetting}.
 * @throws UserSettingsServiceException/* w  w w .  j  a  v a  2  s . c  o  m*/
 */
public UserSetting updateUserSetting(long id, String key, String value) throws UserSettingsServiceException {
    EntityManager em = null;
    EntityTransaction tx = null;
    String orgId = "";
    String username = "";
    logger.debug("Updating user setting id: %d key: %s value: %s", id, key, value);
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        orgId = securityService.getOrganization().getId();
        username = securityService.getUser().getUsername();
        UserSettingDto userSettingDto = em.find(UserSettingDto.class, id);
        em.persist(userSettingDto);
        userSettingDto.setKey(key);
        userSettingDto.setValue(value);
        tx.commit();
        return userSettingDto.toUserSetting();
    } catch (Exception e) {
        logger.error("Could not update user setting username '%s' org:'%s' id:'%d' key:'%s' value:'%s':\n%s",
                username, orgId, id, key, value, ExceptionUtils.getStackTrace(e));
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new UserSettingsServiceException(e);
    } finally {
        if (em != null) {
            em.close();
        }
    }
}