Example usage for javax.persistence EntityManager createNamedQuery

List of usage examples for javax.persistence EntityManager createNamedQuery

Introduction

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

Prototype

public Query createNamedQuery(String name);

Source Link

Document

Create an instance of Query for executing a named query (in the Java Persistence query language or in native SQL).

Usage

From source file:org.nuxeo.theme.webwidgets.providers.PersistentProvider.java

public synchronized void deleteWidgetData(final Widget widget) throws ProviderException {
    if (widget == null) {
        throw new ProviderException("Widget is undefined");
    }/*from  w w  w .  j  av  a2s .co  m*/

    try {
        getPersistenceProvider().run(true, new RunVoid() {
            public void runWith(EntityManager em) {
                Query query = em.createNamedQuery("Data.findByWidget");
                query.setParameter("widgetUid", widget.getUid());
                for (Object dataEntity : query.getResultList()) {
                    em.remove(dataEntity);
                }
            }
        });
    } catch (ClientException e) {
        throw new ProviderException(e);
    }

}

From source file:org.nuxeo.theme.webwidgets.providers.PersistentProvider.java

public synchronized void setWidgetData(final Widget widget, final String dataName, final WidgetData data)
        throws ProviderException {
    if (widget == null) {
        throw new ProviderException("Widget is undefined");
    }//  w  w w  . j  a  v  a  2 s  . c  o  m
    if (dataName == null || "".equals(dataName)) {
        throw new ProviderException("Data name is undefined");
    }

    try {
        getPersistenceProvider().run(true, new RunVoid() {
            public void runWith(EntityManager em) {
                Query query = em.createNamedQuery("Data.findByWidgetAndName");
                query.setParameter("widgetUid", widget.getUid());
                query.setParameter("dataName", dataName);
                List<?> results = query.getResultList();
                final DataEntity dataEntity = results.size() > 0 ? (DataEntity) results.get(0)
                        : new DataEntity(widget.getUid(), dataName);
                dataEntity.setData(data);
                em.merge(dataEntity);
            }
        });
    } catch (ClientException e) {
        throw new ProviderException(e);
    }

}

From source file:uk.ac.edukapp.service.UserAccountService.java

public WidgetFavourite addFavourite(Useraccount user, Widgetprofile favourite, int level) {
    EntityManager em = getEntityManagerFactory().createEntityManager();
    em.getTransaction().begin();//  w w w.jav  a  2 s . c  o m
    WidgetFavourite widgetFavourite = null;
    // check to see if it exists
    try {
        Query q = em.createNamedQuery("favourite.select");
        q.setParameter("user", user);
        q.setParameter("widgetprofile", favourite);
        widgetFavourite = (WidgetFavourite) q.getSingleResult();
        if (widgetFavourite != null) {
            widgetFavourite.setRelevance(level);
        }
    } catch (NoResultException exp) {
        // fine just make one
        widgetFavourite = new WidgetFavourite();
        widgetFavourite.setUserAccount(user);
        widgetFavourite.setWidgetProfile(favourite);
        widgetFavourite.setRelevance(level);
        em.persist(widgetFavourite);
    }
    em.getTransaction().commit();
    em.close();
    return widgetFavourite;
}

From source file:com.webbfontaine.valuewebb.gtns.TTGTNSSynchronizer.java

@Asynchronous
public QuartzTriggerHandle findSentFCVRScheduleTask(@Expiration Date when, @IntervalCron String interval) {
    LOGGER.debug("Scheduler to upload FCVR started");
    long startTime = System.currentTimeMillis();

    synchronized (LOCK) { // allow only one async thread to do this

        EntityManager entityManager = (EntityManager) Component.getInstance("entityManager",
                ScopeType.STATELESS, true);
        List<Long> ttIDs = Utils.setDirectRead(entityManager.createNamedQuery(findSentTTIdsGH)).getResultList();

        LOGGER.debug("Found Sent TTs: {0}", ttIDs);

        if (ttIDs.isEmpty()) {
            return null;
        }/*  ww w  . jav  a2  s.  co  m*/

        for (Long ttId : ttIDs) {
            TtGen ttGen = entityManager.find(TtGen.class, ttId);

            if (!ttGen.getStatus().equals(TT_SENT)) { // already processed by other thread
                continue;
            }

            FisInterface fisInterface = new FisInterface();

            LOGGER.debug("Sending request to upload FCVR for TT # {0}, FCVR Number = {1}", ttGen.getId(),
                    ttGen.getFcvrNum());
            List<String> uploadErrors = fisInterface.sendFCVRUploadRequest(ttGen);

            if (uploadErrors != null) {
                if (uploadErrors.isEmpty()) {
                    LOGGER.debug(
                            "Request to upload FCVR for TT # {0}, FCVR Number = {1} is successfully sent, setting GCNet Submission Flag 'true'",
                            ttGen.getId(), ttGen.getFcvrNum());
                    updateTTFlag(ttGen);
                } else {
                    if (!GCNetUtils.isContain(uploadErrors, FCVR_ALREADY_EXIST)) {
                        LOGGER.debug("Error(s) during upload FCVR: {0}",
                                GCNetUtils.constraintUploadErrors(uploadErrors));
                        if (!AuthenticatorBean.getDaemonIdentity().tryLogin()) {
                            LOGGER.error("Can not login with 'daemon' identity to update TTs");
                            return null;
                        }
                        updateTTForSentError(ttGen, uploadErrors);
                        AuthenticatorBean.getDaemonIdentity().logout();
                    }
                }
            }
        }
    }
    LOGGER.debug("Processing took {0} ms", System.currentTimeMillis() - startTime);

    return null;
}

From source file:org.nuxeo.theme.webwidgets.providers.PersistentProvider.java

public synchronized WidgetData getWidgetData(final Widget widget, final String dataName)
        throws ProviderException {
    if (widget == null) {
        throw new ProviderException("Widget is undefined");
    }/*from w  ww .  j  a  v a  2  s  .  c o m*/
    if (dataName == null || "".equals(dataName)) {
        throw new ProviderException("Data name is undefined");
    }

    try {
        return getPersistenceProvider().run(true, new RunCallback<WidgetData>() {
            public WidgetData runWith(EntityManager em) {
                Query query = em.createNamedQuery("Data.findByWidgetAndName");
                query.setParameter("widgetUid", widget.getUid());
                query.setParameter("dataName", dataName);
                List<?> results = query.getResultList();
                if (results.size() > 0) {
                    DataEntity dataEntity = (DataEntity) results.get(0);
                    return dataEntity.getData();
                }
                return null;
            }

        });
    } catch (ClientException e) {
        throw new ProviderException(e);
    }

}

From source file:in.bookmylab.jpa.JpaDAO.java

/**
* @param em//from w  ww . ja v  a2 s.  c  o m
* @param user
*/
private void grantDefaultRoleToUser(EntityManager em, User user) {
    Query q = em.createNamedQuery("Role.findByRole");
    q.setParameter("role", RoleName.USER.name());
    Role r = (Role) q.getSingleResult();
    if (user.roleList == null)
        user.roleList = new ArrayList<>();
    user.roleList.add(r);
}

From source file:com.webbfontaine.valuewebb.gtns.TTGTNSSynchronizer.java

@Asynchronous
public QuartzTriggerHandle getFCVRStatusScheduleTask(@Expiration Date when, @IntervalCron String interval) {
    LOGGER.debug("Scheduler to get FCVR status started");
    long startTime = System.currentTimeMillis();

    synchronized (LOCK) { // allow only one async thread to do this

        EntityManager entityManager = (EntityManager) Component.getInstance("entityManager",
                ScopeType.STATELESS, true);
        List<Long> ttIDs = Utils.setDirectRead(entityManager.createNamedQuery(findSubmittedSentTTIds))
                .getResultList();//from   w ww. ja  v a 2s.c  o  m

        LOGGER.debug("Found Sent and Uploaded TTs: {0}", ttIDs);

        if (ttIDs.isEmpty()) {
            return null;
        }

        if (!AuthenticatorBean.getDaemonIdentity().tryLogin()) {
            LOGGER.error("Can not login with 'daemon' identity to get TTs status and update TTs");
            return null;
        }

        for (Long ttId : ttIDs) {
            TtGen ttGen = entityManager.find(TtGen.class, ttId);

            if (!ttGen.getStatus().equals(TT_SENT)) { // already processed by other thread
                continue;
            }

            FisInterface fisInterface = new FisInterface();
            LOGGER.debug("Sending request to get FCVR status for TT # {0}, FCVR Number = {1}", ttGen.getId(),
                    ttGen.getFcvrNum());

            Map<String, List<String>> remSt = fisInterface.retrieveFCVRValidationStatus(ttGen.getFcvrNum(),
                    new Date());
            if (remSt != null) {
                String key = (String) remSt.keySet().toArray()[0];
                if (GCNetUtils.isRejected(key)) {
                    LOGGER.debug(
                            "Got successfully FCVR 'Rejected' status for TT # {0}, FCVR Number = {1}, setting GCNet Submission Flag 'false'. Error message is: {2}",
                            ttGen.getId(), ttGen.getFcvrNum(), remSt.get(key));
                    ttGen.setSubmittedToGCNet(false);
                    updateTTForSentError(ttGen, remSt.get(key));
                } else {
                    if (GCNetUtils.isAccepted(key)) {
                        LOGGER.debug(
                                "Got successfully FCVR 'Accepted' status for TT # {0}, FCVR Number = {1}, setting GCNet Submission Flag 'false'",
                                ttGen.getId(), ttGen.getFcvrNum());
                        ttGen.setSubmittedToGCNet(false);
                        updateTT(ttGen, RESPONSE_OK);
                    } else {
                        if (GCNetUtils.isSubmitted(key)) {
                            LOGGER.debug(
                                    "TT # {0}, FCVR Number = {1} is still in Submitted status on GCNet side",
                                    ttGen.getId(), ttGen.getFcvrNum());
                        }
                    }
                }
            }
        }
        AuthenticatorBean.getDaemonIdentity().logout();
    }

    LOGGER.debug("Processing took {0} ms", System.currentTimeMillis() - startTime);

    return null;
}

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

private void tearDownTestEnvironment() throws Exception {
    getTransactionManager().begin();/*from www .ja  va 2 s .  c  o m*/
    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:com.epam.training.taranovski.web.project.repository.implementation.OfferBidRepositoryImplementation.java

@Override
public boolean deleteAllBidsForVacancy(Vacancy vacancy) {
    EntityManager em = entityManagerFactory.createEntityManager();
    boolean success = true;
    try {//from w w  w  .  j  a  va2 s.c  om
        em.getTransaction().begin();
        Query query = em.createNamedQuery("OfferBid.deleteByVacancy");
        query.setParameter("vacancy", vacancy);
        query.executeUpdate();
        em.getTransaction().commit();

        success = true;
    } catch (RuntimeException e) {
        Logger.getLogger(OfferBidRepositoryImplementation.class.getName()).info(e);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
            success = false;
        }
        em.close();
    }

    return success;
}

From source file:com.epam.training.taranovski.web.project.repository.implementation.OfferBidRepositoryImplementation.java

@Override
public boolean deleteAllOffersForEmployee(Employee employee) {
    EntityManager em = entityManagerFactory.createEntityManager();
    boolean success = true;
    try {//  w  w  w  .ja v a 2s. c o  m
        em.getTransaction().begin();
        Query query = em.createNamedQuery("OfferBid.deleteByEmployee");
        query.setParameter("employee", employee);
        query.executeUpdate();
        em.getTransaction().commit();

        success = true;
    } catch (RuntimeException e) {
        Logger.getLogger(OfferBidRepositoryImplementation.class.getName()).info(e);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
            success = false;
        }
        em.close();
    }

    return success;
}