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.fracturedatlas.athena.apa.impl.jpa.JpaApaAdapter.java

@Override
public Boolean deleteRecord(String type, Object id) {
    logger.debug("Deleting ticket: " + id);
    if (id == null) {
        return false;
    }//from   w w  w  .  jav  a2s  .  c o m
    EntityManager em = this.emf.createEntityManager();
    try {
        Long longId = LongUserType.massageToLong(id);
        em.getTransaction().begin();
        JpaRecord t = em.find(JpaRecord.class, longId);
        logger.trace("Deleting ticket: " + t);
        em.remove(t);
        logger.trace("Deleted ticket: " + longId);
        em.getTransaction().commit();
        deleteFromIndex(id);
        return true;
    } finally {
        cleanup(em);
    }
}

From source file:de.zib.gndms.GORFX.context.service.globus.resource.TaskResource.java

@Override
public void remove() {

    if (taskAction != null) {
        Log log = taskAction.getLog();//from w  w w . j a  va  2  s  .  c  om
        log.debug("Removing task resource: " + getID());
        AbstractTask tsk = taskAction.getModel();
        boolean cleanUp = false;
        if (tsk != null) {
            if (!tsk.isDone()) {
                // task is still running cancel it and cleanup entity manager
                taskAction.setCancelled(true);
                log.debug("cancel task " + tsk.getWid());
                cleanUp = true;
                if (future != null) {
                    future.cancel(true);
                    try {
                        // give cancel some time
                        Thread.sleep(2000L);
                    } catch (InterruptedException e) {
                        logger.debug(e);
                    }
                }

                try {
                    EntityManager em = taskAction.getEntityManager();
                    if (em != null && em.isOpen()) {
                        try {
                            EntityTransaction tx = em.getTransaction();
                            if (tx.isActive())
                                tx.rollback();
                        } finally {
                            em.close();
                        }
                    }
                } catch (Exception e) {
                    // don't bother with exceptions
                    log.debug("Exception on task future cancel: " + e.toString(), e);
                }
            }

            EntityManager em = home.getEntityManagerFactory().createEntityManager();
            TxFrame tx = new TxFrame(em);
            // cleanup if necessary
            try {
                try {
                    Task t = em.find(Task.class, tsk.getId());
                    t.setPostMortem(true);
                    tx.commit();

                    if (cleanUp) {
                        log.debug("Triggering task cleanup");
                        try {
                            taskAction.setOwnEntityManager(em);
                            taskAction.cleanUpOnFail(t);
                        } catch (Exception e) {
                            log.debug("Exception on cleanup: " + e.toString());
                        }
                    }

                    // remove task from db
                    log.debug("Removing task: " + t.getId());
                    tx.begin();
                    em.remove(t);
                    tx.commit();
                } finally {
                    tx.finish();
                    if (em.isOpen())
                        em.close();
                }
            } catch (Exception e) {
                log.debug("Exception on task resource removal: " + e.toString());
                e.printStackTrace();
            }
        }
    }
}

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

private void setupTestEnvironment() throws Exception {
    getTransactionManager().begin();// w w w .  j a v a  2s . c  o m
    EntityManager em = getEntityManager();

    try {
        try {
            architecture1 = em.find(Architecture.class, 1);
            architecture2 = em.find(Architecture.class, 2);

            resourceType1 = new ResourceType("platform-" + System.currentTimeMillis(), "TestPlugin",
                    ResourceCategory.PLATFORM, null);
            em.persist(resourceType1);

            // Add package types to resource type
            packageType1 = new PackageType();
            packageType1.setName("package1-" + System.currentTimeMillis());
            packageType1.setDescription("");
            packageType1.setCategory(PackageCategory.DEPLOYABLE);
            packageType1.setDisplayName("TestResourcePackage");
            packageType1.setCreationData(true);
            packageType1.setResourceType(resourceType1);
            em.persist(packageType1);

            packageType2 = new PackageType();
            packageType2.setName("package2-" + System.currentTimeMillis());
            packageType2.setDescription("");
            packageType2.setCategory(PackageCategory.DEPLOYABLE);
            packageType2.setDisplayName("TestResourcePackage2");
            packageType2.setCreationData(true);
            packageType2.setResourceType(resourceType1);
            em.persist(packageType2);

            packageType3 = new PackageType();
            packageType3.setName("package3-" + System.currentTimeMillis());
            packageType3.setDescription("");
            packageType3.setCategory(PackageCategory.DEPLOYABLE);
            packageType3.setDisplayName("TestResourcePackage3");
            packageType3.setCreationData(true);
            packageType3.setResourceType(resourceType1);
            em.persist(packageType3);

            packageType4 = new PackageType();
            packageType4.setName("package4-" + System.currentTimeMillis());
            packageType4.setDescription("");
            packageType4.setCategory(PackageCategory.DEPLOYABLE);
            packageType4.setDisplayName("TestResourcePackage4");
            packageType4.setCreationData(true);
            packageType4.setResourceType(resourceType1);
            em.persist(packageType4);

            resourceType1.addPackageType(packageType1);
            resourceType1.addPackageType(packageType2);
            resourceType1.addPackageType(packageType3);

            // Package 1 - Contains 2 versions
            package1 = new Package("Package1", packageType1);

            package1.addVersion(new PackageVersion(package1, "1.0.0", architecture1));
            package1.addVersion(new PackageVersion(package1, "2.0.0", architecture1));

            em.persist(package1);

            // Package 2 - Contains 2 versions
            package2 = new Package("Package2", packageType2);

            package2.addVersion(new PackageVersion(package2, "1.0.0", architecture1));
            package2.addVersion(new PackageVersion(package2, "2.0.0", architecture1));

            em.persist(package2);

            // Package 3 - Contains 1 version
            package3 = new Package("Package3", packageType3);

            package3.addVersion(new PackageVersion(package3, "1.0.0", architecture1));

            em.persist(package3);

            // Package 4 - Contains 2 versions, the first is installed
            package4 = new Package("Package4", packageType4);

            PackageVersion package4Installed = new PackageVersion(package4, "1.0.0", architecture1);
            package4.addVersion(package4Installed);
            package4.addVersion(new PackageVersion(package4, "2.0.0", architecture1));

            em.persist(package4);

            // Package 5 - Contains 1 version, it is installed
            package5 = new Package("Package5", packageType4);

            PackageVersion package5Installed = new PackageVersion(package5, "1.0.0", architecture1);
            package5.addVersion(package5Installed);

            em.persist(package5);

            // Create resource against which we'll merge the discovery report
            resource1 = new Resource("parent" + System.currentTimeMillis(), "name", resourceType1);
            resource1.setUuid("" + new Random().nextInt());
            em.persist(resource1);

            // Install packages on the resource
            installedPackage1 = new InstalledPackage();
            installedPackage1.setResource(resource1);
            installedPackage1.setPackageVersion(package4Installed);
            resource1.addInstalledPackage(installedPackage1);

            installedPackage2 = new InstalledPackage();
            installedPackage2.setResource(resource1);
            installedPackage2.setPackageVersion(package4Installed);
            resource1.addInstalledPackage(installedPackage2);

            installedPackage1.setResource(resource1);
            installedPackage2.setResource(resource1);

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

From source file:nl.b3p.kaartenbalie.struts.UserAction.java

protected User getUser(DynaValidatorForm dynaForm, HttpServletRequest request, boolean createNew)
        throws Exception {

    log.debug("Getting entity manager ......");
    EntityManager em = getEntityManager();

    User sessUser = (User) request.getUserPrincipal();
    // Alleen beheeders mogen iemand anders bewerken
    if (!request.isUserInRole(Roles.ADMIN) && !createNew) {
        if (sessUser == null) {
            return null;
        }//from   w  w w.j  a  v a2  s .co m
        return (User) em.createQuery("from User u where u.id = :id").setParameter("id", sessUser.getId())
                .getSingleResult();
    }

    User user = null;
    Integer id = getID(dynaForm);
    if (null == id && createNew) {
        user = new User();
    } else if (null != id) {
        user = (User) em.find(User.class, new Integer(id.intValue()));
    }

    if (user == null) {
        return sessUser;
    }
    return user;
}

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

public void deleteTModel(DeleteTModel body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//from  w w  w  .jav  a2s  .  co  m
        tx.begin();

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

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

        // tModels are only lazily deleted!
        List<String> entityKeyList = body.getTModelKey();
        for (String entityKey : entityKeyList) {
            Object obj = em.find(org.apache.juddi.model.Tmodel.class, entityKey);
            ((org.apache.juddi.model.Tmodel) obj).setDeleted(true);

        }

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

From source file:kirchnerei.note.model.DataService.java

public Long storeNote(NoteData noteData) {
    EntityManager em = null;
    EntityTransaction tx = null;/*w ww.ja va2  s  .  c o m*/
    try {
        em = entityService.get();
        tx = em.getTransaction();
        tx.begin();
        // search for category
        String category = noteData.getCategory();
        if (StringUtils.isEmpty(category)) {
            LogUtils.warn(log, "note without category is not allow [%s]", noteData);
            return null;
        }
        TypedQuery<Category> q = em.createNamedQuery("findCategory", Category.class);
        q.setParameter("category", category);
        Category cat = getSingleResult(q);
        if (cat == null) {
            // a new category
            cat = new Category();
            cat.setTitle(category);
            em.persist(cat);
        }
        final Note note;
        if (NumberUtils.isEmpty(noteData.getId())) {
            // create a new note
            note = beanCopy.copy(noteData, Note.class, noteProperties);
            note.setCategory(cat);
            cat.getNotes().add(note);
        } else {
            // update an existed note
            note = em.find(Note.class, noteData.getId());
            beanCopy.copy(noteData, note, noteProperties);
            if (!NumberUtils.compare(note.getCategory().getId(), cat.getId())) {
                // move to other category
                note.getCategory().getNotes().remove(note);
                cat.getNotes().add(note);
                note.setCategory(cat);
            }
        }
        EntityService.commit(tx);
        return note.getId();
    } catch (Exception e) {
        EntityService.rollback(tx);
        return null;
    } finally {
        EntityService.close(em);
    }
}

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

@Test(enabled = TESTS_ENABLED)
public void testMergeSyncReport() throws Exception {
    PageControl pc;/*from w  ww .  j a  v  a 2s .c o  m*/
    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:org.apache.juddi.api.impl.JUDDIApiImpl.java

/**
 * Saves nodes(s) to the persistence layer. This method is specific to
 * jUDDI. Administrative privilege required. This is used for server to server subscriptions and for future use
 * with replication. Administrative privilege required.
 * @param body/* ww  w.j av a2 s  .c o m*/
 * @return NodeDetail
 * @throws DispositionReportFaultMessage 
 */
public NodeDetail saveNode(SaveNode body) throws DispositionReportFaultMessage {

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

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

        new ValidateNode(publisher).validateSaveNode(em, body);

        NodeDetail result = new NodeDetail();

        List<org.apache.juddi.api_v3.Node> apiNodeList = body.getNode();
        ;
        for (org.apache.juddi.api_v3.Node apiNode : apiNodeList) {

            org.apache.juddi.model.Node modelNode = new org.apache.juddi.model.Node();

            MappingApiToModel.mapNode(apiNode, modelNode);

            Object existingUddiEntity = em.find(modelNode.getClass(), modelNode.getName());
            if (existingUddiEntity != null) {
                em.merge(modelNode);
            } else {
                em.persist(modelNode);
            }

            result.getNode().add(apiNode);
        }

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

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

/**
 * Saves clerk(s) to the persistence layer. This method is specific to
 * jUDDI. This is used for server to server subscriptions and for future use
 * with replication. Administrative privilege required.
 * @param body/*ww  w.  java  2 s . co  m*/
 * @return ClerkDetail
 * @throws DispositionReportFaultMessage 
 */
public ClerkDetail saveClerk(SaveClerk body) throws DispositionReportFaultMessage {

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

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

        new ValidateClerk(publisher).validateSaveClerk(em, body);

        ClerkDetail result = new ClerkDetail();

        List<org.apache.juddi.api_v3.Clerk> apiClerkList = body.getClerk();
        ;
        for (org.apache.juddi.api_v3.Clerk apiClerk : apiClerkList) {

            org.apache.juddi.model.Clerk modelClerk = new org.apache.juddi.model.Clerk();

            MappingApiToModel.mapClerk(apiClerk, modelClerk);

            Object existingUddiEntity = em.find(modelClerk.getClass(), modelClerk.getClerkName());
            if (existingUddiEntity != null) {
                em.merge(modelClerk);
            } else {
                em.persist(modelClerk);
            }

            result.getClerk().add(apiClerk);
        }

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

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

/**
 * Saves publisher(s) to the persistence layer. This method is specific
 * to jUDDI. Administrative privilege required.
 *
 * @param body//from ww w  . j a v a  2  s.c om
 * @return PublisherDetail
 * @throws DispositionReportFaultMessage
 */
public PublisherDetail savePublisher(SavePublisher body) throws DispositionReportFaultMessage {

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

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

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

        PublisherDetail result = new PublisherDetail();

        List<org.apache.juddi.api_v3.Publisher> apiPublisherList = body.getPublisher();
        for (org.apache.juddi.api_v3.Publisher apiPublisher : apiPublisherList) {

            org.apache.juddi.model.Publisher modelPublisher = new org.apache.juddi.model.Publisher();

            MappingApiToModel.mapPublisher(apiPublisher, modelPublisher);

            Object existingUddiEntity = em.find(modelPublisher.getClass(), modelPublisher.getAuthorizedName());
            if (existingUddiEntity != null) {
                em.remove(existingUddiEntity);
            }

            em.persist(modelPublisher);

            result.getPublisher().add(apiPublisher);
        }

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