List of usage examples for javax.persistence EntityManager close
public void close();
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.test.MetaCategoryErrorITCase.java
/** * Test add./* w w w.j av a2 s. c o m*/ * * @throws Exception the exception */ @Test public void testMetaCategory_Error_single_document() throws Exception { long size = countArticles(); EntityManager em = emf.createEntityManager(); String[] ids = new String[] { "1000", "1001" }; // insert all items for (String id : ids) { // item should not be in the db Query query = em.createQuery( new StringBuilder().append("SELECT x FROM news x WHERE x.fs_id = ").append(id).toString()); assertEquals(0, query.getResultList().size()); // load content String content = getContent("src/test/resources/inbox/add/pressreleasesdetails_" + id + ".xml", "hibernate"); // send content to jms broker template.sendBody("jms:topic:BUS_OUT", content); // wait Thread.sleep(TimeOuts.LONG); // item should be inserted to db query = em.createQuery( new StringBuilder().append("SELECT x FROM news x WHERE x.fs_id = ").append(id).toString()); assertEquals(1, query.getResultList().size()); } assertEquals("not all items are present", size + ids.length, countArticles()); Query query = em.createQuery( new StringBuilder().append("SELECT x FROM category x WHERE x.fs_id = 2001").toString()); // Query query = em.createQuery(new StringBuilder().append("SELECT x FROM category x WHERE x.fs_id = 3786").toString()); NewsCategory cat = (NewsCategory) query.getSingleResult(); assertEquals(2, cat.getMetaCategories().size()); em.close(); }
From source file:com.enioka.jqm.api.HibernateClient.java
private EntityManagerFactory createFactory() { jqmlogger.debug("Creating connection pool to database"); InputStream fis = null;// w w w . jav a 2 s . co m try { fis = this.getClass().getClassLoader().getResourceAsStream("META-INF/jqm.properties"); if (fis == null) { jqmlogger.trace("No jqm.properties file found."); } else { p.load(fis); jqmlogger.trace("A jqm.properties file was found"); } } catch (IOException e) { // We allow no configuration files, but not an unreadable configuration file. throw new JqmClientException("META-INF/jqm.properties file is invalid", e); } finally { closeQuietly(fis); } EntityManagerFactory newEmf = null; if (p.containsKey("javax.persistence.nonJtaDataSource")) { // This is a hack. Some containers will use root context as default for JNDI (WebSphere, Glassfish...), other will use // java:/comp/env/ (Tomcat...). So if we actually know the required alias, we try both, and the user only has to provide a // root JNDI alias that will work in both cases. try { newEmf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, p); // Do a stupid query to force EMF initialization EntityManager em = newEmf.createEntityManager(); em.createQuery("SELECT n from Node n WHERE 1=0").getResultList().size(); em.close(); } catch (RuntimeException e) { if (e.getCause() != null && e.getCause().getCause() != null && e.getCause().getCause() instanceof NameNotFoundException) { jqmlogger.debug("JNDI alias " + p.getProperty("javax.persistence.nonJtaDataSource") + " was not found. Trying with java:/comp/env/ prefix"); p.setProperty("javax.persistence.nonJtaDataSource", "java:/comp/env/" + p.getProperty("javax.persistence.nonJtaDataSource")); newEmf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, p); // Do a stupid query to force EMF initialization EntityManager em = newEmf.createEntityManager(); em.createQuery("SELECT n from Node n WHERE 1=3").getResultList().size(); em.close(); } else { throw e; } } } else { newEmf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, p); } return newEmf; }
From source file:com.enioka.jqm.api.HibernateClient.java
private void closeQuietly(EntityManager em) { try {/*from w ww . j a v a 2 s .co m*/ if (em != null) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } catch (Exception e) { // fail silently } }
From source file:com.epam.training.taranovski.web.project.repository.implementation.VacancyRepositoryImplementation.java
@Override public List<Employee> getAppropriateAvailableEmployees(Vacancy vacancy) { EntityManager em = entityManagerFactory.createEntityManager(); List<Integer> list = null; List<Employee> list1 = new LinkedList<>(); try {//from w ww. j a va 2 s . co m em.getTransaction().begin(); Query query = em.createNativeQuery( "select \"employeeId\" from (select \"employeeId\", \"vacancyId\" as \"ide\", count(*) as cou from (select \"UserSkill\".\"employeeId\", \"VacancySkill\".\"vacancyId\", \"UserSkill\".\"experience\", \"VacancySkill\".\"experience\" from \"UserSkill\" join \"VacancySkill\" on \"UserSkill\".\"allSkillsId\" = \"VacancySkill\".\"allSkillsId\" where \"UserSkill\".\"experience\" >= \"VacancySkill\".\"experience\" and \"VacancySkill\".\"vacancyId\" = ?) group by \"employeeId\", \"vacancyId\") where cou = (select count(*) from \"VacancySkill\" where \"VacancySkill\".\"vacancyId\" = \"ide\")"); query.setParameter(1, vacancy.getVacancyId()); list = query.getResultList(); if (list.isEmpty()) { list.add(0); } TypedQuery<Employee> query1 = em.createNamedQuery("Employee.findAmongIdsFreeEmployees", Employee.class); query1.setParameter("employeeIdList", list); list1 = query1.getResultList(); em.getTransaction().commit(); } catch (RuntimeException e) { Logger.getLogger(VacancyRepositoryImplementation.class.getName()).info(e); } finally { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } return list1; }
From source file:de.zib.gndms.infra.system.GNDMSystem.java
/** * Refreshes all resources corresponding to a specific GNDMPersistentServiceHome * @param home the GNDMPersistentServiceHome,whose Resource will be refreshed * @param <M> the model type//from w ww. j av a 2 s . co m */ @SuppressWarnings({ "ConstantConditions" }) public final <M extends GridResource> void refreshAllResources( final @NotNull GNDMPersistentServiceHome<M> home) { final EntityManager manager = home.getEntityManagerFactory().createEntityManager(); try { try { manager.getTransaction().begin(); for (String id : listAllResources(home, manager)) { try { if (isDebugging()) logger.debug("Restoring " + home.getNickName() + ':' + id); home.find(home.getKeyForId(id)); } catch (ResourceException e) { logger.warn(e); } } manager.getTransaction().commit(); } finally { if (manager.getTransaction().isActive()) manager.getTransaction().rollback(); } } finally { if (manager.isOpen()) manager.close(); } }
From source file:it.infn.ct.futuregateway.apiserver.v1.ApplicationService.java
/** * Removes the application. Delete the application only if there are not * tasks associated with it because tasks must be associated with an * application./*w w w . j a va 2 s . co m*/ * <p> * Applications with associated tasks can only be disabled to avoid future * execution of new tasks. Nevertheless, a task can be associated with a * disabled application and in this case will stay waiting until the * application is enabled. * * @param id Id of the application to remove */ @DELETE public final void deleteApp(@PathParam("id") final String id) { Application app; EntityManager em = getEntityManager(); try { app = em.find(Application.class, id); if (app == null) { throw new NotFoundException(); } EntityTransaction et = em.getTransaction(); try { et.begin(); List<Object[]> taskForApp = em.createNamedQuery("tasks.forApplication").setParameter("appId", id) .setMaxResults(1).getResultList(); if (taskForApp == null || taskForApp.isEmpty()) { em.remove(app); } else { log.info("Application " + id + " has tasks and cannot be" + " deleted"); throw new WebApplicationException( "The application cannot " + "be removed because there are associated tasks", Response.Status.CONFLICT); } et.commit(); } catch (WebApplicationException wex) { throw wex; } catch (RuntimeException re) { log.error(re); log.error("Impossible to remove the application"); throw new InternalServerErrorException("Error to remove " + "the application " + id); } finally { if (et != null && et.isActive()) { et.rollback(); } } } catch (IllegalArgumentException re) { log.error("Impossible to retrieve the application list"); log.error(re); throw new BadRequestException("Application '" + id + "' " + "does not exist!"); } finally { em.close(); } }
From source file:com.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java
/** * Add or update a news article in the db * * @param entity The NewsItem/*from www .j a v a2 s .com*/ */ public void add(UXBEntity entity) throws Exception { Article art = buildArticle(entity); 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 = :fsid AND x.language=:language").toString()); query.setParameter("fsid", art.getAid()); query.setParameter("language", art.getLanguage()); /* * If the item exists in the db, we update the content and the title of the existing item */ if (query.getResultList().size() > 0) { Article db = (Article) query.getSingleResult(); db.setContent(art.getContent()); db.setTitle(art.getTitle()); db.setUrl(art.getUrl()); db.setCreated(art.getCreated()); db.setAid(art.getAid()); db.setLanguage(art.getLanguage()); db.setVersion(art.getVersion()); db.setLastmodified(art.getLastmodified()); art = db; } // save to db em.persist(art); em.flush(); tx.commit(); } catch (Exception e) { if (tx != null) { tx.setRollbackOnly(); throw e; } logger.error("Failure while writing to the database", e); } finally { if (tx != null && tx.isActive()) { if (tx.getRollbackOnly()) { tx.rollback(); } } if (em != null) { em.close(); } } }
From source file:org.noorganization.instalist.server.api.TagResource.java
/** * Get a list of tags.//from w ww . ja v a2s .c o m * @param _groupId The id of the group containing the tags. * @param _changedSince Limits the request to elements that changed since the given date. ISO * 8601 time e.g. 2016-01-19T11:54:07+0100. Optional. */ @GET @TokenSecured @Produces({ "application/json" }) public Response getTags(@PathParam("groupid") int _groupId, @QueryParam("changedsince") String _changedSince) throws Exception { Instant changedSince = null; try { if (_changedSince != null) changedSince = ISO8601Utils.parse(_changedSince, new ParsePosition(0)).toInstant(); } catch (ParseException _e) { return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE); } EntityManager manager = DatabaseHelper.getInstance().getManager(); List<Tag> tags; List<DeletedObject> deletedTags; DeviceGroup group = manager.find(DeviceGroup.class, _groupId); if (changedSince != null) { TypedQuery<Tag> tagQuery = manager.createQuery( "select t from Tag t where " + "t.group = :group and t.updated > :updated", Tag.class); tagQuery.setParameter("group", group); tagQuery.setParameter("updated", changedSince); tags = tagQuery.getResultList(); TypedQuery<DeletedObject> deletedRecipesQuery = manager.createQuery( "select do " + "from DeletedObject do where do.group = :group and do.updated > :updated and " + "do.type = :type", DeletedObject.class); deletedRecipesQuery.setParameter("group", group); deletedRecipesQuery.setParameter("updated", changedSince); deletedRecipesQuery.setParameter("type", DeletedObject.Type.TAG); deletedTags = deletedRecipesQuery.getResultList(); } else { tags = new ArrayList<Tag>(group.getTags()); TypedQuery<DeletedObject> deletedRecipesQuery = manager.createQuery( "select do " + "from DeletedObject do where do.group = :group and do.type = :type", DeletedObject.class); deletedRecipesQuery.setParameter("group", group); deletedRecipesQuery.setParameter("type", DeletedObject.Type.TAG); deletedTags = deletedRecipesQuery.getResultList(); } manager.close(); ArrayList<TagInfo> rtn = new ArrayList<TagInfo>(tags.size() + deletedTags.size()); for (Tag current : tags) { TagInfo toAdd = new TagInfo().withDeleted(false); toAdd.setUUID(current.getUUID()); toAdd.setName(current.getName()); toAdd.setLastChanged(Date.from(current.getUpdated())); rtn.add(toAdd); } for (DeletedObject current : deletedTags) { TagInfo toAdd = new TagInfo().withDeleted(true); toAdd.setUUID(current.getUUID()); toAdd.setLastChanged(Date.from(current.getUpdated())); rtn.add(toAdd); } return ResponseFactory.generateOK(rtn); }
From source file:org.noorganization.instalist.server.api.UnitResource.java
/** * Get a list of units./* w ww. ja va 2 s . c om*/ * @param _groupId The id of the group containing the requested units. * @param _changedSince Requests only the elements that changed since the given date. ISO * 8601 time e.g. 2016-01-19T11:54:07+01:00 */ @GET @TokenSecured @Produces({ "application/json" }) public Response getUnits(@PathParam("groupid") int _groupId, @QueryParam("changedsince") String _changedSince) throws Exception { Instant changedSince = null; try { if (_changedSince != null) changedSince = ISO8601Utils.parse(_changedSince, new ParsePosition(0)).toInstant(); } catch (ParseException _e) { return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE); } EntityManager manager = DatabaseHelper.getInstance().getManager(); DeviceGroup group = manager.find(DeviceGroup.class, _groupId); List<Unit> resultUnits; List<DeletedObject> resultDeletedUnits; if (changedSince == null) { resultUnits = new ArrayList<Unit>(group.getUnits()); TypedQuery<DeletedObject> deletedUnitsQuery = manager.createQuery( "select do from " + "DeletedObject do where do.group = :group and do.type = :type", DeletedObject.class); deletedUnitsQuery.setParameter("group", group); deletedUnitsQuery.setParameter("type", DeletedObject.Type.UNIT); resultDeletedUnits = deletedUnitsQuery.getResultList(); } else { TypedQuery<Unit> unitsQuery = manager.createQuery( "select u from Unit u where " + "u.group = :group and u.updated > :updated", Unit.class); unitsQuery.setParameter("group", group); unitsQuery.setParameter("updated", changedSince); resultUnits = unitsQuery.getResultList(); TypedQuery<DeletedObject> deletedUnitsQuery = manager.createQuery("select do from " + "DeletedObject do where do.group = :group and do.type = :type and " + "do.updated > :updated", DeletedObject.class); deletedUnitsQuery.setParameter("group", group); deletedUnitsQuery.setParameter("type", DeletedObject.Type.UNIT); deletedUnitsQuery.setParameter("updated", changedSince); resultDeletedUnits = deletedUnitsQuery.getResultList(); } manager.close(); List<UnitInfo> rtn = new ArrayList<UnitInfo>(resultUnits.size() + resultDeletedUnits.size()); for (Unit current : resultUnits) { UnitInfo info = new UnitInfo().withDeleted(false); info.setName(current.getName()); info.setUUID(current.getUUID()); info.setLastChanged(Date.from(current.getUpdated())); rtn.add(info); } for (DeletedObject current : resultDeletedUnits) { UnitInfo info = new UnitInfo().withDeleted(true); info.setUUID(current.getUUID()); info.setLastChanged(Date.from(current.getUpdated())); rtn.add(info); } return ResponseFactory.generateOK(rtn); }
From source file:op.care.med.inventory.PnlInventory.java
private void txtSucheActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSucheActionPerformed JXSearchField search = (JXSearchField) evt.getSource(); if (!search.getText().isEmpty() && search.getText().matches("\\d*")) { // numbers only ! long id = Long.parseLong(search.getText()); EntityManager em = OPDE.createEM(); final MedStock stock = em.find(MedStock.class, id); em.close(); if (stock != null) { final String key = stock.getInventory().getID() + ".xinventory"; if (!resident.equals(stock.getInventory().getResident())) { if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.ARCHIVE, "nursingrecords.info")) { switchResident(stock.getInventory().getResident(), stock.getInventory(), new Closure() { @Override public void execute(Object o) { synchronized (mapKey2ClosedToggleButton) { mapKey2ClosedToggleButton.get(key).setSelected(true); }// ww w . ja v a 2 s . co m } }); } else { OPDE.getDisplayManager().addSubMessage(new DisplayMessage("misc.msg.noarchiveaccess")); } } else { synchronized (mapKey2ClosedToggleButton) { // CollapsiblePane myCP = cpMap.get(key); if (cpMap.get(key).isCollapsed()) { try { cpMap.get(key).setCollapsed(false); } catch (PropertyVetoException e) { // bah! } } } } } else { OPDE.getDisplayManager().addSubMessage(new DisplayMessage("misc.msg.notfound")); } } }