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:info.dolezel.jarss.rest.v1.FeedsService.java

@POST
@Path("{id}/forceFetch")
public Response forceFetch(@Context SecurityContext context, @PathParam("id") int feedId) {
    EntityManager em = HibernateUtil.getEntityManager();
    User user;// w  w  w .  j ava2 s .  c o  m
    Feed feed;

    try {
        user = (User) context.getUserPrincipal();

        feed = em.find(Feed.class, feedId);
        if (feed == null) {
            return Response.status(Response.Status.NOT_FOUND)
                    .entity(new ErrorDescription("Feed does not exist")).build();
        }
        if (!feed.getUser().equals(user)) {
            return Response.status(Response.Status.FORBIDDEN)
                    .entity(new ErrorDescription("Feed not owned by user")).build();
        }

        FeedsEngine.getInstance().submitFeedRefresh(feed.getData());

        return Response.noContent().build();
    } finally {
        em.close();
    }
}

From source file:com.espirit.moddev.examples.uxbridge.newswidget.test.VirtualTopicsITCase.java

/**
 * Test add.//from w  w  w .j  a  v a  2 s . c  om
 *
 * @throws Exception the exception
 */
@Test
public void testAdd() throws Exception {

    assertEquals("DB not empty", 0, countArticles());

    EntityManager em = emf.createEntityManager();

    String[] ids = new String[] { "128", "130", "131", "132", "256", "704" };

    // insert all items
    for (String id : ids) {
        // item should not be in the db
        Query query = em.createQuery(
                new StringBuilder().append("SELECT x FROM article x WHERE x.aid = ").append(id).toString());
        assertEquals(0, query.getResultList().size());

        // load content
        String content = getContent("src/test/resources/inbox/add/pressreleasesdetails_" + id + ".xml",
                "hibernate");
        // send content to jms broker
        template.sendBody("activemq:topic:VirtualTopic.Orders", content);

        // wait
        Thread.sleep(TimeOuts.LONG);

        // item should be inserted to db
        query = em.createQuery(
                new StringBuilder().append("SELECT x FROM article x WHERE x.aid = ").append(id).toString());
        assertEquals(1, query.getResultList().size());
    }

    assertEquals("not all items are present", ids.length, countArticles());

    em.close();
}

From source file:com.tesora.dve.common.catalog.CatalogDAO.java

public void close() {
    EntityManager theEm = em.getAndSet(null);
    if (theEm != null && theEm.isOpen())
        theEm.close();
}

From source file:br.com.i9torpedos.model.service.repository.BaseRepository.java

public T saveOrUpdate(T obj) throws PersistenceException {
    EntityManager em = EntityManagerUtil.getEntityManager();
    em.getTransaction().begin();//from   ww w .  ja  v  a2  s .  c  o m
    Boolean situacao = false;

    if (obj != null) {

        try {
            // if (obj != null) {
            obj = em.merge(obj);

            log.info("Dados Atualizado com Sucesso. " + obj.getClass().getName());
            situacao = true;

            /*} else {
            em.persist(obj);
                    
            log.info("Dados Gravado com Sucesso. " + obj.getClass().getName());
            situacao = true;
            }*/

        } catch (Exception e) {
            situacao = false;
            log.fatal("Falha em Atualizar ou Gravar dados " + e.getMessage());

            //Devida a falha de Persistencia ira Realizar um Rolback
            em.getTransaction().rollback();
            throw new PersistenceException("Falha ao Persistir Dados", e);

        } finally {

            //se for verdadeiro ento realiza o commit e fecha meu entitymanager
            if (situacao) {
                em.getTransaction().commit();
                //em.flush();
                // em.clear();
            }
            em.close();
            log.info("EntityManager fechado com Sucesso. Metodo saveOrUpdate");
        }
    }

    return obj;

}

From source file:com.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java

/**
 * Deletes every article older than the creationTime of the UXBEntity
 *
 * @param entity Entity containing the expireDate (= createTime of the entity)
 *//* w ww.j a  v a 2  s.  co  m*/
public void cleanup(UXBEntity entity) throws Exception {

    EntityManager em = null;
    EntityTransaction tx = null;
    try {

        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();

        Query query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM article x WHERE x.lastmodified<:expiredate ").toString());
        query.setParameter("expiredate", entity.getCreateTime());

        if (!query.getResultList().isEmpty()) {
            for (Object obj : query.getResultList()) {
                Article art = (Article) obj;
                em.remove(art);
            }
        }
        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.setRollbackOnly();
            throw e;
        }
        logger.error("Failure while deleting from the database", e);
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }

}

From source file:edu.kit.dama.rest.sharing.services.impl.SharingRestServiceImpl.java

@Override
public Response revokeGrant(Long pId, String pGroupId, HttpContext hc) {
    IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(pGroupId));
    //Hack using EM directly...other way?
    EntityManager em = PU.entityManager();
    try {//from  www  .j ava2 s  . c om
        LOGGER.debug("Finding grant for id " + pId);
        Grant grant = FindUtil.findGrant(em, pId);
        LOGGER.debug("Revoking grant for id " + pId);
        ResourceServiceLocal.getSingleton().revokeGrant(
                grant.getGrants().getResource().getSecurableResourceId(),
                new UserId(grant.getGrantee().getUserId()), ctx);
        return Response.ok().build();
    } catch (UnauthorizedAccessAttemptException ex) {
        LOGGER.error("Failed to revoke grant with id " + pId, ex);
        throw new WebApplicationException(401);
    } catch (EntityNotFoundException ex) {
        LOGGER.error("EntityNotFoundException caught while obtaining Grant for id " + pId
                + ". Probably, there is no grant for this id.", ex);
        throw new WebApplicationException(404);
    } finally {
        em.close();
    }
}

From source file:mil.navy.med.dzreg.dao.RegistriesManagerDAO.java

private boolean unregister(DzRegPK registryKey, Timestamp today) {
    EntityManager em = null;
    PersistentServiceFactory psf = null;

    try {//from   w ww .  j  a v  a2 s  .  c o m
        psf = PersistentServiceFactory.getInstance(REGISTRY_MANAGER_PU);
        em = psf.getEntityManager();

        em.getTransaction().begin();
        DzReg r = em.find(DzReg.class, registryKey);
        r.setActive(_INACTIVE);
        r.setInsertedDt(today);
        em.getTransaction().commit();

        return true;
    } catch (javax.persistence.NoResultException nre) {
        em.getTransaction().rollback();
        log.error(registryKey + " not found!");
        return false;
    } catch (Exception ex) {
        em.getTransaction().rollback();
        return false;
    } finally {
        em.close();
    }
}

From source file:in.bookmylab.jpa.JpaDAO.java

public HashMap<String, Object> getDashboardData(boolean isManager, int userId) {
    EntityManager em = emf.createEntityManager();
    HashMap<String, Object> data = new HashMap<>();
    try {//from   ww  w .ja  va  2 s. c o m
        if (isManager) {

            List<User> l = em.createNamedQuery("User.findUnverified", User.class).getResultList();
            data.put(Constants.JK_UNVERIFIED_USERS, l);

            List<ResourceBooking> l2 = em
                    .createNamedQuery("ResourceBooking.findUnfinished", ResourceBooking.class).getResultList();
            data.put(Constants.JK_PENDING_BOOKINGS, l2);

        } else {
            List<ResourceBooking> l2 = em
                    .createNamedQuery("ResourceBooking.findUnfinishedForUser", ResourceBooking.class)
                    .setParameter("userId", userId).getResultList();
            data.put(Constants.JK_PENDING_BOOKINGS, l2);

            // TODO: Add other lab bookings

        }
    } finally {
        em.close();
    }
    return data;
}

From source file:op.care.med.inventory.DlgOpenStock.java

private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed
    if (cmbBestID.getSelectedIndex() > 0) {
        EntityManager em = OPDE.createEM();
        try {//from ww w.ja va 2 s .com
            em.getTransaction().begin();
            medStock = em.merge((MedStock) cmbBestID.getSelectedItem());
            em.lock(medStock, LockModeType.OPTIMISTIC);
            em.lock(em.merge(medStock.getInventory().getResident()), LockModeType.OPTIMISTIC);

            medStock.setOpened(new Date());

            em.getTransaction().commit();
        } catch (javax.persistence.OptimisticLockException ole) {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                OPDE.getMainframe().emptyFrame();
                OPDE.getMainframe().afterLogin();
            }
            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
        } catch (Exception e) {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
            OPDE.fatal(e);
        } finally {
            em.close();
        }
        dispose();
    }
}

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

/**
 * Updates an ingredient.//from ww w  . j  ava 2s.c o  m
 * @param _groupId The id of the group containing the ingredient.
 * @param _ingredientUUID The uuid of the ingredient itself.
 * @param _entity Data for updating the ingredient.
 */
@PUT
@TokenSecured
@Path("{ingredientuuid}")
@Consumes("application/json")
@Produces({ "application/json" })
public Response putIngredient(@PathParam("groupid") int _groupId,
        @PathParam("ingredientuuid") String _ingredientUUID, IngredientInfo _entity) throws Exception {
    if ((_entity.getUUID() != null && !_entity.getUUID().equals(_ingredientUUID))
            || (_entity.getDeleted() != null && _entity.getDeleted())
            || (_entity.getAmount() != null && _entity.getAmount() < 0.001f))
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);

    UUID toUpdate;
    UUID productUUID = null;
    UUID recipeUUID = null;
    try {
        toUpdate = UUID.fromString(_ingredientUUID);
        if (_entity.getProductUUID() != null)
            productUUID = UUID.fromString(_entity.getProductUUID());
        if (_entity.getRecipeUUID() != null)
            recipeUUID = UUID.fromString(_entity.getRecipeUUID());
    } 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();
    IIngredientController ingredientController = ControllerFactory.getIngredientController(manager);
    try {
        ingredientController.update(_groupId, toUpdate, recipeUUID, productUUID, _entity.getAmount(), updated);
    } 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."));
    } catch (ConflictException _e) {
        return ResponseFactory.generateConflict(
                new Error().withMessage("The sent data would " + "conflict with saved ingredient."));
    } catch (BadRequestException _e) {
        return ResponseFactory.generateBadRequest(
                new Error().withMessage("The referenced " + "product or recipe was not found."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateOK(null);
}