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.sigmah.server.dao.impl.FileHibernateDAO.java

/**
 * Saves a new file.//from www.  j  av a  2 s  .com
 * 
 * @param properties
 *          The properties map of the uploaded file (see {@link FileUploadUtils}).
 * @param physicalName
 *          The uploaded file content.
 * @param size
 *          Size of the uploaded file.
 * @param id
 *          The file which gets a new version.
 * @param authorId
 *          The author id.
 * @return The file id (must be the same as the parameter).
 * @throws IOException
 */
@Transactional
protected Integer saveNewVersion(Map<String, String> properties, String physicalName, int size, Integer id,
        int authorId) throws IOException {

    final EntityManager em = em();

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("[save] New file version.");
    }

    // Gets the details of the name of the file.
    final String fullName = normalizeFileName(properties.get(FileUploadUtils.DOCUMENT_NAME));
    final int index = fullName.indexOf('.');

    final String name = index > 0 ? fullName.substring(0, index) : fullName;
    final String extension = index > 0 && index < fullName.length() ? fullName.substring(index + 1) : null;

    // Creates and adds the new version.
    final File file = em.find(File.class, Integer.valueOf(id));

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("[save] Found file: " + file.getName() + ".");
    }

    Integer versionNumber;

    Query query = em.createQuery(
            "SELECT max(fv.versionNumber)+1 AS newVersionNumber FROM FileVersion AS fv WHERE parentFile=:parentFile");
    query.setParameter("parentFile", file);
    versionNumber = (Integer) query.getSingleResult();
    if (versionNumber == null) {
        versionNumber = 0;
    }

    final FileVersion version = createVersion(versionNumber, name, extension, authorId, physicalName, size);
    version.setComments(properties.get(FileUploadUtils.DOCUMENT_COMMENTS));
    file.addVersion(version);

    em.persist(file);

    return file.getId();
}

From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * Internal method to find a DataSourceDao object by dataSourceId.
 * /*from   w ww  .jav  a2  s.c om*/
 * @param em
 *          the EntityManager to use
 * @param dataSourceId
 *          the data source id
 * @return the RecordDao object or null
 */
private DataSourceDao findDataSourceDao(final EntityManager em, final String dataSourceId) {
    return em.find(DataSourceDao.class, dataSourceId);
}

From source file:net.officefloor.tutorial.transactionhttpserver.TransactionHttpServerTest.java

/**
 * Ensure the JPA connects to database./* w  w w  .  ja v a 2s  .com*/
 */
public void testJpa() throws Exception {

    // Request page to allow time for database setup
    this.doRequest("http://localhost:7878/users.woof");

    // Obtain entity manager
    EntityManagerFactory factory = Persistence.createEntityManagerFactory("example");
    EntityManager manager = factory.createEntityManager();

    // Ensure can obtain user and person
    Query query = manager.createQuery("SELECT U FROM User U");
    User user = (User) query.getSingleResult();
    assertEquals("Incorrect user name", "daniel", user.getUserName());
    Person person = user.getPerson();
    assertEquals("Incorrect person name", "Daniel Sagenschneider", person.getFullName());

    // Ensure persist user and person
    User newUser = new User();
    newUser.setUserName("test");
    Person newPerson = new Person();
    newPerson.setFullName("TEST");
    newPerson.setUser(newUser);
    manager.persist(newPerson);
    manager.close();

    // Ensure user and person persisted
    manager = factory.createEntityManager();
    User retrievedUser = manager.find(User.class, newUser.getId());
    assertEquals("Incorrect retrieved user name", "test", retrievedUser.getUserName());
    Person retrievedPerson = retrievedUser.getPerson();
    assertEquals("Incorrect retrieved full name", "TEST", retrievedPerson.getFullName());

    // Close persistence
    factory.close();
}

From source file:org.apache.juddi.validation.ValidateSubscription.java

public void validateGetSubscriptionResults(EntityManager em, GetSubscriptionResults body)
        throws DispositionReportFaultMessage {
    // No null input
    if (body == null) {
        throw new FatalErrorException(new ErrorMessage("errors.NullInput"));
    }//from   w  w  w.j a v  a  2  s .  c  o  m

    String subscriptionKey = body.getSubscriptionKey();
    if (subscriptionKey == null || subscriptionKey.length() == 0) {
        throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NullKey", subscriptionKey));
    }

    // Per section 4.4: keys must be case-folded
    subscriptionKey = subscriptionKey.toLowerCase();
    body.setSubscriptionKey(subscriptionKey);

    Object obj = em.find(org.apache.juddi.model.Subscription.class, subscriptionKey);
    if (obj == null) {
        throw new InvalidKeyPassedException(
                new ErrorMessage("errors.invalidkey.SubscriptionNotFound", subscriptionKey));
    }

    Date expiresAfter = ((org.apache.juddi.model.Subscription) obj).getExpiresAfter();
    Date now = new Date();
    if (expiresAfter.getTime() < now.getTime()) {
        throw new InvalidKeyPassedException(
                new ErrorMessage("errors.getsubscriptionresult.SubscriptionExpired", subscriptionKey));
    }

    CoveragePeriod coveragePeriod = body.getCoveragePeriod();
    if (coveragePeriod == null) {
        throw new InvalidTimeException(new ErrorMessage("errors.getsubscriptionresult.NullCoveragePeriod"));
    }

    if (coveragePeriod.getStartPoint() == null || coveragePeriod.getEndPoint() == null) {
        throw new InvalidTimeException(
                new ErrorMessage("errors.getsubscriptionresult.InvalidDateInCoveragePeriod"));
    }

    GregorianCalendar startPoint = coveragePeriod.getStartPoint().toGregorianCalendar();
    GregorianCalendar endPoint = coveragePeriod.getEndPoint().toGregorianCalendar();
    if (startPoint.getTimeInMillis() > endPoint.getTimeInMillis()) {
        throw new InvalidTimeException(new ErrorMessage("errors.getsubscriptionresult.StartPointAfterEndPoint",
                startPoint.toString()));
    }
}

From source file:op.care.med.inventory.DlgNewStocks.java

private void txtBWSucheCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_txtBWSucheCaretUpdate
    if (ignoreEvent || !txtBWSuche.isEnabled()) {
        return;/*from  w  ww . j  a  v a2 s  .  c  o  m*/
    }

    if (txtBWSuche.getText().isEmpty()) {
        cmbBW.setModel(new DefaultComboBoxModel());
        resident = null;
    } else {
        DefaultComboBoxModel dcbm = new DefaultComboBoxModel();
        EntityManager em = OPDE.createEM();
        if (txtBWSuche.getText().trim().length() == 3) { // Knnte eine Suche nach der Kennung sein
            resident = em.find(Resident.class, txtBWSuche.getText().trim());
            if (resident != null) {
                dcbm = new DefaultComboBoxModel(new Resident[] { resident });
            }
        }

        if (dcbm.getSize() == 0) { // Vielleicht Suche nach Nachname

            Query query = em.createQuery(
                    " SELECT b FROM Resident b WHERE b.station IS NOT NULL AND b.name like :nachname ORDER BY b.name, b.firstname ");
            query.setParameter("nachname", txtBWSuche.getText().trim() + "%");
            java.util.List<Resident> listbw = query.getResultList();

            dcbm = new DefaultComboBoxModel(listbw.toArray());
        }

        if (dcbm.getSize() > 0) {
            cmbBW.setModel(dcbm);
            cmbBW.setSelectedIndex(0);
            resident = (Resident) cmbBW.getSelectedItem();
        } else {
            cmbBW.setModel(new DefaultComboBoxModel());
            resident = null;
        }
        em.close();
    }

    if (ovrBW.getOverlayComponents().length > 0) {
        ovrBW.removeOverlayComponent(ovrBW.getOverlayComponents()[0]);
    }
    if (resident == null) {
        ovrBW.addOverlayComponent(attentionIconBW, DefaultOverlayable.SOUTH_WEST);
        attentionIconBW.setToolTipText("<html>Keine(n) BewohnerIn ausgewhlt.<html>");
    }

    initCmbVorrat();
}

From source file:elaborate.editor.publish.PublishTask.java

private void exportPojectData(List<EntryData> entryData, Map<Long, List<String>> thumbnails,
        Multimap<String, AnnotationIndexData> annotationIndex) {
    File json = new File(jsonDir, "config.json");
    EntityManager entityManager = HibernateUtil.getEntityManager();
    Project project = entityManager.find(Project.class, projectId);
    Map<String, Object> projectData = getProjectData(project, entryData, thumbnails);
    List<String> projectEntryMetadataFields = settings.getProjectEntryMetadataFields();
    projectData.put("entryMetadataFields", projectEntryMetadataFields);
    projectData.put("generated", new Date().getTime());
    cnwKludge(project, projectData, projectEntryMetadataFields);

    entityManager.close();/* w w w  . ja v  a  2s .  c o  m*/
    exportJson(json, projectData);

    json = new File(jsonDir, ANNOTATION_INDEX_JSON);
    exportJson(json, annotationIndex.asMap());

    // String indexfilename = "index-" + settings.getProjectType() + ".html.ftl";
    String indexfilename = "index.html.ftl";
    File destIndex = new File(distDir, "index.html");
    String projectType = settings.getProjectType();
    Configuration configuration = Configuration.instance();
    String version = configuration.getSetting("publication.version." + projectType);
    String cdnBaseURL = configuration.getSetting("publication.cdn");
    Map<String, Object> fmRootMap = ImmutableMap.of(//
            "BASE_URL", projectData.get("baseURL"), //
            "TYPE", projectType, //
            "ELABORATE_CDN", cdnBaseURL, //
            "VERSION", version//
    );
    FreeMarker.templateToFile(indexfilename, destIndex, fmRootMap, getClass());
}

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

public TModelDetail getTModelDetail(GetTModelDetail body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();
    try {/*from   www.j  a  v  a2 s.  c om*/
        new ValidateInquiry(null).validateGetTModelDetail(body);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.GET_TMODELDETAIL, QueryStatus.FAILED, procTime);
        throw drfm;
    }

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

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

        TModelDetail result = new TModelDetail();

        List<String> tmodelKeyList = body.getTModelKey();
        for (String tmodelKey : tmodelKeyList) {
            org.apache.juddi.model.Tmodel modelTModel = null;
            try {
                modelTModel = em.find(org.apache.juddi.model.Tmodel.class, tmodelKey);
            } catch (ClassCastException e) {
            }
            if (modelTModel == null)
                throw new InvalidKeyPassedException(
                        new ErrorMessage("errors.invalidkey.TModelNotFound", tmodelKey));

            org.uddi.api_v3.TModel apiTModel = new org.uddi.api_v3.TModel();

            MappingModelToApi.mapTModel(modelTModel, apiTModel);

            result.getTModel().add(apiTModel);
        }

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

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

From source file:org.mule.module.jpa.command.Find.java

public Object execute(EntityManager entityManager, Object message, Map<String, Object> parameters,
        Boolean flush) throws Exception {
    Object primaryKey = parameters.get("id");
    logger.debug(String.format("Finding entities of type: %s with primary key: %s",
            parameters.get("entityClass"), primaryKey));

    Object result = entityManager.find(Class.forName((String) parameters.get("entityClass")), primaryKey);

    if (flush) {/*  ww  w .j  av  a 2  s . c  o  m*/
        entityManager.flush();
    }

    return result;
}

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

public OperationalInfos getOperationalInfo(GetOperationalInfo body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();
    try {/*  w  w w  . j a va2 s  .  com*/
        new ValidateInquiry(null).validateGetOperationalInfo(body);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.GET_OPERATIONALINFO, QueryStatus.FAILED, procTime);
        throw drfm;
    }

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

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

        OperationalInfos result = new OperationalInfos();

        List<String> entityKeyList = body.getEntityKey();
        for (String entityKey : entityKeyList) {
            org.apache.juddi.model.UddiEntity modelUddiEntity = null;
            try {
                modelUddiEntity = em.find(org.apache.juddi.model.UddiEntity.class, entityKey);
            } catch (ClassCastException e) {
            }
            if (modelUddiEntity == null)
                throw new InvalidKeyPassedException(
                        new ErrorMessage("errors.invalidkey.EntityNotFound", entityKey));

            org.uddi.api_v3.OperationalInfo apiOperationalInfo = new org.uddi.api_v3.OperationalInfo();

            MappingModelToApi.mapOperationalInfo(modelUddiEntity, apiOperationalInfo);

            result.getOperationalInfo().add(apiOperationalInfo);
        }

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

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

From source file:commonSession.PersistAttivitaFacadeBean.java

public Object find(Object id, Class clazz, String unit) throws Exception {

    try {/*w  w w .j a  v a 2  s .c  om*/

        EntityManager em = null;

        if (unit == "TerritorioEm")
            em = TerritorioEm;
        if (unit == "GestionaleEm")
            em = GestionaleEm;

        //      if(unit.equals("GestionaleEm")) em = GestionaleEm;
        //          else em = TerrEm;

        Object ret = em.find(clazz, id);

        return ret;

    } catch (Exception e) {

        throw e;
    }

}