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.UDDIPublicationImpl.java

private void setOperationalInfo(EntityManager em, org.apache.juddi.model.Tmodel uddiEntity,
        UddiEntityPublisher publisher) throws DispositionReportFaultMessage {

    uddiEntity.setAuthorizedName(publisher.getAuthorizedName());

    Date now = new Date();
    uddiEntity.setModified(now);// w ww . j a v  a2 s .c om
    uddiEntity.setModifiedIncludingChildren(now);

    String nodeId = "";
    try {
        nodeId = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID);
    } catch (ConfigurationException ce) {
        throw new FatalErrorException(
                new ErrorMessage("errors.configuration.Retrieval", Property.JUDDI_NODE_ID));
    }
    uddiEntity.setNodeId(nodeId);

    org.apache.juddi.model.Tmodel existingUddiEntity = em.find(uddiEntity.getClass(),
            uddiEntity.getEntityKey());
    if (existingUddiEntity != null)
        uddiEntity.setCreated(existingUddiEntity.getCreated());
    else
        uddiEntity.setCreated(now);

    if (existingUddiEntity != null)
        em.remove(existingUddiEntity);

}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

public <T extends EntityBaseStandard> T find(Class<T> classObj, Object id) throws Exception {
    T returnValue = null;/*  w  w w .j  av  a2 s. com*/

    EntityManagerFactory emf = null;
    EntityManager em = null;
    try {
        emf = getEntityManagerFactory();
        em = emf.createEntityManager();

        returnValue = (T) em.find(classObj, id);
    } catch (Exception e) {
        // logger.error("Errore su find di controller : " + e.getMessage() +
        // " " + e.getCause() != null ? e.getCause().getMessage() : "");
        ExceptionLogger.logExceptionWithCause(logger, e);
        throw e;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
        }
        em = null;
    }
    return returnValue;
}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

/**
 * Usato specialmente per aggiornare dopo un salvataggio. Nel caso delle
 * applicazioni web usiamo em che si chiude dopo la request quindi gli
 * oggetti non si aggiornano in automatico dopo il salvataggio.
 * //from   w  w  w.j  a v  a 2s.  co  m
 * @param <T>
 * @param classObj
 * @param id
 * @return
 * @throws Exception
 */
public <T extends EntityBaseStandard> T findAndRefresh(Class<T> classObj, Object id) throws Exception {
    T returnValue = null;

    EntityManagerFactory emf = null;
    EntityManager em = null;
    try {
        emf = getEntityManagerFactory();
        em = emf.createEntityManager();

        returnValue = (T) em.find(classObj, id);

        if (returnValue != null) {
            // if (lazyCloseEM) {
            em.refresh(returnValue);
            // }
        }

    } catch (Exception e) {
        // logger.error("Errore su find di controller : " + e.getMessage() +
        // " " + e.getCause() != null ? e.getCause().getMessage() : "");
        ExceptionLogger.logExceptionWithCause(logger, e);
        throw e;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
        }
        em = null;
    }
    return returnValue;
}

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

private void setOperationalInfo(EntityManager em, org.apache.juddi.model.BusinessEntity uddiEntity,
        UddiEntityPublisher publisher) throws DispositionReportFaultMessage {

    uddiEntity.setAuthorizedName(publisher.getAuthorizedName());

    Date now = new Date();
    uddiEntity.setModified(now);/*from   ww w. j a  va  2 s  . co  m*/
    uddiEntity.setModifiedIncludingChildren(now);

    String nodeId = "";
    try {
        nodeId = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID);
    } catch (ConfigurationException ce) {
        throw new FatalErrorException(
                new ErrorMessage("errors.configuration.Retrieval", Property.JUDDI_NODE_ID));
    }
    uddiEntity.setNodeId(nodeId);

    org.apache.juddi.model.BusinessEntity existingUddiEntity = em.find(uddiEntity.getClass(),
            uddiEntity.getEntityKey());
    if (existingUddiEntity != null)
        uddiEntity.setCreated(existingUddiEntity.getCreated());
    else
        uddiEntity.setCreated(now);

    List<org.apache.juddi.model.BusinessService> serviceList = uddiEntity.getBusinessServices();
    for (org.apache.juddi.model.BusinessService service : serviceList)
        setOperationalInfo(em, service, publisher, true);

    if (existingUddiEntity != null)
        em.remove(existingUddiEntity);

}

From source file:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Creates an AnnotationStatus that specifies another AnnotationStatus
 * @param label//from w  w w .  j av  a2  s  .  c om
 * @param comment
 * @param father
 * @return
 */
public boolean createAnnotationStatusChild(String label, String comment, String color, AnnotationStatus father,
        JSONArray descripteur) {
    label = StringOp.deleteBlanks(label);
    if (!StringOp.isNull(label)) {
        comment = StringOp.deleteBlanks(comment);
        AnnotationStatus _as = new AnnotationStatus();
        _as.setComment(comment);
        _as.setLabel(label);
        _as.setFather(father);
        _as.setDescripteur(descripteur);
        _as.setColor(color);
        //   EntityManagerFactory emf = this.setEMF();
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            if (father.getId() != null) {
                AnnotationStatus _synchro_father = em.find(AnnotationStatus.class, father.getId());
                if (_synchro_father != null)
                    _as.setFather(_synchro_father);
            }
            em.persist(_as);
            tx.commit();
            //      em.close();
            return true;
        } catch (Exception e) {
            System.out
                    .println("[CreateAnnotationStatus.createAnnotationStatus] fails to create AnnotationStatus"
                            + " label : " + label + " comment : " + comment + " cause : " + e.getMessage());
            tx.rollback();
            //   em.close();
            return false;
        }
    } else {
        System.out.println("[CreateAnnotationStatus.createAnnotationStatus] unable to persist AnnotationStatus"
                + " not a valid label : " + label);
        return false;
    }
}

From source file:com.enioka.jqm.api.HibernateClient.java

@Override
public int enqueueFromHistory(int jobIdToCopy) {
    EntityManager em = null;
    History h = null;/*from w w w  . j  a va  2 s  . c  o m*/
    try {
        em = getEm();
        h = em.find(History.class, jobIdToCopy);
        return enqueue(getJobRequest(h, em));
    } catch (NoResultException e) {
        throw new JqmInvalidRequestException("No job for this ID in the history");
    } finally {
        closeQuietly(em);
    }
}

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

public void saveSubscription(String authInfo, Holder<List<Subscription>> subscription)
        throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//from   w w w. jav a2  s . com
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo);
        new ValidateSubscription(publisher).validateSubscriptions(em, subscription.value);

        List<org.uddi.sub_v3.Subscription> apiSubscriptionList = subscription.value;
        for (org.uddi.sub_v3.Subscription apiSubscription : apiSubscriptionList) {

            org.apache.juddi.model.Subscription modelSubscription = new org.apache.juddi.model.Subscription();

            Object existing = em.find(org.apache.juddi.model.Subscription.class,
                    apiSubscription.getSubscriptionKey());
            if (existing != null) {
                org.apache.juddi.model.Subscription existingEntity = (org.apache.juddi.model.Subscription) existing;
                doRenewal(existingEntity, apiSubscription);
                //carrying over the created and last notified dates if this is a renewal.
                modelSubscription.setCreateDate(existingEntity.getCreateDate());
                modelSubscription.setLastNotified(existingEntity.getLastNotified());
                em.remove(existing);
            } else {
                modelSubscription.setCreateDate(new Date());
            }

            doSubscriptionExpirationDate(apiSubscription);

            MappingApiToModel.mapSubscription(apiSubscription, modelSubscription);

            modelSubscription.setAuthorizedName(publisher.getAuthorizedName());

            // Add the matching keys to the match collection
            List<?> keys = getSubscriptionMatches(apiSubscription.getSubscriptionFilter(), em);
            if (keys != null && keys.size() > 0) {
                for (Object key : keys) {
                    SubscriptionMatch subMatch = new SubscriptionMatch(modelSubscription, (String) key);
                    modelSubscription.getSubscriptionMatches().add(subMatch);
                }
            }

            em.persist(modelSubscription);
        }

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(SubscriptionQuery.SAVE_SUBSCRIPTION, QueryStatus.SUCCESS, procTime);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(SubscriptionQuery.SAVE_SUBSCRIPTION, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:com.enioka.jqm.api.HibernateClient.java

@Override
public InputStream getDeliverableContent(int delId) {
    EntityManager em = null;
    Deliverable deliverable = null;//from ww  w  . j a v  a 2  s . co  m

    try {
        em = getEm();
        deliverable = em.find(Deliverable.class, delId);
    } catch (Exception e) {
        throw new JqmInvalidRequestException(
                "Could not get find deliverable description inside DB - your ID may be wrong", e);
    } finally {
        closeQuietly(em);
    }

    return getDeliverableContent(deliverable);
}

From source file:com.enioka.jqm.api.HibernateClient.java

private InputStream getJobLog(int jobId, String extension, String param) {
    // 1: retrieve node to address
    EntityManager em = null;
    Node n = null;//from w w w  .  ja v a  2  s  .  co  m
    try {
        em = getEm();
        History h = em.find(History.class, jobId);
        if (h != null) {
            n = h.getNode();
        } else {
            JobInstance ji = em.find(JobInstance.class, jobId);
            if (ji != null) {
                n = ji.getNode();
            } else {
                throw new NoResultException("No history or running instance for this jobId.");
            }
        }
    } catch (Exception e) {
        closeQuietly(em);
        throw new JqmInvalidRequestException("No job found with the job ID " + jobId, e);
    }

    if (n == null) {
        throw new JqmInvalidRequestException("cannot retrieve a file from a deleted node");
    }

    // 2: build URL
    URL url = null;
    try {
        url = new URL(
                getFileProtocol(em) + n.getDns() + ":" + n.getPort() + "/ws/simple/" + param + "?id=" + jobId);
        jqmlogger.trace("URL: " + url.toString());
    } catch (MalformedURLException e) {
        throw new JqmClientException("URL is not valid " + url, e);
    } finally {
        em.close();
    }

    return getFile(url.toString());
}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

/**
 * //from ww w . ja v a 2  s . c  o m
 * Restituisce loggetto relativo specificando classe ed id
 * 
 * @param classObj
 * @param id
 * @return EntityBase
 * @throws java.lang.Exception
 */
public <T extends EntityBaseStandard> T find2(Class<T> classObj, Object id) throws Exception {
    T returnValue = null;

    EntityManagerFactory emf = null;
    EntityManager em = null;
    try {
        /* Istanzio l'entity manager */
        emf = getEntityManagerFactory();
        em = emf.createEntityManager();

        /* Calcolo l'oggetto */
        returnValue = (T) em.find(classObj, id);
    } catch (Exception e) {
        throw e;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
        }
        em = null;
    }
    return returnValue;
}