List of usage examples for javax.persistence EntityManager close
public void close();
From source file:BO.UserHandler.java
public List<VUser> getFriends(VUser user) { EntityManager em; EntityManagerFactory emf;/*w w w. j av a 2 s .c o m*/ emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME); em = emf.createEntityManager(); try { List<Friendship> list = (List<Friendship>) em .createQuery("SELECT f FROM Friendship f WHERE f.receivingFriend.email LIKE :email " + "OR f.sendingFriend.email LIKE :email2") .setParameter("email", user.getEmail()).setParameter("email2", user.getEmail()).getResultList(); List<VUser> friends = new ArrayList<>(); for (Friendship f : list) { if (f.isDidAccept()) { if (f.getSendingFriend().getEmail().equals(user.getEmail())) { friends.add(new VUser(f.getReceivingFriend().getEmail(), "", "", "", false)); } else { friends.add(new VUser(f.getSendingFriend().getEmail(), "", "", "", false)); } } } return friends; } catch (Exception e) { return null; } finally { if (em != null) { em.close(); } emf.close(); } }
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(); exportJson(json, projectData);/*w w w.ja va 2 s . c o m*/ 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:mil.navy.med.dzreg.dao.RegistriesManagerDAO.java
/** * Check registry type, returns a DzType object. * @param r//ww w . j a v a 2 s .co m * @return DzType registry type object */ private DzType validRegistryType(RegistryType r) throws Exception { EntityManager em = null; PersistentServiceFactory psf = null; DzType registry = null; try { psf = PersistentServiceFactory.getInstance(REGISTRY_MANAGER_PU); em = psf.getEntityManager(); Query query = em.createNamedQuery("DzType.findByDztypeId"); query.setParameter("dztypeId", r.getRegistryId()); registry = (DzType) query.getSingleResult(); if (registry == null) { throw new Exception("Invalid/Unknown registy type requested - " + r.getRegistryId()); } log.debug("Located registry - " + registry); return registry; } catch (javax.persistence.NoResultException nre) { throw new Exception("Invalid/Unknown registy type requested - " + r.getRegistryId()); } catch (Exception ex) { throw new Exception("Failed to register patient in registry."); } finally { em.close(); } }
From source file:com.sun.socialsite.userapi.UserManagerImpl.java
private UserRole getOrCreateRole(String roleName) throws PersistenceException { UserRole role = null;//from www . ja v a 2 s . c o m try { Query query = getNamedQuery("UserRole.findByRoleName"); query.setParameter("roleName", roleName); role = (UserRole) query.getSingleResult(); } catch (NoResultException nre) { // create the role in database EntityManager em2 = null; try { em2 = getEmf().createEntityManager(); em2.getTransaction().begin(); UserRole newRole = new UserRole(); newRole.setRoleName(roleName); em2.persist(newRole); em2.flush(); em2.getTransaction().commit(); } catch (PersistenceException pe) { if (em2 == null) { // If we couldn't even create an EntityManager, something is clearly wrong throw pe; } else { // Otherwise, ignore exception for now; the role may have been created in another thread if (em2.getTransaction().isActive()) em2.getTransaction().rollback(); } } finally { if (em2 != null) em2.close(); } } // If role is null, try again (since it _should_ now exist in the DB). if (role == null) { Query query = getNamedQuery("UserRole.findByRoleName"); query.setParameter("roleName", roleName); role = (UserRole) query.getSingleResult(); } return role; }
From source file:com.sixsq.slipstream.run.RunNodeResource.java
private Representation addNodeInstancesInTransaction(Representation entity) throws Exception { EntityManager em = PersistenceUtil.createEntityManager(); EntityTransaction transaction = em.getTransaction(); Run run = Run.loadFromUuid(getUuid(), em); List<String> instanceNames = new ArrayList<String>(); try {/*w w w .java2 s . c o m*/ validateRun(run); transaction.begin(); int noOfInst = getNumberOfInstancesToAdd(entity); Node node = getNode(run, nodename); for (int i = 0; i < noOfInst; i++) { instanceNames.add(createNodeInstanceOnRun(run, node)); } run.postEventScaleUp(nodename, instanceNames, noOfInst); incrementNodeMultiplicityOnRun(noOfInst, run); StateMachine.createStateMachine(run).tryAdvanceToProvisionning(); if (Configuration.isQuotaEnabled()) { User user = User.loadByName(run.getUser()); Quota.validate(user, run.getCloudServiceUsage(), Vm.usage(user.getName())); } transaction.commit(); } catch (Exception ex) { if (transaction.isActive()) { transaction.rollback(); } throw ex; } finally { em.close(); } getResponse().setStatus(Status.SUCCESS_CREATED); return new StringRepresentation(StringUtils.join(instanceNames, ","), MediaType.TEXT_PLAIN); }
From source file:com.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java
/** * Deletes a news article from the db/*from w w w . j a va2 s . c o m*/ * * @param entity The article to delete */ public void delete(UXBEntity entity) throws Exception { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); // Query query = em.createQuery(new StringBuilder().append("SELECT x FROM Article x WHERE x.aid = ").append(entity.getUuid()).append(" AND x.language='").append(entity.getLanguage()).append("'").toString()); Query query = em.createQuery(new StringBuilder() .append("SELECT x FROM article x WHERE x.aid = :fsid AND x.language=:language").toString()); query.setParameter("fsid", Long.parseLong(entity.getUuid())); query.setParameter("language", entity.getLanguage()); if (!query.getResultList().isEmpty()) { Article art = (Article) query.getSingleResult(); em.remove(art); } tx.commit(); } catch (Exception e) { if (tx != null) { tx.setRollbackOnly(); throw e; } logger.error("Failure while deleting from the database", e); } finally { if (tx != null && tx.isActive()) { if (tx.getRollbackOnly()) { tx.rollback(); } } if (em != null) { em.close(); } } }
From source file:br.edimarmanica.fazenda.control.LoadBBControl.java
private boolean load(Pessoa pessoa, String file) { EntityManager em = Conexao.getEntityManager(); em.getTransaction().begin();/*from ww w.j a v a2s . c om*/ boolean error = false; try (CSVParser parser = CSVParser.parse(new File(file), Charset.forName("ISO-8859-1"), CSVFormat.EXCEL.withHeader())) { for (CSVRecord record : parser) { TipoCaixa tc = new TipoCaixa(); tc.setCdBb(new BigInteger(record.get("Nmero do documento"))); if (tc.getCdBb() != null) { List<TipoCaixa> tcs = daoTipo.search(tc); if (tcs != null && tcs.size() == 1) { Caixa caixa = new Caixa(); caixa.setCdTipoCaixa(tcs.get(0)); caixa.setCdPessoa(pessoa); caixa.setVlCaixa((new BigDecimal(record.get("Valor"))).abs()); caixa.setDtPagamento(new Date(record.get("Data"))); caixa.setDtVencimento(new Date(record.get("Data"))); caixa.setDsCaixa("IMPORTAO BB 02"); em.persist(caixa); } } } } catch (IOException ex) { Logger.getLogger(LoadBBControl.class.getName()).log(Level.SEVERE, null, ex); error = true; } if (!error) { em.getTransaction().commit(); } else { em.getTransaction().rollback(); } em.close(); return !error; }
From source file:au.edu.uq.cmm.paul.servlet.WebUIController.java
private DatafileMetadata fetchMetadata(File file) { EntityManager entityManager = createEntityManager(); try {/*w w w . ja v a 2 s. c o m*/ TypedQuery<DatafileMetadata> query = entityManager.createQuery( "from DatafileMetadata d where d.capturedFilePathname = :pathName", DatafileMetadata.class); query.setParameter("pathName", file.getAbsolutePath()); return query.getSingleResult(); } catch (NoResultException ex) { return null; } finally { entityManager.close(); } }
From source file:mil.navy.med.dzreg.dao.RegistriesManagerDAO.java
/** * Returns the registry profile of a person. * @param personId unique identifier of person * @return PersonRegistryProfileType// w w w .j a v a 2 s . c om */ public PersonRegistryProfileType getRegistryProfile(Long personId) { EntityManager em = null; PersonRegistryProfileType profile = null; PersistentServiceFactory psf = null; if (personId != null) { try { psf = PersistentServiceFactory.getInstance(REGISTRY_MANAGER_PU); em = psf.getEntityManager(); Query query = em.createNamedQuery("DzPatients.findByPatid"); query.setParameter("patid", personId); DzPatients result = (DzPatients) query.getSingleResult(); if (result != null) { em.refresh(result); //log.debug(result.toString()); try { profile = map(result); } catch (Exception e) { e.printStackTrace(); } } } catch (javax.persistence.NoResultException nr) { log.error("No data found for personId=" + personId); } finally { em.close(); } } else { log.error("personId can not be null or empty"); } return profile; }
From source file:com.github.jinahya.persistence.ShadowTest.java
@Test(enabled = true, invocationCount = 1) public void testNassword0() { final EntityManager manager = LocalPU.createEntityManager(); try {/*from w ww . j a v a2s. c o m*/ final EntityTransaction transaction = manager.getTransaction(); transaction.begin(); try { final String username = newUsername(manager); final byte[] password = newPassword(); Shadow shadow = persistInstance(manager, username, password); Assert.assertTrue(shadow.puthenticate(shadow, password)); System.out.println("========================================="); LOGGER.log(Level.INFO, "mortons: {0}", MORTONS(manager, 0, 1024)); final byte[] nassword = newPassword(); shadow.nassword(shadow, password, nassword); shadow = manager.merge(shadow); manager.flush(); System.out.println("========================================="); LOGGER.log(Level.INFO, "mortons: {0}", MORTONS(manager, 0, 1024)); Assert.assertFalse(shadow.puthenticate(shadow, password)); Assert.assertTrue(shadow.puthenticate(shadow, nassword)); transaction.commit(); } catch (Exception e) { transaction.rollback(); e.printStackTrace(System.err); Assert.fail(e.getMessage()); } } finally { manager.close(); } }