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:de.zib.gndms.logic.model.TaskAction.java

/**
 *
 * Retrieves the AbstractTask from the database, which corresponds to {@code getModel()).
 * It is marked as done, by invoking {@code setDone(true)} on it and restored to the database.
 *
 * It will be set as {@code this}' the new model by calling {@code setModelAndBackup()}, which also makes a backup
 * of the new model.//from   w w w.j  a v  a  2 s. co  m
 *
 */
private void markAsDone() {
    final @NotNull AbstractTask model = getModel();
    if (!(getCancelled() || model.isDone())) {
        final EntityManager em = getEntityManager();
        try {
            em.getTransaction().begin();
            AbstractTask newModel = em.find(AbstractTask.class, getModel().getId());
            newModel.setDone(true);
            em.getTransaction().commit();
            setModelAndBackup(newModel);
        } catch (RuntimeException e) {
            trace("Non throwable exception: ", e);
        } finally {
            try {
                if (em.getTransaction().isActive())
                    em.getTransaction().rollback();
            } catch (RuntimeException e) {
                trace("Non throwable exception: ", e);
            }
        }
    }
}

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

public BindingDetail getBindingDetail(GetBindingDetail body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();
    try {/*from   www.  jav  a  2s.c  om*/
        new ValidateInquiry(null).validateGetBindingDetail(body);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.FIND_TMODEL, QueryStatus.FAILED, procTime);
        throw drfm;
    }

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        if (isAuthenticated())
            this.getEntityPublisher(em, body.getAuthInfo());

        BindingDetail result = new BindingDetail();

        List<String> bindingKeyList = body.getBindingKey();
        for (String bindingKey : bindingKeyList) {
            org.apache.juddi.model.BindingTemplate modelBindingTemplate = null;
            try {
                modelBindingTemplate = em.find(org.apache.juddi.model.BindingTemplate.class, bindingKey);
            } catch (ClassCastException e) {
            }
            if (modelBindingTemplate == null)
                throw new InvalidKeyPassedException(
                        new ErrorMessage("errors.invalidkey.BindingTemplateNotFound", bindingKey));

            org.uddi.api_v3.BindingTemplate apiBindingTemplate = new org.uddi.api_v3.BindingTemplate();

            MappingModelToApi.mapBindingTemplate(modelBindingTemplate, apiBindingTemplate);

            result.getBindingTemplate().add(apiBindingTemplate);
        }

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

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

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

public ServiceDetail getServiceDetail(GetServiceDetail body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();
    try {//from  w ww  .j av a2  s.co m
        new ValidateInquiry(null).validateGetServiceDetail(body);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.GET_SERVICEDETAIL, QueryStatus.FAILED, procTime);
        throw drfm;
    }

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        if (isAuthenticated())
            this.getEntityPublisher(em, body.getAuthInfo());

        ServiceDetail result = new ServiceDetail();

        List<String> serviceKeyList = body.getServiceKey();
        for (String serviceKey : serviceKeyList) {
            org.apache.juddi.model.BusinessService modelBusinessService = null;
            try {
                modelBusinessService = em.find(org.apache.juddi.model.BusinessService.class, serviceKey);
            } catch (ClassCastException e) {
            }
            if (modelBusinessService == null)
                throw new InvalidKeyPassedException(
                        new ErrorMessage("errors.invalidkey.ServiceNotFound", serviceKey));

            org.uddi.api_v3.BusinessService apiBusinessService = new org.uddi.api_v3.BusinessService();

            MappingModelToApi.mapBusinessService(modelBusinessService, apiBusinessService);

            result.getBusinessService().add(apiBusinessService);
        }

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

        return result;

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

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

public BusinessDetail getBusinessDetail(GetBusinessDetail body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();
    try {/*from w  w w  . j  av a 2s. com*/
        new ValidateInquiry(null).validateGetBusinessDetail(body);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.GET_BUSINESSDETAIL, QueryStatus.FAILED, procTime);
        throw drfm;
    }

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        if (isAuthenticated())
            this.getEntityPublisher(em, body.getAuthInfo());

        BusinessDetail result = new BusinessDetail();

        List<String> businessKeyList = body.getBusinessKey();
        for (String businessKey : businessKeyList) {
            org.apache.juddi.model.BusinessEntity modelBusinessEntity = null;
            try {
                modelBusinessEntity = em.find(org.apache.juddi.model.BusinessEntity.class, businessKey);
            } catch (ClassCastException e) {
            }
            if (modelBusinessEntity == null)
                throw new InvalidKeyPassedException(
                        new ErrorMessage("errors.invalidkey.BusinessNotFound", businessKey));

            org.uddi.api_v3.BusinessEntity apiBusinessEntity = new org.uddi.api_v3.BusinessEntity();

            MappingModelToApi.mapBusinessEntity(modelBusinessEntity, apiBusinessEntity);

            result.getBusinessEntity().add(apiBusinessEntity);
        }

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

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

From source file:org.meveo.service.billing.impl.InvoiceService.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void createAgregatesAndInvoice(BillingAccount billingAccount, Long billingRunId, User currentUser)
        throws BusinessException, Exception {
    log.debug("createAgregatesAndInvoice tx status={}", txReg.getTransactionStatus());
    EntityManager em = getEntityManager();
    BillingRun billingRun = em.find(BillingRun.class, billingRunId);
    em.refresh(billingRun);/*from  www . jav  a2 s .c om*/
    try {
        billingAccount = em.find(billingAccount.getClass(), billingAccount.getId());
        em.refresh(billingAccount);
        currentUser = em.find(currentUser.getClass(), currentUser.getId());
        em.refresh(currentUser);

        Long startDate = System.currentTimeMillis();
        BillingCycle billingCycle = billingRun.getBillingCycle();
        if (billingCycle == null) {
            billingCycle = billingAccount.getBillingCycle();
        }
        if (billingCycle == null) {
            throw new BusinessException("Cant find the billing cycle");
        }
        InvoiceType invoiceType = billingCycle.getInvoiceType();
        if (invoiceType == null) {
            invoiceType = invoiceTypeService.getDefaultCommertial(currentUser);
        }
        Invoice invoice = new Invoice();
        invoice.setInvoiceType(invoiceType);
        invoice.setBillingAccount(billingAccount);
        invoice.setBillingRun(billingRun);
        invoice.setAuditable(billingRun.getAuditable());
        invoice.setProvider(billingRun.getProvider());
        // ticket 680
        Date invoiceDate = billingRun.getInvoiceDate();
        invoice.setInvoiceDate(invoiceDate);

        Integer delay = billingCycle.getDueDateDelay();
        Date dueDate = invoiceDate;
        if (delay != null) {
            dueDate = DateUtils.addDaysToDate(invoiceDate, delay);
        }
        invoice.setDueDate(dueDate);

        PaymentMethodEnum paymentMethod = billingAccount.getPaymentMethod();
        if (paymentMethod == null) {
            paymentMethod = billingAccount.getCustomerAccount().getPaymentMethod();
        }
        invoice.setPaymentMethod(paymentMethod);
        invoice.setProvider(billingRun.getProvider());

        em.persist(invoice);

        // create(invoice, currentUser, currentUser.getProvider());
        log.debug("created invoice entity with id={},  tx status={}, em open={}", invoice.getId(),
                txReg.getTransactionStatus(), em.isOpen());
        ratedTransactionService.createInvoiceAndAgregates(billingAccount, invoice,
                billingRun.getLastTransactionDate(), currentUser);
        log.debug("created aggregates tx status={}, em open={}", txReg.getTransactionStatus(), em.isOpen());
        em.joinTransaction();

        if (billingRun.getProvider().isDisplayFreeTransacInInvoice()) {
            em.createNamedQuery("RatedTransaction.updateInvoicedDisplayFree")
                    .setParameter("billingAccount", billingAccount)
                    .setParameter("lastTransactionDate", billingRun.getLastTransactionDate())
                    .setParameter("billingRun", billingRun).setParameter("invoice", invoice).executeUpdate();
        } else {
            em.createNamedQuery("RatedTransaction.updateInvoiced")
                    .setParameter("billingAccount", billingAccount)
                    .setParameter("lastTransactionDate", billingRun.getLastTransactionDate())
                    .setParameter("billingRun", billingRun).setParameter("invoice", invoice).executeUpdate();

        }

        StringBuffer num1 = new StringBuffer("000000000");
        num1.append(invoice.getId() + "");
        String invoiceNumber = num1.substring(num1.length() - 9);
        int key = 0;

        for (int i = 0; i < invoiceNumber.length(); i++) {
            key = key + Integer.parseInt(invoiceNumber.substring(i, i + 1));
        }

        invoice.setTemporaryInvoiceNumber(invoiceNumber + "-" + key % 10);
        // getEntityManager().merge(invoice);
        Long endDate = System.currentTimeMillis();

        log.info("createAgregatesAndInvoice BR_ID=" + billingRun.getId() + ", BA_ID=" + billingAccount.getId()
                + ", Time en ms=" + (endDate - startDate));
    } catch (Exception e) {
        log.error("Error for BA=" + billingAccount.getCode() + " : ", e);

        RejectedBillingAccount rejectedBA = new RejectedBillingAccount(billingAccount, billingRun,
                e.getMessage());
        rejectedBillingAccountService.create(rejectedBA, currentUser);
    }
}

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

/**
 * Completely deletes a tModel from the persistence layer.
 * Administrative privilege required. All entities that reference this tModel
 * will no longer be able to use the tModel if jUDDI Option Enforce referential Integrity is enabled.<br>
 * Required permission, you must be am administrator
 * {@link Property#JUDDI_ENFORCE_REFERENTIAL_INTEGRITY}
 * @param body/*ww  w . j a  v  a  2  s .  c  om*/
 * @throws DispositionReportFaultMessage 
 */
public void adminDeleteTModel(DeleteTModel body) throws DispositionReportFaultMessage {

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

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

        new ValidatePublish(publisher).validateAdminDeleteTModel(em, body);

        List<String> entityKeyList = body.getTModelKey();
        for (String entityKey : entityKeyList) {
            Object obj = em.find(org.apache.juddi.model.Tmodel.class, entityKey);
            em.remove(obj);
        }

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

From source file:org.rhq.enterprise.server.content.test.ContentUIManagerBeanEligiblePackagesTest.java

private void tearDownTestEnvironment() throws Exception {
    getTransactionManager().begin();/*  w ww.j a  va  2 s.c om*/
    EntityManager em = getEntityManager();

    try {
        try {
            Query q = em.createNamedQuery(RepoPackageVersion.DELETE_BY_REPO_ID);
            q.setParameter("repoId", repo1.getId());
            q.executeUpdate();

            q = em.createNamedQuery(ResourceRepo.DELETE_BY_RESOURCE_ID);
            q.setParameter("resourceId", resource.getId());
            q.executeUpdate();

            getTransactionManager().commit();
        } catch (Exception e) {
            e.printStackTrace();
            getTransactionManager().rollback();
            throw e;
        }
    } finally {
        em.close();
    }

    getTransactionManager().begin();
    em = getEntityManager();

    try {
        try {
            resource = em.find(Resource.class, resource.getId());
            for (InstalledPackage ip : resource.getInstalledPackages()) {
                em.remove(ip);
            }

            package1 = em.find(Package.class, package1.getId());
            em.remove(package1);

            package2 = em.find(Package.class, package2.getId());
            em.remove(package2);

            package3 = em.find(Package.class, package3.getId());
            em.remove(package3);

            package4 = em.find(Package.class, package4.getId());
            em.remove(package4);

            packageType1 = em.find(PackageType.class, packageType1.getId());
            em.remove(packageType1);

            ResourceTreeHelper.deleteResource(em, resource);

            repo1 = em.find(Repo.class, repo1.getId());
            em.remove(repo1);

            repo2 = em.find(Repo.class, repo2.getId());
            em.remove(repo2);

            productVersion1 = em.find(ProductVersion.class, productVersion1.getId());
            em.remove(productVersion1);

            productVersion2 = em.find(ProductVersion.class, productVersion2.getId());
            em.remove(productVersion2);

            resourceType = em.find(ResourceType.class, resourceType.getId());
            em.remove(resourceType);

            getTransactionManager().commit();
        } catch (Exception e) {
            e.printStackTrace();
            getTransactionManager().rollback();
            throw e;
        }
    } finally {
        em.close();
    }
}

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

/**
 * Delete's a client's subscription information. This is typically used for
 * server to server subscriptions// w w  w .  j  av a 2  s.  c o m
 * Administrative privilege required.
 * @param body
 * @throws DispositionReportFaultMessage
 * @throws RemoteException 
 */
public void deleteClientSubscriptionInfo(DeleteClientSubscriptionInfo body)
        throws DispositionReportFaultMessage, RemoteException {

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

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

        new ValidateClientSubscriptionInfo(publisher).validateDeleteClientSubscriptionInfo(em, body);

        List<String> entityKeyList = body.getSubscriptionKey();
        for (String entityKey : entityKeyList) {
            Object obj = em.find(org.apache.juddi.model.ClientSubscriptionInfo.class, entityKey);
            em.remove(obj);
        }

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

}

From source file:de.zib.gndms.logic.model.TaskAction.java

/**
 * Initializes a TaskAction by denoting an EntityManager and primary key
 *
 * Retrieves the model (an AbstractTask), managed by the EntityManager, sets it as the model of {@code this} and
 * makes a backup of it.//from w w  w  . j a v a  2 s  .  c o  m
 *
 * The AbstractTask is select by the primary key {@code pk}. The EntityManager {@code em}
 * will be set as EntityManager for {@code this}, using {@link #setOwnEntityManager(javax.persistence.EntityManager)}.
 *
 * @param em an EntityManager, storing AbstractTasks
 * @param pk the primary key a of specific AbstractTask, which is managed by the EntityManager
 */
public void initFromPk(final EntityManager em, final String pk) {
    boolean wasActive = em.getTransaction().isActive();
    if (!wasActive)
        em.getTransaction().begin();
    try {
        final AbstractTask model = em.find(getTaskClass(), pk);
        if (model == null)
            throw new IllegalArgumentException("Model not found for pk: " + pk);
        if (!wasActive)
            em.getTransaction().commit();
        setOwnEntityManager(em);
        setModelAndBackup(model);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
    }
}

From source file:portal.api.impl.PortalJpaController.java

public PortalUser readPortalUserById(int userid) {

    EntityManager entityManager = entityManagerFactory.createEntityManager();
    return entityManager.find(PortalUser.class, userid);

    // Query q = entityManager.createQuery("SELECT m FROM PortalUser m WHERE
    // m.id=" + userid );
    // return (q.getResultList().size()==0)?null:(PortalUser)
    // q.getSingleResult();

}