List of usage examples for javax.persistence EntityManager close
public void close();
From source file:org.noorganization.instalist.server.api.TagResource.java
/** * Updates the tag./*from w ww .java2 s. c o m*/ * @param _groupId The id of the group containing the tag to change. * @param _tagUUID The uuid of the tag identifying it in the group. * @param _entity Data to change. */ @PUT @TokenSecured @Path("{taguuid}") @Consumes("application/json") @Produces({ "application/json" }) public Response putTag(@PathParam("groupid") int _groupId, @PathParam("taguuid") String _tagUUID, TagInfo _entity) throws Exception { if ((_entity.getUUID() != null && !_entity.getUUID().equals(_tagUUID)) || (_entity.getName() != null && _entity.getName().length() == 0) || (_entity.getDeleted() != null && _entity.getDeleted())) return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA); UUID toUpdate; try { toUpdate = UUID.fromString(_tagUUID); } catch (IllegalArgumentException _e) { return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID); } Instant updated; if (_entity.getLastChanged() != null) { updated = _entity.getLastChanged().toInstant(); if (Instant.now().isBefore(updated)) return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE); } else updated = Instant.now(); EntityManager manager = DatabaseHelper.getInstance().getManager(); ITagController tagController = ControllerFactory.getTagController(manager); try { tagController.update(_groupId, toUpdate, _entity.getName(), updated); } catch (NotFoundException _e) { return ResponseFactory.generateNotFound(new Error().withMessage("The tag was not " + "found.")); } catch (GoneException _e) { return ResponseFactory.generateGone(new Error().withMessage("The tag has been " + "deleted.")); } catch (ConflictException _e) { return ResponseFactory .generateConflict(new Error().withMessage("The sent data would " + "conflict with saved tag.")); } finally { manager.close(); } return ResponseFactory.generateOK(null); }
From source file:cz.fi.muni.pa165.dto.PrintedBookDAOTest.java
@Test public void testInsert() { EntityManager em = emf.createEntityManager(); PrintedBookDAOImpl bdao = new PrintedBookDAOImpl(); bdao.setManager(em);/*from w w w . j ava2 s. co m*/ em.getTransaction().begin(); Book book = new Book(); book.setName("Harry Potter"); book.setISBN("123112315"); book.setDescription("Book about Wizard!"); book.setAuthors("J.K. Rowling"); book.setDepartment(Department.Sport); book.setIdBook(1); PrintedBook pbook = new PrintedBook(); pbook.setBook(book); pbook.setState(Boolean.FALSE); pbook.setCondition(Condition.Damaged); bdao.insert(pbook); em.getTransaction().commit(); List<PrintedBook> books = em.createQuery("SELECT b FROM PrintedBook b", PrintedBook.class).getResultList(); em.close(); assertEquals(books.size(), 3); }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.test.NewsITCase.java
/** * Before test.// w w w. j a va2 s . c o m * * @throws Exception the exception */ @Before public void beforeTest() throws Exception { EntityManager em = emf.createEntityManager(); try { Query query = em.createQuery(new StringBuilder().append("SELECT x FROM news x").toString()); List<News> newsList = query.getResultList(); for (News news : newsList) { em.remove(news); } query = em.createQuery(new StringBuilder().append("SELECT x FROM category x").toString()); List<NewsCategory> catList = query.getResultList(); for (NewsCategory temp : catList) { em.remove(temp); } query = em.createQuery(new StringBuilder().append("SELECT x FROM metaCategory x").toString()); List<NewsMetaCategory> metaList = query.getResultList(); for (NewsMetaCategory temp : metaList) { em.remove(temp); } } finally { em.close(); } }
From source file:org.noorganization.instalist.server.api.ProductResource.java
/** * Creates a product.//from ww w. j av a2 s . c om * @param _groupId The id of the group that should contain the new product. * @param _entity Data for creating the group. */ @POST @TokenSecured @Consumes("application/json") @Produces({ "application/json" }) public Response postProduct(@PathParam("groupid") int _groupId, ProductInfo _entity) throws Exception { if (_entity.getUUID() == null || (_entity.getName() != null && _entity.getName().length() == 0) || (_entity.getDeleted() != null && _entity.getDeleted()) || (_entity.getDefaultAmount() != null && _entity.getDefaultAmount() < 0.001f) || (_entity.getStepAmount() != null && _entity.getStepAmount() < 0.001f)) return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA); UUID toCreate; UUID unitUUID = null; boolean removeUnit = (_entity.getRemoveUnit() != null ? _entity.getRemoveUnit() : false); try { toCreate = UUID.fromString(_entity.getUUID()); if (_entity.getUnitUUID() != null && !removeUnit) unitUUID = UUID.fromString(_entity.getUnitUUID()); } catch (IllegalArgumentException _e) { return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID); } Instant created; if (_entity.getLastChanged() != null) { created = _entity.getLastChanged().toInstant(); if (Instant.now().isBefore(created)) return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE); } else created = Instant.now(); float defaultAmount = (_entity.getDefaultAmount() != null ? _entity.getDefaultAmount() : 1f); float stepAmount = (_entity.getStepAmount() != null ? _entity.getStepAmount() : 1f); EntityManager manager = DatabaseHelper.getInstance().getManager(); IProductController productController = ControllerFactory.getProductController(manager); try { productController.add(_groupId, toCreate, _entity.getName(), defaultAmount, stepAmount, unitUUID, created); } catch (ConflictException _e) { return ResponseFactory.generateConflict( new Error().withMessage("The sent data would " + "conflict with saved product.")); } catch (BadRequestException _e) { return ResponseFactory .generateBadRequest(new Error().withMessage("The referenced " + "unit was not found.")); } finally { manager.close(); } return ResponseFactory.generateCreated(null); }
From source file:com.sixsq.slipstream.persistence.Run.java
public static List<RunView> viewList(User user, String moduleResourceUri, Integer offset, Integer limit, String cloudServiceName) throws ConfigurationException, ValidationException { List<RunView> views = null; EntityManager em = PersistenceUtil.createEntityManager(); try {// www . j a v a2s . c o m CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Run> critQuery = builder.createQuery(Run.class); Root<Run> rootQuery = critQuery.from(Run.class); critQuery.select(rootQuery); Predicate where = viewListCommonQueryOptions(builder, rootQuery, user, moduleResourceUri, cloudServiceName); if (where != null) { critQuery.where(where); } critQuery.orderBy(builder.desc(rootQuery.get("startTime"))); TypedQuery<Run> query = em.createQuery(critQuery); if (offset != null) { query.setFirstResult(offset); } query.setMaxResults((limit != null) ? limit : DEFAULT_LIMIT); List<Run> runs = query.getResultList(); views = convertRunsToRunViews(runs); } finally { em.close(); } return views; }
From source file:org.opencastproject.userdirectory.jpa.JpaUserAndRoleProvider.java
public User loadUser(String userName, String organizationId) { EntityManager em = null; try {//from ww w . j a v a 2 s . c o m em = emf.createEntityManager(); Query q = em.createNamedQuery("user"); q.setParameter("u", userName); q.setParameter("o", organizationId); JpaUser user = null; try { user = (JpaUser) q.getSingleResult(); } catch (NoResultException e) { return null; } Set<String> roles = user.getRoles(); return new User(userName, user.getPassword(), user.getOrganization(), roles.toArray(new String[roles.size()])); } finally { if (em != null) em.close(); } }
From source file:org.noorganization.instalist.server.api.CategoriesResource.java
/** * Deletes the category./* w w w . j av a 2 s. c o m*/ * * @param _groupId The group of the category to delete. * @param _uuid The uuid of the category to delete. */ @DELETE @TokenSecured @Path("{categoryuuid}") @Produces({ "application/json" }) public Response deleteCategory(@PathParam("groupid") int _groupId, @PathParam("categoryuuid") String _uuid) throws Exception { UUID newCatUUID; try { newCatUUID = UUID.fromString(_uuid); } catch (IllegalArgumentException e) { return ResponseFactory.generateNotFound(CommonEntity.INVALID_UUID); } EntityManager manager = DatabaseHelper.getInstance().getManager(); ICategoryController categoryController = ControllerFactory.getCategoryController(manager); try { categoryController.delete(_groupId, newCatUUID); } catch (GoneException _e) { return ResponseFactory.generateGone(new Error().withMessage("The category " + "was already deleted")); } catch (NotFoundException _e) { return ResponseFactory.generateNotFound(new Error().withMessage("The category " + "was not found.")); } catch (ConflictException _e) { return ResponseFactory .generateConflict(new Error().withMessage("The category still " + "contains lists.")); } finally { manager.close(); } return ResponseFactory.generateOK(null); }
From source file:com.epam.training.taranovski.web.project.repository.implementation.OfferBidRepositoryImplementation.java
@Override public OfferBid getBidByEmployeeAndVacancy(Employee employee, Vacancy vacancy) { EntityManager em = entityManagerFactory.createEntityManager(); OfferBid offer = null;/*w ww . jav a2 s. c o m*/ try { em.getTransaction().begin(); TypedQuery<OfferBid> query = em.createNamedQuery("OfferBid.findBidByEmployeeAndVacancy", OfferBid.class); query.setParameter("employee", employee); query.setParameter("vacancy", vacancy); offer = query.getSingleResult(); em.getTransaction().commit(); } catch (RuntimeException e) { Logger.getLogger(OfferBidRepositoryImplementation.class.getName()).info(e); offer = null; } finally { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } return offer; }
From source file:com.epam.training.taranovski.web.project.repository.implementation.OfferBidRepositoryImplementation.java
@Override public OfferBid getOfferByEmployeeAndVacancy(Employee employee, Vacancy vacancy) { EntityManager em = entityManagerFactory.createEntityManager(); OfferBid offer = null;/* w w w . java2 s. co m*/ try { em.getTransaction().begin(); TypedQuery<OfferBid> query = em.createNamedQuery("OfferBid.findOfferByEmployeeAndVacancy", OfferBid.class); query.setParameter("employee", employee); query.setParameter("vacancy", vacancy); offer = query.getSingleResult(); em.getTransaction().commit(); } catch (RuntimeException e) { Logger.getLogger(OfferBidRepositoryImplementation.class.getName()).info(e); offer = null; } finally { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } return offer; }
From source file:org.noorganization.instalist.server.api.RecipeResource.java
/** * Updates the recipe.//from w ww .jav a2s . c om * @param _groupId The id of the group containing the recipe to change. * @param _recipeUUID The uuid of the recipe identifying it in the group. * @param _entity Data to change. */ @PUT @TokenSecured @Path("{recipeuuid}") @Consumes("application/json") @Produces({ "application/json" }) public Response putRecipe(@PathParam("groupid") int _groupId, @PathParam("recipeuuid") String _recipeUUID, RecipeInfo _entity) throws Exception { if ((_entity.getUUID() != null && !_entity.getUUID().equals(_recipeUUID)) || (_entity.getName() != null && _entity.getName().length() == 0) || (_entity.getDeleted() != null && _entity.getDeleted())) return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA); UUID toUpdate; try { toUpdate = UUID.fromString(_recipeUUID); } catch (IllegalArgumentException _e) { return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID); } Instant updated; if (_entity.getLastChanged() != null) { updated = _entity.getLastChanged().toInstant(); if (Instant.now().isBefore(updated)) return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE); } else updated = Instant.now(); EntityManager manager = DatabaseHelper.getInstance().getManager(); IRecipeController recipeController = ControllerFactory.getRecipeController(manager); try { recipeController.update(_groupId, toUpdate, _entity.getName(), updated); } catch (NotFoundException _e) { return ResponseFactory.generateNotFound(new Error().withMessage("The recipe was not " + "found.")); } catch (GoneException _e) { return ResponseFactory.generateGone(new Error().withMessage("The recipe has been " + "deleted.")); } catch (ConflictException _e) { return ResponseFactory.generateConflict( new Error().withMessage("The sent data would " + "conflict with saved recipe.")); } finally { manager.close(); } return ResponseFactory.generateOK(null); }