List of usage examples for javax.persistence EntityManagerFactory createEntityManager
public EntityManager createEntityManager();
EntityManager
. From source file:BO.UserHandler.java
public boolean login(VUser u) { EntityManager em;/*from www. j ava 2 s .c om*/ EntityManagerFactory emf; emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME); em = emf.createEntityManager(); try { Query q = em.createQuery("SELECT u FROM User u WHERE u.email LIKE :email"); q.setParameter("email", u.getEmail()); q.setMaxResults(1); q.getSingleResult(); return true; } catch (NoResultException e) { em.getTransaction().begin(); User userToInsert = new User(u.getEmail()); em.persist(userToInsert); em.flush(); em.getTransaction().commit(); return true; } finally { if (em != null) { em.close(); } emf.close(); } }
From source file:BO.UserHandler.java
public List<VUser> getPendingFriends(VUser user) { EntityManager em;/* w ww .ja v a 2 s. co m*/ EntityManagerFactory emf; 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 " + "AND f.didRespond LIKE :didrespond") .setParameter("email", user.getEmail()).setParameter("didrespond", false).getResultList(); List<VUser> senders = new ArrayList<>(); for (Friendship f : list) { senders.add(new VUser(f.getSendingFriend().getEmail(), "", "", "", false)); } return senders; } catch (Exception e) { return null; } finally { if (em != null) { em.close(); } emf.close(); } }
From source file:BO.UserHandler.java
public boolean respondFriendRequest(VUser user) { EntityManager em;/*from w w w .ja va 2 s .c om*/ EntityManagerFactory emf; emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME); em = emf.createEntityManager(); try { em.getTransaction().begin(); System.out.println("Receiving friend: " + user.getEmail()); System.out.println("Sending friend: " + user.getFriendToAdd()); Friendship f = (Friendship) em .createQuery("SELECT f from Friendship f WHERE f.receivingFriend.email LIKE :email1 " + "AND f.sendingFriend.email LIKE :email2") .setParameter("email1", user.getEmail()).setParameter("email2", user.getFriendToAdd()) .getSingleResult(); f.setDidRespond(true); f.setDidAccept(user.isDidAccept()); em.persist(f); em.flush(); em.getTransaction().commit(); return true; } catch (Exception e) { System.out.println(e); return false; } finally { if (em != null) { em.close(); } emf.close(); } }
From source file:BO.UserHandler.java
public List<VUser> getFriends(VUser user) { EntityManager em;//from w w w .j av a 2s . c o m EntityManagerFactory emf; 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:org.mule.module.jpa.JPAUtils.java
/** * Fetches an EntityManager in a transaction-aware manner. *///from ww w . ja v a 2 s .c om @SuppressWarnings({ "unchecked" }) static public <T> T getTransactionalResource(EntityManagerFactory entityManagerFactory) { Transaction currentTx = TransactionCoordination.getInstance().getTransaction(); if (currentTx != null) { if (logger.isDebugEnabled()) { logger.debug("Transaction in scope: " + currentTx); } if (currentTx.hasResource(entityManagerFactory)) { if (logger.isDebugEnabled()) { logger.debug("Transaction already bound to " + entityManagerFactory); } return (T) currentTx.getResource(entityManagerFactory); } else { Object connectionResource = entityManagerFactory.createEntityManager(); try { if (currentTx.supports(entityManagerFactory, connectionResource)) { if (logger.isDebugEnabled()) { logger.debug("Binding new entityManager " + connectionResource + " to transaction " + currentTx); } currentTx.bindResource(entityManagerFactory, connectionResource); } else { throw new TransactionException(CoreMessages.createStaticMessage( "Endpoint is transactional but transaction does not support it")); } } catch (MuleException ex) { throw new JPAException(ex); } return (T) connectionResource; } } else { EntityManager entityManager = entityManagerFactory.createEntityManager(); if (logger.isDebugEnabled()) { logger.debug("Returning non-transactional entityManager " + entityManager); } return (T) entityManager; } }
From source file:BO.UserHandler.java
public boolean addFriend(VUser u) { EntityManager em;/*w w w .j a v a 2 s .c o m*/ EntityManagerFactory emf; 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:BO.UserHandler.java
public int sendChallengeRequest(VUser user) { EntityManager em;/*from w w w . j a va2 s .c om*/ EntityManagerFactory emf; 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:servlet.MatrialRequest.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/* w w w . j a v a 2 s.com*/ * @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 { // processRequest(request, response); boolean isMultipart = ServletFileUpload.isMultipartContent(request); MaterialRequest materialRequest = new MaterialRequest(); if (!isMultipart) { } else { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); MatrialRequest matrialRequest = new MatrialRequest(); List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { switch (item.getFieldName()) { case "typeId": materialRequest.setMrId(Integer.valueOf(getStringFromInputStream(item.getInputStream()))); break; case "typeDate": SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy"); String d = getStringFromInputStream(item.getInputStream()); { try { materialRequest.setMrDate(formatter.parse(d)); } catch (ParseException ex) { Logger.getLogger(MatrialRequest.class.getName()).log(Level.SEVERE, null, ex); } } break; case "typeDesc": materialRequest.setMaterialTypeId( Integer.valueOf(getStringFromInputStream(item.getInputStream()))); break; case "itemProjCode": materialRequest.setProjectItemCode(getStringFromInputStream(item.getInputStream())); break; case "itemDesc": materialRequest .setItemDescId(Integer.valueOf(getStringFromInputStream(item.getInputStream()))); break; case "itemQty": materialRequest .setMrQuantity(Integer.valueOf(getStringFromInputStream(item.getInputStream()))); break; case "typeunit": materialRequest.setUnitId(Integer.valueOf(getStringFromInputStream(item.getInputStream()))); break; case "typeRemarks": materialRequest.setRemark(getStringFromInputStream(item.getInputStream())); break; case "endRow": //Will save MR type; try { EntityManagerFactory emf = Persistence.createEntityManagerFactory(cons.entityName); EntityManager em = emf.createEntityManager(); MaterialRequestJpaController controller = new MaterialRequestJpaController(emf); controller.create(materialRequest); em.getTransaction().commit(); materialRequest = new MaterialRequest(); } catch (Exception e) { e.printStackTrace(); } break; } } else { try { String itemName = item.getName(); File savedFile = new File(FILES_DIRECTORY + itemName); item.write(savedFile); System.out.println("Your file has been saved at the loaction: " + getServletContext().getRealPath("/") + "uploadedFiles" + "\\" + itemName); materialRequest.setAttachFile(itemName); } catch (Exception e) { e.printStackTrace(); } } } response.sendRedirect("/insider360_dev/cNewMR.jsp"); // Before save, make sure there is attched file } }
From source file:servlet.MatrialRequest.java
/** * Handles the HTTP <code>GET</code> method. * * @param request servlet request// w ww.j a va 2 s.co m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String requestType = request.getParameter("requestType"); EntityManagerFactory emf = null; Gson gson = new Gson(); emf = Persistence.createEntityManagerFactory(cons.entityName); EntityManager em = emf.createEntityManager(); if (requestType.equalsIgnoreCase("load")) { MaterialRequestJpaController controller = new MaterialRequestJpaController(emf); MaterialTypeJpaController materialTypeJpaController = new MaterialTypeJpaController(emf); response.setContentType("application/json"); em.getTransaction().begin(); int nextId = controller.getNextId(); List<MaterialType> allMaterials = materialTypeJpaController.getMaterialsByItemTypeDesc(); em.getTransaction().commit(); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("nextId", nextId); jsonObject.addProperty("allTypes", gson.toJson(allMaterials)); PrintWriter writer = response.getWriter(); writer.write(gson.toJson(jsonObject)); writer.close(); em.close(); emf.close(); } else if (requestType.equalsIgnoreCase("getItemDescs")) { Integer mrid = Integer.valueOf(request.getParameter("mrid")); ItemDescriptionTypeJpaController itemDescriptionTypeJpaController = new ItemDescriptionTypeJpaController( emf); em.getTransaction().begin(); List<ItemDescriptionType> idts = itemDescriptionTypeJpaController.findItemDescriptionTypeByMRId(mrid); List<Integer> ids = new ArrayList<>(); for (ItemDescriptionType descriptionType : idts) { ids.add(descriptionType.getItemTypeId()); } ItemDescriptionJpaController descriptionJpaController = new ItemDescriptionJpaController(emf); List<ItemDescription> descriptions = descriptionJpaController.findItemsDescriptionsByItemTypeIds(ids); em.getTransaction().commit(); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("allDescs", gson.toJson(descriptions)); PrintWriter writer = response.getWriter(); writer.write(gson.toJson(jsonObject)); writer.close(); em.close(); emf.close(); } else if (requestType.equalsIgnoreCase("getItemFileds")) { Integer itemId = Integer.valueOf(request.getParameter("itemid")); ItemDescriptionTypeJpaController itemDescriptionTypeJpaController = new ItemDescriptionTypeJpaController( emf); em.getTransaction().begin(); ItemDescriptionJpaController descriptionJpaController = new ItemDescriptionJpaController(emf); ItemDescription itemDescription = descriptionJpaController.findItemDescription(itemId); JsonObject jsonObject = new JsonObject(); UnitsJpaController unitsJpaController = new UnitsJpaController(emf); Units findUnits = unitsJpaController.findUnits(itemDescription.getUnitId()); jsonObject.addProperty("unitId", findUnits.getUnitId()); jsonObject.addProperty("unitDesc", findUnits.getUnitDesc()); String image = ""; try { String extension = FilenameUtils.getExtension(itemDescription.getUploadFileName()); BufferedImage img = ImageIO.read(new File(PICS_DIRECTORY + itemDescription.getUploadFileName())); image = encodeToString(img, extension); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } jsonObject.addProperty("thumb", image); PrintWriter writer = response.getWriter(); writer.write(gson.toJson(jsonObject)); writer.close(); em.close(); emf.close(); } }
From source file:otn.mobile.services.trackServices.java
public void init() { EntityManagerFactory factory; factory = Persistence.createEntityManagerFactory("OTNplatformPU"); em = factory.createEntityManager(); }