Example usage for javax.persistence EntityManager close

List of usage examples for javax.persistence EntityManager close

Introduction

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

Prototype

public void close();

Source Link

Document

Close an application-managed entity manager.

Usage

From source file:org.noorganization.instalist.server.api.ProductResource.java

/**
 * Deletes the product./*  w  w w .  jav a  2 s .c o m*/
 * @param _groupId The id of the group which contains the product.
 * @param _productUUID The uuid of the still existing product.
 *     
 */
@DELETE
@TokenSecured
@Path("{productuuid}")
@Produces({ "application/json" })
public Response deleteProduct(@PathParam("groupid") int _groupId, @PathParam("productuuid") String _productUUID)
        throws Exception {
    UUID toDelete;
    try {
        toDelete = UUID.fromString(_productUUID);
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    IProductController productController = ControllerFactory.getProductController(manager);
    try {
        productController.delete(_groupId, toDelete);
    } catch (NotFoundException _e) {
        return ResponseFactory.generateNotFound(new Error().withMessage("The product was not " + "found."));
    } catch (GoneException _e) {
        return ResponseFactory.generateGone(new Error().withMessage("The product has been " + "deleted."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateOK(null);
}

From source file:net.officefloor.tutorial.transactionhttpserver.TransactionHttpServerTest.java

/**
 * Ensure the JPA connects to database.//from ww  w .java 2 s  .c om
 */
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:org.noorganization.instalist.server.api.IngredientResource.java

/**
 * Deletes the ingredient./*from  ww  w .  j  a  v a  2s . c  o m*/
 * @param _groupId The id of the group still containing the ingredient.
 * @param _ingredientUUID The uuid of the ingredient itself.
 */
@DELETE
@TokenSecured
@Path("{ingredientuuid}")
@Produces({ "application/json" })
public Response deleteIngredient(@PathParam("groupid") int _groupId,
        @PathParam("ingredientuuid") String _ingredientUUID) throws Exception {
    UUID toDelete;
    try {
        toDelete = UUID.fromString(_ingredientUUID);
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    IIngredientController ingredientController = ControllerFactory.getIngredientController(manager);
    try {
        ingredientController.delete(_groupId, toDelete);
    } catch (NotFoundException _e) {
        return ResponseFactory.generateNotFound(new Error().withMessage("The ingredient was " + "not found."));
    } catch (GoneException _e) {
        return ResponseFactory.generateGone(new Error().withMessage("The ingredient has been " + "deleted."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateOK(null);
}

From source file:com.edsoft.teknosaproject.bean.ReportBean.java

@Override
public void typeListener() {
    Menus menus;//from  w w  w.  j  ava 2 s .  com
    typeMenu.clear();
    brandMenu.clear();
    documentMenu.clear();

    path = Paths.get(DIR, "AnaDepo", family);
    //path = Paths.get("D:", "Teknosa", family);
    fileList = path.toFile().listFiles();
    EntityManager em = Persistence.createEntityManagerFactory("teknosa").createEntityManager();
    em.getTransaction().begin();
    Query query = em.createNamedQuery("Menus.findByValued");
    typeMenu.add(new SelectItem("", "Seiniz"));
    for (File file : fileList) {
        if (file.isDirectory()) {
            query.setParameter("valued", file.getName());
            menus = (Menus) query.getResultList().get(0);
            menus.setLabel(menus.getLabel1());
            menus.setValue(menus.getValued());
            typeMenu.add(menus);
        }
    }
    em.getTransaction().commit();
    em.close();
}

From source file:com.edsoft.teknosaproject.bean.ReportBean.java

@Override
public void brandListener() {
    Menus menus;/*from   www . j  a  v a  2  s.  c  o  m*/
    brandMenu.clear();
    documentMenu.clear();
    path = Paths.get(DIR, "AnaDepo", family, type);
    //path = Paths.get("D:", "Teknosa", family, type);
    fileList = path.toFile().listFiles();
    EntityManager em = Persistence.createEntityManagerFactory("teknosa").createEntityManager();
    em.getTransaction().begin();
    Query query = em.createNamedQuery("Menus.findByValued");
    brandMenu.add(new SelectItem("", "Seiniz"));
    for (File file : fileList) {
        if (file.isDirectory()) {
            query.setParameter("valued", file.getName());
            menus = (Menus) query.getResultList().get(0);
            menus.setLabel(menus.getLabel1());
            menus.setValue(menus.getValued());
            brandMenu.add(menus);
        }
    }
    em.getTransaction().commit();
    em.close();
}

From source file:com.enioka.jqm.api.ServiceSimple.java

@GET
@Path("file")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public InputStream getDeliverableStream(@QueryParam("id") String randomId) {
    if (n == null) {
        throw new ErrorDto("can only retrieve a file when the web app runs on top of JQM", "", 7,
                Status.BAD_REQUEST);/*from   w w w .ja v  a 2s.  c  o  m*/
    }

    Deliverable d = null;
    EntityManager em = null;
    try {
        em = ((HibernateClient) JqmClientFactory.getClient()).getEm();
        d = em.createQuery("SELECT d from Deliverable d WHERE d.randomId = :ii", Deliverable.class)
                .setParameter("ii", randomId).getSingleResult();
    } catch (NoResultException e) {
        throw new ErrorDto("Deliverable does not exist", 8, e, Status.BAD_REQUEST);
    } catch (Exception e) {
        throw new ErrorDto("Could not retrieve Deliverable metadata from database", 9, e,
                Status.INTERNAL_SERVER_ERROR);
    } finally {
        if (em != null) {
            em.close();
        }
    }

    String ext = FilenameUtils.getExtension(d.getOriginalFileName());
    res.setHeader("Content-Disposition",
            "attachment; filename=" + d.getFileFamily() + "." + d.getId() + "." + ext);
    return getFile(FilenameUtils.concat(n.getDlRepo(), d.getFilePath()));
}

From source file:com.edsoft.teknosaproject.bean.ReportBean.java

@Override
public void documentListener() {
    Menus menus;//from w w w  .  jav a 2 s .  com
    documentMenu.clear();
    path = Paths.get(DIR, "AnaDepo", family, type, brand);
    //path = Paths.get("D:", "Teknosa", family, type, brand);
    fileList = path.toFile().listFiles();
    EntityManager em = Persistence.createEntityManagerFactory("teknosa").createEntityManager();
    em.getTransaction().begin();
    Query query = em.createNamedQuery("Menus.findByValued");
    documentMenu.add(new SelectItem("", "Seiniz"));
    for (File file : fileList) {
        if (file.isDirectory()) {
            query.setParameter("valued", file.getName());
            menus = (Menus) query.getResultList().get(0);
            menus.setLabel(menus.getLabel1());
            menus.setValue(menus.getValued());
            documentMenu.add(menus);
        }
    }
    em.getTransaction().commit();
    em.close();
}

From source file:com.edsoft.teknosaproject.bean.ReportBean.java

@PostConstruct
public void initialize() {
    list = new ArrayList<>();
    filtered = new ArrayList<>();
    Menus menus;//from w ww .j  av a 2 s. c  o  m
    familyMenu = new ArrayList<>();
    typeMenu = new ArrayList<>();
    brandMenu = new ArrayList<>();
    documentMenu = new ArrayList<>();
    path = Paths.get(DIR, "AnaDepo");
    //path = Paths.get("D:", "Teknosa");
    fileList = path.toFile().listFiles();
    EntityManager em = Persistence.createEntityManagerFactory("teknosa").createEntityManager();
    em.getTransaction().begin();
    Query query = em.createNamedQuery("Menus.findByValued");
    familyMenu.add(new SelectItem("", "Seiniz"));
    for (File file : fileList) {
        if (file.isDirectory()) {
            query.setParameter("valued", file.getName());
            menus = (Menus) query.getResultList().get(0);
            menus.setValue(menus.getValued());
            menus.setLabel(menus.getLabel1());
            familyMenu.add(menus);
        }
    }
    em.getTransaction().commit();
    em.close();
}

From source file:edu.csueb.cs6320.utils.UserService.java

public boolean updatePassword(long userid, String newPassword) {
    EntityManager em = Persistence.createEntityManagerFactory("TestPU").createEntityManager();
    User u = em.find(User.class, userid);
    if (u == null) {
        return false;
    }/*from  ww  w  .  ja v a 2s  .c  o m*/

    em.getTransaction().begin();

    // TODO: This block of code really belongs in User.setPassword()
    String salt = Auth.getSalt();
    u.setSalt(salt);
    try {
        u.setSaltedHashedPassword(Auth.hashPassword(newPassword, salt));
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        em.getTransaction().rollback();
        return false;
    }
    em.getTransaction().commit();
    em.close();

    return true;
}

From source file:ec.edu.chyc.manejopersonal.controller.PersonaJpaController.java

public List<Persona> listPersonas() throws Exception {
    EntityManager em = null;
    try {/*from w w  w.  jav a  2  s .c  o  m*/
        em = getEntityManager();
        Query q = em.createQuery(
                "select distinct p from Persona p left join fetch p.personaFirmasCollection where p.activo is not null");
        List<Persona> list = q.getResultList();
        return list;
    } finally {
        if (em != null) {
            em.close();
        }
    }
}