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.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * {@inheritDoc}//  ww  w.  j  ava 2  s  .  c  om
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#clear()
 */
@Override
public void clear() throws DeltaIndexingException {
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();
            // delete delta indexing entries
            final Query diQuery = em.createNamedQuery(DeltaIndexingDao.NAMED_QUERY_DELETE_ALL);
            diQuery.executeUpdate();
            // delete source
            final Query dsQuery = em.createNamedQuery(DataSourceDao.NAMED_QUERY_DELETE_SOURCES);
            dsQuery.executeUpdate();

            transaction.commit();
            if (_log.isInfoEnabled()) {
                _log.info("cleared delta indexing");
            }
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException("error clearing delta indexing", e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }

}

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

/**
 * {@inheritDoc}/*  w w w  . j av  a  2 s. c  om*/
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#clear(String)
 */
@Override
public void clear(final String sessionId) throws DeltaIndexingSessionException, DeltaIndexingException {
    _lock.readLock().lock();
    try {
        final DataSourceDao dao = assertSession(sessionId);

        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();
            // delete delta indexing entries
            final Query diQuery = em.createNamedQuery(DeltaIndexingDao.NAMED_QUERY_DELETE_BY_SOURCE);
            diQuery.setParameter(DeltaIndexingDao.NAMED_QUERY_PARAM_SOURCE, dao.getDataSourceId())
                    .executeUpdate();

            transaction.commit();
            if (_log.isInfoEnabled()) {
                _log.info("cleared delta indexing for sessionId: " + sessionId + " with data source "
                        + dao.getDataSourceId());
            }
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException("error clearing delta indexing for session id: " + sessionId, e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }

}

From source file:org.sakaiproject.kernel.test.ObservationKernelUnitT.java

@BeforeClass
public static void beforeThisClass() throws ComponentActivatorException, RepositoryException,
        JCRNodeFactoryServiceException, IOException, InterruptedException {
    shutdown = KernelIntegrationBase.beforeClass();

    // get some services

    KernelManager km = new KernelManager();
    Kernel kernel = km.getKernel();
    AuthzResolverService authzResolverService = kernel.getService(AuthzResolverService.class);
    JCRNodeFactoryService jcrNodeFactoryService = kernel.getService(JCRNodeFactoryService.class);
    JCRService jcrService = kernel.getService(JCRService.class);
    EntityManager entityManager = kernel.getService(EntityManager.class);

    // bypass security
    authzResolverService.setRequestGrant("Populating Test JSON");

    // login to the repo with super admin
    SakaiJCRCredentials credentials = new SakaiJCRCredentials();
    Session session = jcrService.getRepository().login(credentials);
    jcrService.setSession(session);/* w  w w  . ja  va2 s.  c o  m*/

    // setup the user environment for the admin user.
    for (String userName : USERS) {
        String prefix = PathUtils.getUserPrefix(userName);
        String userEnvironmentPath = "/userenv" + prefix + "userenv";

        LOG.info("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++Saving " + userEnvironmentPath);
        InputStream in = ResourceLoader.openResource(TEST_USERENV + userName + ".json",
                ObservationKernelUnitT.class.getClassLoader());
        Node n = jcrNodeFactoryService.setInputStream(userEnvironmentPath, in, RestProvider.CONTENT_TYPE);
        n.setProperty(JCRConstants.ACL_OWNER, userName);
        in.close();
    }

    // add some group definitions in a random place, indexing should happen as a
    // result of events.
    for (String group : GROUPS) {
        String prefix = PathUtils.getUserPrefix(group);
        // imagine this is anywhere on the content system, probably with other
        // items related to the group
        String groupPath = "/somepath" + prefix + "groupdef.json";

        LOG.info("Saving " + groupPath);
        InputStream in = ResourceLoader.openResource(TEST_GROUPENV + group + ".json",
                ObservationKernelUnitT.class.getClassLoader());
        @SuppressWarnings("unused")
        Node n = jcrNodeFactoryService.setInputStream(groupPath, in, RestProvider.CONTENT_TYPE);
        in.close();
    }

    session.save();
    jcrService.logout();
    // clear the security bypass
    authzResolverService.clearRequestGrant();

    Query query = entityManager.createNamedQuery(SubjectPermissionBean.FINDBY_GROUP);
    int n = 0;
    while (n < GROUPS.length) {
        n = 0;
        for (String group : GROUPS) {
            query.setParameter(SubjectPermissionBean.PARAM_GROUP, group);
            List<?> subjectPermissionList = query.getResultList();
            if (subjectPermissionList.size() > 0) {
                LOG.info("Found " + group);
                n++;
            } else {
                LOG.info("Missing " + group);
            }
        }
        if (n < GROUPS.length) {
            Thread.sleep(500);
        }
    }

    // pause untill the subjects appear.
}

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

/**
 * Sets the visited flags of a unchanged dao object. The modified flag is NOT set !!! Sub compounds of compounds are
 * also set to visited./*from  ww  w.jav  a 2 s  . c  o m*/
 * 
 * @param em
 *          the EntityManager
 * @param dao
 *          the DeltaIndexingDao
 * @throws DeltaIndexingException
 *           if any error occurs
 */
private void visitUnchangedDaos(final EntityManager em, final DeltaIndexingDao dao)
        throws DeltaIndexingException {
    // visit dao if it's a compound or if it has no parent
    dao.visit();
    em.merge(dao);
    if (_log.isTraceEnabled()) {
        _log.trace("visited Id with hash:" + dao.getIdHash());
    }

    // check if dao is a compound and visit all sub compounds
    if (dao.isCompound()) {
        final Query query = em.createNamedQuery(DeltaIndexingDao.NAMED_QUERY_FIND_SUB_COMPOUNDS);
        final List<DeltaIndexingDao> daos = query
                .setParameter(DeltaIndexingDao.NAMED_QUERY_PARAM_PARENT_ID_HASH, dao.getIdHash())
                .getResultList();
        if (daos != null) {
            for (final DeltaIndexingDao subDao : daos) {
                visitUnchangedDaos(em, subDao);
            } // for
        } // if
    }
}

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

/**
 * This is a temporary method to undo the messiness of this test in the past. The test will be changed to
 * clean up after itself, however this call will set the state to a clean one for environments that have
 * run the previous incarnation.//from   ww  w  .  ja va 2  s  .com
 *
 * @throws Exception
 */
private void cleanupPreviousTestRuns() throws Exception {
    getTransactionManager().begin();
    EntityManager em = getEntityManager();

    try {
        try {
            Query query;
            List results;

            query = em.createNamedQuery(ContentSource.QUERY_FIND_BY_NAME_AND_TYPENAME);
            query.setParameter("name", "testUpdateContentSource");
            query.setParameter("typeName", "testUpdateContentSourceCST");
            results = query.getResultList();

            if (results.size() > 0) {
                ContentSource deleteMe = (ContentSource) results.get(0);
                em.remove(deleteMe);
            }

            query = em.createNamedQuery(ContentSource.QUERY_FIND_BY_NAME_AND_TYPENAME);
            query.setParameter("name", "testUpdateContentSource2");
            query.setParameter("typeName", "testUpdateContentSourceCST2");
            results = query.getResultList();

            if (results.size() > 0) {
                ContentSource deleteMe = (ContentSource) results.get(0);
                em.remove(deleteMe);
            }

            query = em.createNamedQuery(ContentSource.QUERY_FIND_BY_NAME_AND_TYPENAME);
            query.setParameter("name", "testConstraintViolation");
            query.setParameter("typeName", "testConstraintViolationCST");
            results = query.getResultList();

            if (results.size() > 0) {
                ContentSource deleteMe = (ContentSource) results.get(0);
                em.remove(deleteMe);
            }

            query = em.createNamedQuery(ContentSourceType.QUERY_FIND_BY_NAME);
            query.setParameter("name", "testUpdateContentSourceCST");
            results = query.getResultList();

            if (results.size() > 0) {
                ContentSourceType deleteMe = (ContentSourceType) results.get(0);
                em.remove(deleteMe);
            }

            query = em.createNamedQuery(ContentSourceType.QUERY_FIND_BY_NAME);
            query.setParameter("name", "testUpdateContentSourceCST2");
            results = query.getResultList();

            if (results.size() > 0) {
                ContentSourceType deleteMe = (ContentSourceType) results.get(0);
                em.remove(deleteMe);
            }

            query = em.createNamedQuery(ContentSourceType.QUERY_FIND_BY_NAME);
            query.setParameter("name", "testConstraintViolationCST");
            results = query.getResultList();

            if (results.size() > 0) {
                ContentSourceType deleteMe = (ContentSourceType) results.get(0);
                em.remove(deleteMe);
            }

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

}

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

public Object execute(EntityManager entityManager, Object payload, Map<String, Object> parameters,
        Boolean flush) throws Exception {

    Object queryParameters = parameters.get("queryParameters");

    Object result;//from   www .j  a va  2 s  .  c  om
    if (queryParameters instanceof CriteriaQuery) {
        logger.debug("Executing CriteriaQuery: " + queryParameters);
        result = entityManager.createQuery((CriteriaQuery) queryParameters).getResultList();
    } else if (parameters.containsKey("namedQuery")) {
        logger.debug("Executing Named Query: " + parameters.get("namedQuery"));
        javax.persistence.Query query = entityManager.createNamedQuery((String) parameters.get("namedQuery"));
        if (queryParameters != null) {
            setParameters(queryParameters, query);
        }
        result = query.getResultList();
    } else if (parameters.containsKey("statement")) {
        logger.debug("Executing JPQL statement: " + parameters.get("statement"));
        javax.persistence.Query query = entityManager.createQuery((String) parameters.get("statement"));
        if (queryParameters != null) {
            setParameters(queryParameters, query);
        }
        result = query.getResultList();
    } else {
        throw new JPAException(
                "Couldn't resolve query from either the query parameters or the statement attribute");
    }

    if (flush) {
        entityManager.flush();
    }

    return result;
}

From source file:org.apache.oozie.test.XTestCase.java

private void cleanUpDBTablesInternal() throws StoreException {
    EntityManager entityManager = Services.get().get(JPAService.class).getEntityManager();
    entityManager.setFlushMode(FlushModeType.COMMIT);
    entityManager.getTransaction().begin();

    Query q = entityManager.createNamedQuery("GET_WORKFLOWS");
    List<WorkflowJobBean> wfjBeans = q.getResultList();
    int wfjSize = wfjBeans.size();
    for (WorkflowJobBean w : wfjBeans) {
        entityManager.remove(w);//www. j  a va 2s.c  om
    }

    q = entityManager.createNamedQuery("GET_ACTIONS");
    List<WorkflowActionBean> wfaBeans = q.getResultList();
    int wfaSize = wfaBeans.size();
    for (WorkflowActionBean w : wfaBeans) {
        entityManager.remove(w);
    }

    q = entityManager.createNamedQuery("GET_COORD_JOBS");
    List<CoordinatorJobBean> cojBeans = q.getResultList();
    int cojSize = cojBeans.size();
    for (CoordinatorJobBean w : cojBeans) {
        entityManager.remove(w);
    }

    q = entityManager.createNamedQuery("GET_COORD_ACTIONS");
    List<CoordinatorActionBean> coaBeans = q.getResultList();
    int coaSize = coaBeans.size();
    for (CoordinatorActionBean w : coaBeans) {
        entityManager.remove(w);
    }

    q = entityManager.createNamedQuery("GET_BUNDLE_JOBS");
    List<BundleJobBean> bjBeans = q.getResultList();
    int bjSize = bjBeans.size();
    for (BundleJobBean w : bjBeans) {
        entityManager.remove(w);
    }

    q = entityManager.createNamedQuery("GET_BUNDLE_ACTIONS");
    List<BundleActionBean> baBeans = q.getResultList();
    int baSize = baBeans.size();
    for (BundleActionBean w : baBeans) {
        entityManager.remove(w);
    }

    q = entityManager.createNamedQuery("GET_SLA_EVENTS");
    List<SLAEventBean> slaBeans = q.getResultList();
    int slaSize = slaBeans.size();
    for (SLAEventBean w : slaBeans) {
        entityManager.remove(w);
    }

    q = entityManager.createQuery("select OBJECT(w) from SLARegistrationBean w");
    List<SLARegistrationBean> slaRegBeans = q.getResultList();
    int slaRegSize = slaRegBeans.size();
    for (SLARegistrationBean w : slaRegBeans) {
        entityManager.remove(w);
    }

    q = entityManager.createQuery("select OBJECT(w) from SLASummaryBean w");
    List<SLASummaryBean> sdBeans = q.getResultList();
    int ssSize = sdBeans.size();
    for (SLASummaryBean w : sdBeans) {
        entityManager.remove(w);
    }

    entityManager.getTransaction().commit();
    entityManager.close();
    log.info(wfjSize + " entries in WF_JOBS removed from DB!");
    log.info(wfaSize + " entries in WF_ACTIONS removed from DB!");
    log.info(cojSize + " entries in COORD_JOBS removed from DB!");
    log.info(coaSize + " entries in COORD_ACTIONS removed from DB!");
    log.info(bjSize + " entries in BUNDLE_JOBS removed from DB!");
    log.info(baSize + " entries in BUNDLE_ACTIONS removed from DB!");
    log.info(slaSize + " entries in SLA_EVENTS removed from DB!");
    log.info(slaRegSize + " entries in SLA_REGISTRATION removed from DB!");
    log.info(ssSize + " entries in SLA_SUMMARY removed from DB!");

}

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

private List<Widgetprofile> getWidgetProfilesForWidgets(List<Widget> widgets) {
    List<Widgetprofile> widgetProfiles = new ArrayList<Widgetprofile>();

    EntityManager entityManager = getEntityManagerFactory().createEntityManager();
    entityManager.getTransaction().begin();

    ////from ww  w .jav  a2  s . com
    // For each Widget returned from the search index, correlate with
    // an Edukapp WidgetProfile, if one exists. Otherwise, construct a
    // new profile for it and persist it.
    //
    for (Widget widget : widgets) {
        Widgetprofile widgetProfile = null;

        //
        // Find matching profile
        //
        try {
            Query wpQuery = entityManager.createNamedQuery("Widgetprofile.findByUri");
            wpQuery.setParameter("uri", widget.getUri());
            widgetProfile = (Widgetprofile) wpQuery.getSingleResult();
            //
            // Ensure dependent objects are available when detached
            //
            widgetProfile.getTags();
            widgetProfile.getActivities();
            widgetProfile.getFunctionalities();
            widgetProfile.getCategories();

            // add stats here otherwise we done have them on the searched widget list.
            WidgetStats widgetStats = entityManager.find(WidgetStats.class, widgetProfile.getId());
            if (widgetStats == null) {
                widgetStats = new WidgetStats();
                widgetStats.setWid_id(widgetProfile.getId());
                widgetStats.setDownloads(0);
                widgetStats.setEmbeds(0);
                widgetStats.setViews(0);
            }

            Query q = entityManager.createNamedQuery("Userrating.getAverageValue");
            q.setParameter("widgetprofile", widgetProfile);

            Number average = (Number) q.getSingleResult();
            if (average == null)
                average = 0.0;

            widgetStats.setAverageRating(average);

            q = entityManager.createNamedQuery("Userrating.getCount");
            q.setParameter("widgetprofile", widgetProfile);

            Long count = (Long) q.getSingleResult();
            widgetStats.setTotalRatings(count);

        } catch (NoResultException e) {

            //
            // Create a new profile
            //
            widgetProfile = new Widgetprofile();
            widgetProfile.setName(widget.getTitle());
            widgetProfile.setWidId(widget.getUri());
            widgetProfile.setIcon(widget.getIcon());
            widgetProfile.setCreated(new Date());
            widgetProfile.setUpdated(new Date());
            widgetProfile.setAuthor(widget.getAuthor());
            widgetProfile.setLicense(widget.getLicense());
            entityManager.persist(widgetProfile);

            //
            // Create the widget description
            //
            WidgetDescription widgetDescription = new WidgetDescription();
            widgetDescription.setWid_id(widgetProfile.getId());
            widgetDescription.setDescription(widget.getDescription());
            widgetProfile.setDescription(widgetDescription);

            //
            // Create the widget stats
            //
            WidgetStats widgetStats = new WidgetStats();
            widgetStats.setWid_id(widgetProfile.getId());
            widgetStats.setDownloads(0);
            widgetStats.setEmbeds(0);
            widgetStats.setViews(0);
            entityManager.persist(widgetStats);

        }

        widgetProfiles.add(widgetProfile);
    }

    entityManager.getTransaction().commit();
    entityManager.close();

    return widgetProfiles;
}

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

@Test(enabled = TESTS_ENABLED)
public void testMergeSyncReport() throws Exception {
    PageControl pc;/*from w  w w.j a v a2 s .c om*/
    int repoId = 0;
    int contentSourceId = 0;

    try {
        // create content source type
        ContentSourceType type = new ContentSourceType("testMergeSyncReportCST");
        Set<ContentSourceType> types = new HashSet<ContentSourceType>();
        types.add(type);
        contentSourceMetadataManager.registerTypes(types); // this blows away any previous existing types
        type = contentSourceManager.getContentSourceType(type.getName());
        assert type != null;
        assert type.getId() > 0;

        // create content source
        ContentSource contentSource = new ContentSource("testMergeSyncReportCS", type);
        contentSource = contentSourceManager.simpleCreateContentSource(overlord, contentSource);
        assert contentSource != null;
        contentSourceId = contentSource.getId();
        assert contentSourceId > 0;

        // create a repo
        Repo repo = new Repo("testRepo");
        repo = repoManager.createRepo(overlord, repo);
        repoId = repo.getId();

        // this report will add a mapping to PV->CS
        // we didn't set up any mappings like that yet - this will be the first one
        PackageSyncReport report = new PackageSyncReport();
        ContentProviderPackageDetailsKey key = new ContentProviderPackageDetailsKey(
                "testCreateContentSourceFoo", "testCreateContentSourceVer", packageType1.getName(),
                architecture1.getName(), resourceType1.getName(), resourceType1.getPlugin());
        ContentProviderPackageDetails details = new ContentProviderPackageDetails(key);
        details.setLocation("dummy-location");
        details.setMetadata("dummy-metadata".getBytes());
        details.addResourceVersion("1.0.0");
        details.addResourceVersion("2.0.0");
        report.addNewPackage(details);
        Map<ContentProviderPackageDetailsKey, PackageVersionContentSource> previous;
        previous = new HashMap<ContentProviderPackageDetailsKey, PackageVersionContentSource>();

        // merge the report!
        RepoSyncResults results = new RepoSyncResults(repo);
        results = repoManager.persistRepoSyncResults(results);
        assert results != null;

        results = contentSourceManager.mergePackageSyncReport(contentSource, repo, report, previous, results);
        assert results != null;

        // Verify the product version was created
        getTransactionManager().begin();
        EntityManager em = getEntityManager();
        try {
            resourceType1 = em.find(ResourceType.class, resourceType1.getId());

            Query productVersionQuery = em
                    .createNamedQuery(ProductVersion.QUERY_FIND_BY_RESOURCE_TYPE_AND_VERSION);
            productVersionQuery.setParameter("resourceType", resourceType1);
            productVersionQuery.setParameter("version", "1.0.0");

            List productVersionList = productVersionQuery.getResultList();
            assert productVersionList.size() > 0 : "Could not find product version for 1.0.0";

            productVersionQuery = em.createNamedQuery(ProductVersion.QUERY_FIND_BY_RESOURCE_TYPE_AND_VERSION);
            productVersionQuery.setParameter("resourceType", resourceType1);
            productVersionQuery.setParameter("version", "2.0.0");

            productVersionList = productVersionQuery.getResultList();
            assert productVersionList.size() > 0 : "Could not find product version for 2.0.0";
        } finally {
            getTransactionManager().rollback();
            em.close();
        }

        // see that the resource sees no metadata yet - not subscribed yet
        pc = PageControl.getUnlimitedInstance();
        PageList<PackageVersionMetadataComposite> metadataList;
        metadataList = contentSourceManager.getPackageVersionMetadata(resource1.getId(), pc);
        assert metadataList != null;
        assert metadataList.size() == 0 : "-->" + metadataList;
        String metadataMd5 = contentSourceManager.getResourceSubscriptionMD5(resource1.getId());
        assert metadataMd5 != null;
        assert metadataMd5.length() == 32 : "-->" + metadataMd5;
        assert metadataMd5.equals("d41d8cd98f00b204e9800998ecf8427e") : "-->" + metadataMd5;

        // just to make sure the MD5 for empty data is what we think it is...
        metadataMd5 = contentSourceManager.getResourceSubscriptionMD5(Integer.MIN_VALUE); // should find no metadata at all
        assert metadataMd5 != null;
        assert metadataMd5.length() == 32 : "-->" + metadataMd5;
        assert metadataMd5.equals("d41d8cd98f00b204e9800998ecf8427e") : "-->" + metadataMd5;

        // add the content source's packages to the repo
        repoManager.addContentSourcesToRepo(overlord, repoId, new int[] { contentSourceId });

        // see the package versions have been assigned to the repo and content source
        List<PackageVersion> inRepo;
        List<PackageVersionContentSource> inContentSources;
        List<PackageVersionContentSource> inContentSource;

        pc = PageControl.getUnlimitedInstance();
        inRepo = repoManager.findPackageVersionsInRepo(overlord, repoId, pc);
        pc = PageControl.getUnlimitedInstance();
        inContentSources = contentSourceManager.getPackageVersionsFromContentSources(overlord,
                new int[] { contentSourceId }, pc);
        inContentSource = contentSourceManager.getPackageVersionsFromContentSource(overlord, contentSourceId,
                pc);
        assert inRepo != null;
        assert inContentSources != null;
        assert inContentSource != null;
        assert inRepo.size() == 1 : inRepo;
        assert inContentSources.size() == 1 : inContentSources;
        assert inContentSource.size() == 1 : inContentSource;

        // confirm that we didn't load the bits yet
        pc = PageControl.getUnlimitedInstance();
        List<PackageVersionContentSource> unloaded;
        unloaded = contentSourceManager.getUnloadedPackageVersionsFromContentSourceInRepo(overlord,
                contentSourceId, repoId, pc);
        assert unloaded != null;
        assert unloaded.size() == 1;

        // check the counts
        long pvccount = repoManager.getPackageVersionCountFromRepo(overlord, repo.getId());
        assert (pvccount == 1) : "-->" + pvccount;
        long pvcscount = contentSourceManager.getPackageVersionCountFromContentSource(overlord,
                contentSourceId);
        assert (pvcscount == 1) : "-->" + pvcscount;

        // subscribe the resource
        repoManager.subscribeResourceToRepos(overlord, resource1.getId(), new int[] { repoId });

        // confirm the resource is subscribed
        pc = PageControl.getUnlimitedInstance();
        metadataList = contentSourceManager.getPackageVersionMetadata(resource1.getId(), pc);
        assert metadataList != null;
        assert metadataList.size() == 1 : "-->" + metadataList;
        metadataMd5 = contentSourceManager.getResourceSubscriptionMD5(resource1.getId());
        assert metadataMd5 != null;
        assert metadataMd5.length() == 32 : "-->" + metadataMd5;

        // MD5 is based on the hash code of last modified time
        repo = repoManager.getRepo(overlord, repoId);
        long modifiedTimestamp = repo.getLastModifiedDate();
        Date modifiedDate = new Date(modifiedTimestamp);
        String datehash = Integer.toString(modifiedDate.hashCode());
        assert metadataMd5.equals(MessageDigestGenerator.getDigestString(datehash)) : "-->" + metadataMd5;

        repoManager.unsubscribeResourceFromRepos(overlord, resource1.getId(), new int[] { repoId });

        // confirm the resource is unsubscribed
        pc = PageControl.getUnlimitedInstance();
        metadataList = contentSourceManager.getPackageVersionMetadata(resource1.getId(), pc);
        assert metadataList != null;
        assert metadataList.size() == 0 : "-->" + metadataList;
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        try {
            // clean up - delete all created entities
            if (repoId != 0) {
                repoManager.deleteRepo(overlord, repoId);
            }

            if (contentSourceId != 0) {
                contentSourceManager.deleteContentSource(overlord, contentSourceId);
            }

            contentSourceMetadataManager.registerTypes(new HashSet<ContentSourceType>());
        } catch (Throwable t) {
        }
    }
}

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

public int getItemCount(Class classObj, String query, Map<String, Object> map) throws Exception {
    int returnValue = 0;

    EntityManagerFactory emf = null;//from  w w w .  ja v  a  2  s  .  c  o  m
    EntityManager em = null;
    Query q = null;
    Iterator i = null;
    Map.Entry entry = null;
    try {
        emf = getEntityManagerFactory();
        em = emf.createEntityManager();

        q = em.createNamedQuery(query);

        if (map != null) {
            for (i = map.entrySet().iterator(); i.hasNext();) {
                entry = (Map.Entry) i.next();
                q.setParameter((String) entry.getKey(), entry.getValue());
            }
        }
        returnValue = ((Long) q.getSingleResult()).intValue();
    } catch (Exception e) {
        throw e;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
        }
        em = null;
        q = null;
        i = null;
        entry = null;
    }
    return returnValue;
}