List of usage examples for javax.persistence EntityManager close
public void close();
From source file:BO.UserHandler.java
public boolean addFriend(VUser u) { EntityManager em; EntityManagerFactory emf;/*from www .j a v a 2 s . c om*/ emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME); em = emf.createEntityManager(); try { em.getTransaction().begin(); System.out.println(u.getEmail()); System.out.println(u.getFriendToAdd()); try { List<Friendship> f = (List<Friendship>) em .createQuery("SELECT f from Friendship f WHERE f.receivingFriend.email LIKE :email1 " + "AND f.sendingFriend.email LIKE :email2") .setParameter("email1", u.getEmail()).setParameter("email2", u.getFriendToAdd()) .getResultList(); if (!f.isEmpty()) { return false; } } catch (Exception e) { } try { List<Friendship> f = (List<Friendship>) em .createQuery("SELECT f from Friendship f WHERE f.sendingFriend.email LIKE :email1 " + "AND f.receivingFriend.email LIKE :email2") .setParameter("email1", u.getEmail()).setParameter("email2", u.getFriendToAdd()) .getResultList(); if (!f.isEmpty()) { return false; } } catch (Exception e) { } User sender = getUserByEmail(u.getEmail()); User receiver = getUserByEmail(u.getFriendToAdd()); Friendship friendship = new Friendship(sender, receiver); em.persist(friendship); em.flush(); em.getTransaction().commit(); return true; } catch (Exception e) { return false; } finally { if (em != null) { em.close(); } emf.close(); } }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.test.NewsITCase.java
/** * Test persistence.//from ww w . j a v a2 s . c om * * @throws Exception the exception */ @Test public void testPersistence() throws Exception { long size = countNews(); EntityManager em = emf.createEntityManager(); EntityTransaction tx = null; try { tx = em.getTransaction(); tx.begin(); News news = new News(); news.setContent("Spider-man was seen."); news.setHeadline("The amazing spider-man"); news.setFs_id(1l); news.setLanguage("DE"); news.setTeaser("spider-man"); NewsCategory sport = new NewsCategory(); sport.setFs_id(2l); sport.setName("Sport"); sport.setLanguage("DE"); NewsMetaCategory soccer = new NewsMetaCategory(); soccer.setFs_id(3l); soccer.setLanguage("DE"); soccer.setName("Fussball"); if (sport.getMetaCategories() == null) { sport.setMetaCategories(new ArrayList<NewsMetaCategory>()); } sport.getMetaCategories().add(soccer); if (news.getCategories() == null) { news.setCategories(new ArrayList<NewsCategory>()); } news.getCategories().add(sport); em.persist(news); em.flush(); tx.commit(); assertEquals("Entity not filled", size + 1, countNews()); Query query = em.createQuery("SELECT mc FROM metaCategory mc WHERE fs_id=3"); NewsMetaCategory metaCat = (NewsMetaCategory) query.getSingleResult(); assertNotNull(metaCat); query = em.createQuery( "SELECT c FROM category c join c.metaCategories mc WHERE mc.fs_id=" + metaCat.getFs_id()); NewsCategory category = (NewsCategory) query.getSingleResult(); assertNotNull(category); query = em.createQuery("SELECT n FROM news n join n.categories c WHERE c.fs_id=" + category.getFs_id()); News n = (News) query.getSingleResult(); assertNotNull(n); } finally { if (tx != null && tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java
/** * handle the update and save process./*from w w w.ja v a2 s. c o m*/ * * @param entity the newsdrilldown entity * @throws Exception the exception */ private void handle(UXBEntity entity) throws Exception { /** * Due to a hibernate problem when updating or saving a newsdrilldown with * related categories we have to perform these step for saving the newsdrilldown * * 1. save/update all categories and remove them from the newsdrilldown * 1.1 save/update all metaCategories and remove them from the categories * 1.2 save the categories * 1.3 read all metaCategories to the categories * 1.4 save the categories again to create the relations * 2. save the newsdrilldown * 3. read all categories to the newsdrilldown */ EntityManager em = null; EntityTransaction tx = null; try { News news = buildNews(entity); List<Long> categories = new ArrayList<Long>(); /* * 1. update or save all categories * Steps 1.1 - 1.4 */ if (news.getCategories() != null && !news.getCategories().isEmpty()) { for (NewsCategory cat : news.getCategories()) { cat = saveNewsCategory(cat); if (!categories.contains(cat.getFs_id())) { categories.add(cat.getFs_id()); } } news.setCategories(new ArrayList<NewsCategory>()); } em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); // 2. save the newsdrilldown news = saveNews(news, em); // 3. read all categories to the newsdrilldown if (!categories.isEmpty()) { for (Long cat : categories) { NewsCategory ncat = getNewsCategory(cat, news.getLanguage(), em); news.getCategories().add(ncat); } } tx.commit(); } catch (Exception e) { if (tx != null && tx.isActive()) { tx.setRollbackOnly(); } throw e; } finally { if (tx != null && tx.isActive()) { if (tx.getRollbackOnly()) { tx.rollback(); } } if (em != null) { em.close(); } } }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.test.CommandITCase.java
/** * Test add./*from w w w . jav a2s. co m*/ * * @throws Exception the exception */ @Test public void testAdd() throws Exception { long size = countArticles(); EntityManager em = emf.createEntityManager(); String[] ids = new String[] { "128", "130", "131", "132", "256" }; // 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()); // now check, that items are not insert twice if resend the same content for (String id : ids) { // 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); // only one item should be present Query query = em.createQuery( new StringBuilder().append("SELECT x FROM news x WHERE x.fs_id = ").append(id).toString()); assertEquals(1, query.getResultList().size()); } em.close(); }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.test.CommandITCase.java
/** * Test delete./*from w w w. ja v a2 s .c o m*/ * * @throws Exception the exception */ @Test public void testDelete() throws Exception { long size = countArticles(); EntityManager em = emf.createEntityManager(); String[] ids = new String[] { "132" }; // 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); query = em.createQuery( new StringBuilder().append("SELECT x FROM news x WHERE x.fs_id = ").append(id).toString()); assertEquals(1, query.getResultList().size()); } // wait Thread.sleep(TimeOuts.LONG); assertEquals("not all items are present", size + ids.length, countArticles()); // now send the delete command for (String id : ids) { // load content String content = getContent("src/test/resources/inbox/delete/pressreleasesdetails_" + id + ".xml", "hibernate"); // send content to jms broker template.sendBody("jms:topic:BUS_OUT", content); // wait Thread.sleep(TimeOuts.LONG); // item should be deleted Query query = em.createQuery( new StringBuilder().append("SELECT x FROM news x WHERE x.fs_id = ").append(id).toString()); assertEquals(0, query.getResultList().size()); } assertEquals("ups, there are items left in the db", size, countArticles()); em.close(); }
From source file:org.noorganization.instalist.server.api.CategoriesResource.java
/** * Get a list of categories.//from ww w . ja v a2 s . co m * * @param _groupId The id of the group. * @param _changedSince Optional. 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 getCategories(@PathParam("groupid") int _groupId, @QueryParam("changedsince") String _changedSince) throws Exception { try { Instant changedSince = null; if (_changedSince != null) { try { changedSince = ISO8601Utils.parse(_changedSince, new ParsePosition(0)).toInstant(); } catch (ParseException _e) { return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA); } } List<Category> categories; List<DeletedObject> deletedCategories; EntityManager manager = DatabaseHelper.getInstance().getManager(); DeviceGroup group = manager.find(DeviceGroup.class, _groupId); if (changedSince != null) { TypedQuery<Category> categoriesQuery = manager.createQuery( "select c from Category c " + "where c.group = :groupid and c.updated > :updated", Category.class); categoriesQuery.setParameter("groupid", group); categoriesQuery.setParameter("updated", changedSince); categories = categoriesQuery.getResultList(); TypedQuery<DeletedObject> deletedCategoriesQuery = manager .createQuery("select do " + "from DeletedObject do where do.group = :groupid and " + "do.type = :type and do.updated > :updated", DeletedObject.class); deletedCategoriesQuery.setParameter("groupid", group); deletedCategoriesQuery.setParameter("updated", changedSince); deletedCategoriesQuery.setParameter("type", DeletedObject.Type.CATEGORY); deletedCategories = deletedCategoriesQuery.getResultList(); } else { TypedQuery<Category> categoriesQuery = manager .createQuery("select c from Category c " + "where c.group = :groupid", Category.class); categoriesQuery.setParameter("groupid", group); categories = categoriesQuery.getResultList(); TypedQuery<DeletedObject> deletedCategoriesQuery = manager.createQuery( "select do " + "from DeletedObject do where do.group = :groupid and " + "do.type = :type", DeletedObject.class); deletedCategoriesQuery.setParameter("groupid", group); deletedCategoriesQuery.setParameter("type", DeletedObject.Type.CATEGORY); deletedCategories = deletedCategoriesQuery.getResultList(); } manager.close(); List<CategoryInfo> rtnPayload = new ArrayList<CategoryInfo>( categories.size() + deletedCategories.size()); for (Category currentCat : categories) { CategoryInfo info = new CategoryInfo(); info.setUUID(currentCat.getUUID()); info.setName(currentCat.getName()); info.setLastChanged(Date.from(currentCat.getUpdated())); info.setDeleted(false); rtnPayload.add(info); } for (DeletedObject currentCat : deletedCategories) { CategoryInfo info = new CategoryInfo(); info.setUUID(currentCat.getUUID()); info.setLastChanged(Date.from(currentCat.getUpdated())); info.setDeleted(true); rtnPayload.add(info); } return ResponseFactory.generateOK(rtnPayload); } catch (Exception _e) { _e.printStackTrace(); throw _e; } }
From source file:gov.osti.services.Metadata.java
/** * Obtain a reserved DOI value if possible. * * @return a DoiReservation if successful, or null if not *//*from www . j a v a 2s .c o m*/ private static DoiReservation getReservedDoi() { EntityManager em = DoeServletContextListener.createEntityManager(); // set a LOCK TIMEOUT to prevent collision em.setProperty("javax.persistence.lock.timeout", 5000); try { em.getTransaction().begin(); DoiReservation reservation = em.find(DoiReservation.class, DoiReservation.TYPE, LockModeType.PESSIMISTIC_WRITE); if (null == reservation) reservation = new DoiReservation(); reservation.reserve(); em.merge(reservation); em.getTransaction().commit(); // send it back return reservation; } catch (PessimisticLockException | LockTimeoutException e) { log.warn("DOI Reservation, unable to obtain lock.", e); return null; } finally { em.close(); } }
From source file:BO.UserHandler.java
public int sendChallengeRequest(VUser user) { EntityManager em; EntityManagerFactory emf;//www .j a va2 s.co m emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME); em = emf.createEntityManager(); try { em.getTransaction().begin(); System.out.println("Challenged by: " + user.getEmail()); System.out.println("Challenged friend: " + user.getFriendToAdd()); User friend = getUserByEmail(user.getFriendToAdd()); GameServerCommunicator gameComm = new GameServerCommunicator(); ArrayList<String> playerNames = new ArrayList<>(); playerNames.add(user.getEmail()); playerNames.add(user.getFriendToAdd()); int gameId = gameComm.requestNewGame(playerNames); if (gameId == -1) { //if something went wrong return -1; } //Send cloud message to friend JSONObject notificationObj = new JSONObject(); notificationObj.put("body", "CHALLENGE " + user.getEmail() + " " + GameInfo.getInstance().getIp() + " " + GameInfo.getInstance().getClientPort() + " " + gameId); notificationObj.put("title", "A Challenge"); JSONObject messageObj = new JSONObject(); messageObj.put("token", friend.getDeviceToken()); messageObj.put("notification", notificationObj); JSONObject mainObject = new JSONObject(); mainObject.put("message", messageObj); HttpPost url = getHttpURL(); url.setEntity(new StringEntity(mainObject.toString())); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(url); System.out.println("Response:"); HttpEntity entity = response.getEntity(); String responseString = EntityUtils.toString(entity, "UTF-8"); System.out.println(responseString); em.flush(); em.getTransaction().commit(); return gameId; } catch (Exception e) { System.out.println(e); return -1; } finally { if (em != null) { em.close(); } emf.close(); } }
From source file:com.sixsq.slipstream.run.RunNodeResource.java
private void deleteNodeInstancesInTransaction(Representation entity) throws Exception { EntityManager em = PersistenceUtil.createEntityManager(); EntityTransaction transaction = em.getTransaction(); Run run = Run.loadFromUuid(getUuid(), em); try {/* ww w .j a va 2 s . c om*/ Form form = new Form(entity); boolean deleteOnly = "true".equals(form.getFirstValue(DELETE_INSTANCE_IDS_ONLY_FORM_PARAM, "").trim()) ? true : false; if (!deleteOnly) { validateRun(run); } transaction.begin(); String ids = form.getFirstValue(INSTANCE_IDS_REMOVE_FORM_PARAM, ""); if (ids.isEmpty()) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Provide list of node instance IDs to be removed from the Run."); } else { String cloudServiceName = ""; try { cloudServiceName = run.getCloudServiceNameForNode(nodename); } catch (NullPointerException ex) { throwClientBadRequest("Invalid nodename: " + nodename); } List<String> instanceIds = Arrays.asList(ids.split("\\s*,\\s*")); for (String _id : instanceIds) { String instanceName = ""; try { instanceName = getNodeInstanceName(Integer.parseInt(_id)); } catch (NumberFormatException ex) { throwClientBadRequest("Invalid instance name: " + _id); } setRemovingNodeInstance(run, instanceName); run.removeNodeInstanceName(instanceName, cloudServiceName); } run.postEventScaleDown(nodename, instanceIds); // update instance ids removeNodeInstanceIndices(run, instanceIds); decrementNodeMultiplicityOnRun(instanceIds.size(), run); } if (!deleteOnly) { StateMachine.createStateMachine(run).tryAdvanceToProvisionning(); } transaction.commit(); } catch (Exception ex) { if (transaction.isActive()) { transaction.rollback(); } throw ex; } finally { em.close(); } getResponse().setStatus(Status.SUCCESS_NO_CONTENT); }
From source file:ec.edu.chyc.manejopersonal.controller.PersonaJpaController.java
public void create(Persona persona/*, Contratado contratado, Tesista tesista, Pasante pasante*/) throws Exception { EntityManager em = null; try {/*from ww w. ja va 2s . co m*/ em = getEntityManager(); em.getTransaction().begin(); em.persist(persona); /* if (contratado != null) { contratado.setId(persona.getId()); em.persist(contratado); } if (tesista != null) { tesista.setId(persona.getId()); em.persist(tesista); } if (pasante != null) { pasante.setId(persona.getId()); em.persist(pasante); } */ for (PersonaTitulo personaTitulo : persona.getPersonaTitulosCollection()) { personaTitulo.setPersona(persona); Titulo titulo = personaTitulo.getTitulo(); if (titulo.getId() == null || titulo.getId() < 0) { titulo.setId(null); em.persist(titulo); } if (personaTitulo.getUniversidad().getId() == null || personaTitulo.getUniversidad().getId() < 0) { personaTitulo.getUniversidad().setId(null); em.persist(personaTitulo.getUniversidad()); } if (personaTitulo.getId() == null || personaTitulo.getId() < 0) { personaTitulo.setId(null); em.persist(personaTitulo); } } /*for (PersonaFirma personaFirma : persona.getPersonaFirmasCollection()) { personaFirma.setPersona(persona); Firma firma = personaFirma.getFirma(); if (firma.getId() == null || firma.getId() < 0) { firma.setId(null); em.persist(firma); } if (personaFirma.getId() == null || personaFirma.getId() < 0) { personaFirma.setId(null); em.persist(personaFirma); } }*/ guardarPersonaFirma(em, persona); em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } }