Example usage for javax.persistence EntityManagerFactory close

List of usage examples for javax.persistence EntityManagerFactory close

Introduction

In this page you can find the example usage for javax.persistence EntityManagerFactory close.

Prototype

public void close();

Source Link

Document

Close the factory, releasing any resources that it holds.

Usage

From source file:BO.UserHandler.java

public boolean login(VUser u) {

    EntityManager em;/*from ww  w  .  ja v a2  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:ict.DoLoginServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww w  .  j  av a2  s.co  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    try {
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("WSPU");
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        entityManager.getTransaction().begin();

        String _request = request.getParameter("AAA");
        String userID = new String(Base64.decodeBase64(_request));

        String _request_ = request.getParameter("BBB");
        String userPassword = new String(Base64.decodeBase64(_request_));

        //String userID = request.getParameter("userID");
        //String userPassword = request.getParameter("userPassword");
        User tmp = new User();
        tmp.setUserID(userID);
        tmp.setPassword(userPassword);
        System.out.println("*****" + tmp.getUserID());

        User user = entityManager.find(User.class, tmp.getUserID());
        if (user.getPassword().equals(tmp.getPassword())) {
            entityManager.getTransaction().commit();
            entityManager.close();
            entityManagerFactory.close();
            request.getSession(true).setAttribute("user", user.getUserName());
        }

    } catch (Exception e) {
        System.out.println("****ERROR:****" + e.getMessage());
    }
    response.sendRedirect("index.jsp");
}

From source file:BO.UserHandler.java

public boolean updateDeviceToken(VUser u) {
    EntityManager em;/*from w  ww . j a  v a 2 s .  com*/
    EntityManagerFactory emf;
    emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME);
    em = emf.createEntityManager();
    System.out.println("Updating token: " + u.getDeviceToken());
    try {
        em.getTransaction().begin();
        User user;
        user = (User) em.createQuery("SELECT u FROM User u WHERE u.email LIKE :email")
                .setParameter("email", u.getEmail()).setMaxResults(1).getSingleResult();
        user.setDeviceToken(u.getDeviceToken());
        em.persist(user);
        em.flush();
        em.getTransaction().commit();

        return true;
    } catch (NoResultException e) {
        return false;
    } finally {
        if (em != null) {
            em.close();
        }
        emf.close();
    }

}

From source file:BO.UserHandler.java

public List<VUser> getPendingFriends(VUser user) {

    EntityManager em;/*from   www.  j a  va  2 s .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 "
                        + "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:net.officefloor.tutorial.transactionhttpserver.TransactionHttpServerTest.java

/**
 * Ensure the JPA connects to database.// w  ww.ja v  a2s.c  o  m
 */
public void testJpa() throws Exception {

    // Request page to allow time for database setup
    this.doRequest("http://localhost:7878/users.woof");

    // Obtain entity manager
    EntityManagerFactory factory = Persistence.createEntityManagerFactory("example");
    EntityManager manager = factory.createEntityManager();

    // Ensure can obtain user and person
    Query query = manager.createQuery("SELECT U FROM User U");
    User user = (User) query.getSingleResult();
    assertEquals("Incorrect user name", "daniel", user.getUserName());
    Person person = user.getPerson();
    assertEquals("Incorrect person name", "Daniel Sagenschneider", person.getFullName());

    // Ensure persist user and person
    User newUser = new User();
    newUser.setUserName("test");
    Person newPerson = new Person();
    newPerson.setFullName("TEST");
    newPerson.setUser(newUser);
    manager.persist(newPerson);
    manager.close();

    // Ensure user and person persisted
    manager = factory.createEntityManager();
    User retrievedUser = manager.find(User.class, newUser.getId());
    assertEquals("Incorrect retrieved user name", "test", retrievedUser.getUserName());
    Person retrievedPerson = retrievedUser.getPerson();
    assertEquals("Incorrect retrieved full name", "TEST", retrievedPerson.getFullName());

    // Close persistence
    factory.close();
}

From source file:BO.UserHandler.java

public boolean respondFriendRequest(VUser user) {
    EntityManager em;//w  ww.  j  av a 2s .  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:com.edugility.substantia.substance.TestCasePerson.java

@Test
public void testingJPA() throws Exception {
    final EntityManagerFactory emf = Persistence.createEntityManagerFactory("test");
    assertNotNull(emf);//from  w w  w  .ja v a 2  s  .  c  om

    final EntityManager em = emf.createEntityManager();
    assertNotNull(em);

    final EntityTransaction et = em.getTransaction();
    assertNotNull(et);
    et.begin();

    final Person p = new Person();
    em.persist(p);
    em.flush();
    assertFalse(p.isTransient());
    assertTrue(p.isVersioned());
    assertEquals(Long.valueOf(1L), p.getId());
    assertEquals(Integer.valueOf(1), p.getVersion());

    et.commit();
    et.begin();

    final Person p2 = em.find(Person.class, 1L, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
    assertNotNull(p2);
    assertFalse(p2.isTransient());
    assertTrue(p2.isVersioned());
    assertEquals(Long.valueOf(1L), p2.getId());
    assertEquals(Integer.valueOf(1), p2.getVersion());

    et.commit();
    et.begin();

    final Person p3 = em.getReference(Person.class, 1L);
    assertNotNull(p3);
    assertFalse(p3.isTransient());
    assertTrue(p3.isVersioned());
    assertEquals(Long.valueOf(1L), p3.getId());
    assertEquals(Integer.valueOf(2), p3.getVersion());

    et.commit();
    et.begin();

    assertTrue(em.contains(p));
    em.remove(p);

    et.commit();

    em.close();

    emf.close();
}

From source file:BO.UserHandler.java

public List<VUser> getFriends(VUser user) {
    EntityManager em;//from  ww w.  j a  v a2 s  .c om

    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:BO.UserHandler.java

public boolean addFriend(VUser u) {
    EntityManager em;//from   w w w  . j  a  va  2  s.  c  om
    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:Logica.Usuario.java

/**
 *
 * @param anterior/* w w  w  .j av  a2 s  .  c  o m*/
 * @param id
 * @return boolean
 * @throws RemoteException
 *
 * Verifica la validez de la contrasea anterior, antes de realizar el
 * cambio de clave.
 */
@Override
public boolean verificarClave(String anterior, String id) throws RemoteException {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("Biot_ServerPU");
    UsuarioJpaController us = new UsuarioJpaController(emf);
    Entities.Usuario findUsuario = us.findUsuario(id);
    emf.close();
    return findUsuario.getPsw().equalsIgnoreCase(this.encriptar(anterior));
}