List of usage examples for javax.persistence EntityManager find
public <T> T find(Class<T> entityClass, Object primaryKey);
From source file:org.noorganization.instalist.server.api.EntryResource.java
/** * Returns a single list-entry./*from w w w .ja va2 s . co m*/ * @param _groupId The id of the group containing the entry. * @param _entryUUID The uuid of the entry itself. */ @GET @TokenSecured @Path("{entryuuid}") @Produces({ "application/json" }) public Response getEntry(@PathParam("groupid") int _groupId, @PathParam("entryuuid") String _entryUUID) throws Exception { UUID toFind; try { toFind = UUID.fromString(_entryUUID); } catch (IllegalArgumentException _e) { return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID); } EntityManager manager = DatabaseHelper.getInstance().getManager(); DeviceGroup group = manager.find(DeviceGroup.class, _groupId); IEntryController entryController = ControllerFactory.getEntryController(manager); ListEntry foundEntry = entryController.findByGroupAndUUID(group, toFind); if (foundEntry == null) { if (entryController.findDeletedByGroupAndUUID(group, toFind) != null) { manager.close(); return ResponseFactory .generateGone(new Error().withMessage("The requested " + "listentry has been deleted.")); } manager.close(); return ResponseFactory .generateNotFound(new Error().withMessage("The requested " + "listentry was not found.")); } manager.close(); EntryInfo rtn = new EntryInfo().withDeleted(false); rtn.setUUID(foundEntry.getUUID()); rtn.setProductUUID(foundEntry.getProduct().getUUID()); rtn.setListUUID(foundEntry.getList().getUUID()); rtn.setAmount(foundEntry.getAmount()); rtn.setPriority(foundEntry.getPriority()); rtn.setStruck(foundEntry.getStruck()); rtn.setLastChanged(Date.from(foundEntry.getUpdated())); return ResponseFactory.generateOK(rtn); }
From source file:org.noorganization.instalist.server.api.ProductResource.java
/** * Finds a single product./*from ww w .j a v a 2 s . c o m*/ * @param _groupId The id of the group containing the searched product. * @param _productUUID The uuid of the needed product. */ @GET @TokenSecured @Path("{productuuid}") @Produces({ "application/json" }) public Response getProduct(@PathParam("groupid") int _groupId, @PathParam("productuuid") String _productUUID) throws Exception { UUID toFind; try { toFind = UUID.fromString(_productUUID); } catch (IllegalArgumentException _e) { return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID); } EntityManager manager = DatabaseHelper.getInstance().getManager(); DeviceGroup group = manager.find(DeviceGroup.class, _groupId); IProductController productController = ControllerFactory.getProductController(manager); Product foundProduct = productController.findByGroupAndUUID(group, toFind); if (foundProduct == null) { if (productController.findDeletedByGroupAndUUID(group, toFind) != null) { manager.close(); return ResponseFactory .generateGone(new Error().withMessage("The requested " + "product has been deleted.")); } manager.close(); return ResponseFactory .generateNotFound(new Error().withMessage("The requested " + "product was not found.")); } manager.close(); ProductInfo rtn = new ProductInfo().withDeleted(false); rtn.setUUID(toFind); rtn.setName(foundProduct.getName()); rtn.setDefaultAmount(foundProduct.getDefaultAmount()); rtn.setStepAmount(foundProduct.getStepAmount()); if (foundProduct.getUnit() != null) rtn.setUnitUUID(foundProduct.getUnit().getUUID()); rtn.setLastChanged(Date.from(foundProduct.getUpdated())); return ResponseFactory.generateOK(rtn); }
From source file:com.gigglinggnus.controllers.ModifyAppointmentController.java
/** * * @param request servlet request/*from w w w . j ava2 s .c om*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { EntityManager em = (EntityManager) request.getSession().getAttribute("em"); Clock clk = (Clock) (request.getSession().getAttribute("clock")); boolean modified = false; String userId = request.getParameter("userid"); User user = em.find(User.class, userId); String examId = request.getParameter("examid"); Exam exam = em.find(Exam.class, examId); Appointment appt = user.getAppointmentByExam(exam); String startTime = request.getParameter("startTime"); String seatZone = request.getParameter("seatingZone"); String seatNum = request.getParameter("seatNum"); String cancel = request.getParameter("cancel"); try { em.getTransaction().begin(); if (startTime != "") { appt.changeStartTime(Instant.parse(startTime), clk); em.persist(appt); modified = true; } if (seatZone != "") { appt.setSeatingZone(Seating.parse(seatZone)); em.persist(appt); modified = true; } if (seatNum != "") { appt.setSeatNum(Integer.parseInt(seatNum)); em.persist(appt); modified = true; } em.getTransaction().commit(); } catch (Exception e) { em.getTransaction().rollback(); request.setAttribute("msg", e); RequestDispatcher rd = request.getRequestDispatcher("/home.jsp"); rd.forward(request, response); } if (cancel != null) { request.setAttribute("msg", "Appointment cancelled"); RequestDispatcher rd = request.getRequestDispatcher("/home.jsp"); rd.forward(request, response); } if (modified == true) { request.setAttribute("msg", "Appointment modified"); RequestDispatcher rd = request.getRequestDispatcher("/home.jsp"); rd.forward(request, response); } else { request.setAttribute("msg", "Appointment unchanged"); RequestDispatcher rd = request.getRequestDispatcher("/home.jsp"); rd.forward(request, response); } }
From source file:kirchnerei.note.model.DataService.java
public boolean removeNote(Long id) { if (NumberUtils.isEmpty(id)) { return false; }//w w w. j a va 2 s . c o m EntityManager em = null; EntityTransaction tx = null; try { em = entityService.get(); tx = em.getTransaction(); tx.begin(); Note note = em.find(Note.class, id); if (note == null) { return false; } Category category = note.getCategory(); category.getNotes().remove(note); note.setCategory(null); em.remove(note); if (category.getNotes().isEmpty()) { LogUtils.debug(log, "empty category '%s', then remove it", category.getTitle()); em.remove(category); } EntityService.commit(tx); return true; } catch (Exception e) { EntityService.rollback(tx); return false; } finally { EntityService.close(em); } }
From source file:edu.vt.middleware.gator.JpaConfigManager.java
/** {@inheritDoc}. */ @Transactional(readOnly = true, propagation = Propagation.REQUIRED) public <T extends Config> T find(final Class<T> type, final int id) { final EntityManager em = getEntityManager(); logger.trace(String.format("Querying for %s ID=%s", type.getSimpleName(), id)); return em.find(type, id); }
From source file:org.broadleafcommerce.common.web.BroadleafRequestContext.java
/** * Resurrect the BroadleafRequestContext state based on a JSON representation. * * @param Json/*from ww w . ja v a 2s .co m*/ * @param em * @return */ public static BroadleafRequestContext createLightWeightCloneFromJson(String Json, EntityManager em) { BroadleafRequestContext context = new BroadleafRequestContext(); JsonFactory factory = new JsonFactory(); ObjectMapper mapper = new ObjectMapper(factory); TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String, String>>() { }; HashMap<String, String> json; try { json = mapper.readValue(Json, typeRef); } catch (IOException e) { throw ExceptionHelper.refineException(e); } if (!json.get("ignoreSite").equals("null")) { context.setIgnoreSite(Boolean.valueOf(json.get("ignoreSite"))); } if (!json.get("sandBox").equals("null")) { context.setSandBox(em.find(SandBoxImpl.class, Long.parseLong(json.get("sandBox")))); } if (!json.get("nonPersistentSite").equals("null")) { context.setNonPersistentSite(em.find(SiteImpl.class, Long.parseLong(json.get("nonPersistentSite")))); } if (!json.get("enforceEnterpriseCollectionBehaviorState").equals("null")) { context.setEnforceEnterpriseCollectionBehaviorState(EnforceEnterpriseCollectionBehaviorState .valueOf(json.get("enforceEnterpriseCollectionBehaviorState"))); } if (!json.get("admin").equals("null")) { context.setAdmin(Boolean.valueOf(json.get("admin"))); } if (!json.get("adminUserId").equals("null")) { context.setAdminUserId(Long.parseLong(json.get("ignoreSite"))); } if (!json.get("broadleafCurrency").equals("null")) { context.setBroadleafCurrency(em.find(BroadleafCurrencyImpl.class, json.get("broadleafCurrency"))); } if (!json.get("currentCatalog").equals("null")) { context.setCurrentCatalog(em.find(CatalogImpl.class, Long.parseLong(json.get("currentCatalog")))); } if (!json.get("currentProfile").equals("null")) { context.setCurrentProfile(em.find(SiteImpl.class, Long.parseLong(json.get("currentProfile")))); } if (!json.get("deployBehavior").equals("null")) { context.setDeployBehavior(DeployBehavior.valueOf(json.get("deployBehavior"))); } if (!json.get("deployState").equals("null")) { context.setDeployState(DeployState.valueOf(json.get("deployState"))); } if (!json.get("internalIgnoreFilters").equals("null")) { context.setInternalIgnoreFilters(Boolean.valueOf(json.get("internalIgnoreFilters"))); } if (!json.get("locale").equals("null")) { context.setLocale(em.find(LocaleImpl.class, json.get("locale"))); } if (!json.get("validateProductionChangesState").equals("null")) { context.setValidateProductionChangesState( ValidateProductionChangesState.valueOf(json.get("validateProductionChangesState"))); } if (!json.get("timeZone").equals("null")) { context.setTimeZone(TimeZone.getTimeZone(json.get("timeZone"))); } return context; }
From source file:fr.amapj.service.services.saisiepermanence.PermanenceService.java
/** * Permet de charger le planning des distributions pour un utilisateur final *///from w w w. j av a 2s . c o m @DbRead public MesPermanencesDTO getMesDistributions(Date d) { EntityManager em = TransactionHelper.getEm(); MesPermanencesDTO res = new MesPermanencesDTO(); Utilisateur user = em.find(Utilisateur.class, SessionManager.getUserId()); res.dateDebut = fr.amapj.common.DateUtils.firstMonday(d); res.dateFin = DateUtils.addDays(res.dateDebut, 6); // On rcupre ensuite la liste de toutes les distributions dans cet intervalle res.permanencesSemaine = getAllDistributions(em, res.dateDebut, res.dateFin); // On rcupre la liste des distributions de cet utilisateur dans le futur res.permanencesFutures = getDistributionsFutures(em, user); return res; }
From source file:org.noorganization.instalist.server.api.CategoriesResource.java
/** * Get a list of categories.//w ww.j av a 2s . co m * * @param _groupId The id of the group. * @param _categoryUUID The uuid of the category to fetch. */ @GET @TokenSecured @Path("{categoryuuid}") @Produces({ "application/json" }) public Response getCategory(@PathParam("groupid") int _groupId, @PathParam("categoryuuid") String _categoryUUID) throws Exception { UUID categoryUUID; try { categoryUUID = UUID.fromString(_categoryUUID); } catch (IllegalArgumentException e) { return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID); } EntityManager manager = DatabaseHelper.getInstance().getManager(); DeviceGroup group = manager.find(DeviceGroup.class, _groupId); TypedQuery<Category> categoriesQuery = manager.createQuery( "select c from Category c " + "where c.group = :groupid and c.UUID = :uuid", Category.class); categoriesQuery.setParameter("groupid", group); categoriesQuery.setParameter("uuid", categoryUUID); List<Category> categories = categoriesQuery.getResultList(); if (categories.size() != 1) { TypedQuery<DeletedObject> deletedCategoriesQuery = manager .createQuery("select do " + "from DeletedObject do where do.group = :groupid and " + "do.type = :type and do.UUID = :uuid", DeletedObject.class); deletedCategoriesQuery.setParameter("groupid", group); deletedCategoriesQuery.setParameter("type", DeletedObject.Type.CATEGORY); deletedCategoriesQuery.setParameter("uuid", categoryUUID); List<DeletedObject> deletedCategories = deletedCategoriesQuery.getResultList(); manager.close(); if (deletedCategories.size() == 1) { CategoryInfo catInfo = new CategoryInfo(); catInfo.setDeleted(true); catInfo.setLastChanged(Date.from(deletedCategories.get(0).getUpdated())); catInfo.setUUID(categoryUUID); return ResponseFactory.generateGone(catInfo); } else { return ResponseFactory.generateNotFound(new Error().withMessage("Category was not" + " found.")); } } manager.close(); CategoryInfo catInfo = new CategoryInfo(); catInfo.setDeleted(false); catInfo.setLastChanged(Date.from(categories.get(0).getUpdated())); catInfo.setName(categories.get(0).getName()); catInfo.setUUID(categoryUUID); return ResponseFactory.generateOK(catInfo); }
From source file:org.noorganization.instalist.server.api.IngredientResource.java
/** * Get a list of ingredients.// w w w.j a v a 2 s . c om * @param _groupId The id of the group containing various ingredients. * @param _changedSince Limits the result 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 getIngredients(@PathParam("groupid") int _groupId, @QueryParam("changedsince") String _changedSince) throws Exception { List<Ingredient> ingedients; List<DeletedObject> deletedIngredients; EntityManager manager = DatabaseHelper.getInstance().getManager(); DeviceGroup group = manager.find(DeviceGroup.class, _groupId); if (_changedSince != null) { Instant changedSince; try { changedSince = ISO8601Utils.parse(_changedSince, new ParsePosition(0)).toInstant(); } catch (ParseException _e) { manager.close(); return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE); } TypedQuery<Ingredient> IngredientsQuery = manager.createQuery( "select i from " + "Ingredient i where i.group = :group and i.updated > :updated", Ingredient.class); IngredientsQuery.setParameter("group", group); IngredientsQuery.setParameter("updated", changedSince); ingedients = IngredientsQuery.getResultList(); TypedQuery<DeletedObject> deletedIngredientsQuery = manager.createQuery( "select do " + "from DeletedObject do where do.group = :group and do.updated > :updated and " + "do.type = :type", DeletedObject.class); deletedIngredientsQuery.setParameter("group", group); deletedIngredientsQuery.setParameter("updated", changedSince); deletedIngredientsQuery.setParameter("type", DeletedObject.Type.INGREDIENT); deletedIngredients = deletedIngredientsQuery.getResultList(); } else { ingedients = new ArrayList<Ingredient>(group.getIngredients()); TypedQuery<DeletedObject> deletedIngredientsQuery = manager.createQuery( "select do from " + "DeletedObject do where do.group = :group and do.type = :type", DeletedObject.class); deletedIngredientsQuery.setParameter("group", group); deletedIngredientsQuery.setParameter("type", DeletedObject.Type.INGREDIENT); deletedIngredients = deletedIngredientsQuery.getResultList(); } manager.close(); ArrayList<IngredientInfo> rtn = new ArrayList<IngredientInfo>( ingedients.size() + deletedIngredients.size()); for (Ingredient current : ingedients) { IngredientInfo toAdd = new IngredientInfo().withDeleted(false); toAdd.setUUID(current.getUUID()); toAdd.setProductUUID(current.getProduct().getUUID()); toAdd.setRecipeUUID(current.getRecipe().getUUID()); toAdd.setAmount(current.getAmount()); toAdd.setLastChanged(Date.from(current.getUpdated())); rtn.add(toAdd); } for (DeletedObject current : deletedIngredients) { IngredientInfo toAdd = new IngredientInfo(); toAdd.setUUID(current.getUUID()); toAdd.setLastChanged(Date.from(current.getUpdated())); toAdd.setDeleted(true); rtn.add(toAdd); } return ResponseFactory.generateOK(rtn); }
From source file:org.noorganization.instalist.server.api.TaggedProductResource.java
/** * Get a list of tagged products.//from w ww. jav a2 s . c o m * @param _groupId The id of the group containing various tagged products. * @param _changedSince Limits the result 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 getTaggedProducts(@PathParam("groupid") int _groupId, @QueryParam("changedsince") String _changedSince) throws Exception { List<TaggedProduct> taggedProducts; List<DeletedObject> deletedTaggedProducts; EntityManager manager = DatabaseHelper.getInstance().getManager(); DeviceGroup group = manager.find(DeviceGroup.class, _groupId); if (_changedSince != null) { Instant changedSince; try { changedSince = ISO8601Utils.parse(_changedSince, new ParsePosition(0)).toInstant(); } catch (ParseException _e) { manager.close(); return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE); } TypedQuery<TaggedProduct> taggedProductQuery = manager.createQuery( "select tp from " + "TaggedProduct tp where tp.group = :group and tp.updated > :updated", TaggedProduct.class); taggedProductQuery.setParameter("group", group); taggedProductQuery.setParameter("updated", changedSince); taggedProducts = taggedProductQuery.getResultList(); TypedQuery<DeletedObject> deletedTaggedProductQuery = manager.createQuery( "select do " + "from DeletedObject do where do.group = :group and do.updated > :updated and " + "do.type = :type", DeletedObject.class); deletedTaggedProductQuery.setParameter("group", group); deletedTaggedProductQuery.setParameter("updated", changedSince); deletedTaggedProductQuery.setParameter("type", DeletedObject.Type.TAGGEDPRODUCT); deletedTaggedProducts = deletedTaggedProductQuery.getResultList(); } else { taggedProducts = new ArrayList<TaggedProduct>(group.getTaggedProducts()); TypedQuery<DeletedObject> deletedIngredientsQuery = manager.createQuery( "select do " + "from DeletedObject do where do.group = :group and do.type = :type", DeletedObject.class); deletedIngredientsQuery.setParameter("group", group); deletedIngredientsQuery.setParameter("type", DeletedObject.Type.TAGGEDPRODUCT); deletedTaggedProducts = deletedIngredientsQuery.getResultList(); } manager.close(); ArrayList<TaggedProductInfo> rtn = new ArrayList<TaggedProductInfo>( taggedProducts.size() + deletedTaggedProducts.size()); for (TaggedProduct current : taggedProducts) { TaggedProductInfo toAdd = new TaggedProductInfo().withDeleted(false); toAdd.setUUID(current.getUUID()); toAdd.setProductUUID(current.getProduct().getUUID()); toAdd.setTagUUID(current.getTag().getUUID()); toAdd.setLastChanged(Date.from(current.getUpdated())); rtn.add(toAdd); } for (DeletedObject current : deletedTaggedProducts) { TaggedProductInfo toAdd = new TaggedProductInfo(); toAdd.setUUID(current.getUUID()); toAdd.setLastChanged(Date.from(current.getUpdated())); toAdd.setDeleted(true); rtn.add(toAdd); } return ResponseFactory.generateOK(rtn); }