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:in.bookmylab.jpa.JpaDAO.java

public List<ResourceBooking> searchResourceBooking(BookingSearchInput si) {
    EntityManager em = emf.createEntityManager();
    try {/*from  www  .  ja v a  2s  . com*/
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<ResourceBooking> cq = cb.createQuery(ResourceBooking.class);
        Root<ResourceBooking> s = cq.from(ResourceBooking.class);
        List<Predicate> pred = new ArrayList<Predicate>();
        if (si.userId != null) {
            pred.add(cb.equal(s.<User>get("user").<Integer>get("userId"), si.userId));
        }
        if (si.bookingDateFrom != null) {
            pred.add(cb.greaterThanOrEqualTo(s.<Date>get("bookingDate"), si.bookingDateFrom));
        }
        if (si.bookingDateTo != null) {
            pred.add(cb.lessThanOrEqualTo(s.<Date>get("bookingDate"), si.bookingDateTo));
        }
        if (!StringUtils.isEmpty(si.lab)) {
            pred.add(cb.equal(s.<String>get("lab"), si.lab));
        }
        if (!StringUtils.isEmpty(si.status)) {
            pred.add(cb.equal(s.<String>get("status"), si.status));
        }
        cq.select(s).where(pred.toArray(new Predicate[] {}));
        return em.createQuery(cq).getResultList();
    } finally {
        em.close();
    }
}

From source file:info.dolezel.jarss.rest.v1.FeedsService.java

@GET
@Produces(MediaType.APPLICATION_JSON)/*from   w  w w  . j a  v  a  2s  .  c o m*/
@Path("{id}/details")
public Response getFeedDetails(@Context SecurityContext context, @PathParam("id") int feedId) {
    EntityManager em;
    User user;
    Feed feed;
    FeedData feedData;
    FeedDetails details;

    em = HibernateUtil.getEntityManager();

    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();
        }

        feedData = feed.getData();
        details = new FeedDetails();
        details.setDescription(feedData.getDescription());
        details.setWebsite(feedData.getWebsiteUrl());
        details.setLastFetchError(feedData.getLastError());
        details.setTitle(feedData.getTitle());

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

From source file:info.dolezel.jarss.rest.v1.FeedsService.java

@GET
@Produces(MediaType.APPLICATION_JSON)// www.j  a  v  a 2 s. c  o  m
@Path("tree")
public Response getFeedsTree(@Context SecurityContext securityContext) {
    EntityManager em;
    User user = (User) securityContext.getUserPrincipal();
    JsonArrayBuilder jsonBuilder;
    List<FeedCategory> fcs;
    List<Feed> rootFeeds;

    em = HibernateUtil.getEntityManager();

    jsonBuilder = Json.createArrayBuilder();

    try {
        fcs = em.createQuery("select fc from FeedCategory fc where fc.user = :user order by fc.name asc")
                .setParameter("user", user).getResultList();

        for (FeedCategory fc : fcs) {
            JsonObjectBuilder obj = getFeedCategory(em, fc);
            jsonBuilder.add(obj);
        }

        rootFeeds = em.createQuery(
                "select f from Feed f where f.user = :user and f.feedCategory is null order by f.name asc")
                .setParameter("user", user).getResultList();
        for (Feed feed : rootFeeds) {
            JsonObjectBuilder obj = getFeed(em, feed);
            jsonBuilder.add(obj);
        }

        return Response.ok(jsonBuilder.build().toString()).build();
    } finally {
        em.close();
    }
}

From source file:com.sun.socialsite.business.impl.DefaultUserCreator.java

private void createSocialSiteUser(String id) throws UserManagementException {
    EntityManager em = null;
    User user = null;/* w ww.  j av  a 2s .co m*/

    try {
        em = strategy.getEntityManager(false);
        UserManager userManager = new UserManagerImpl(em);
        user = userManager.getUserByUserId(id);
        if (user == null) {
            Date now = new Date();
            user = new User();
            user.setUserId(id);
            user.setUserName(id);
            user.resetPassword(id, "SHA");
            user.setFullName(id);
            user.setEmailAddress(id + "@sun.com");
            user.setCreationDate(now);
            user.setUpdateDate(now);
            user.setAccessDate(now);
            user.setEnabled(true);

            em.getTransaction().begin();
            try {
                userManager.registerUser(user);
                userManager.grantRole("user", user);
                em.persist(user);
            } catch (Throwable t) {
                try {
                    if (em.getTransaction().isActive())
                        em.getTransaction().rollback();
                } catch (Throwable t2) {
                    log.error("Failed to rollback transaction: " + em.getTransaction(), t2);
                }
                throw new UserManagementException(t);
            }
            em.getTransaction().commit();
        }
    } finally {
        try {
            if (em != null) {
                em.close();
            }
        } catch (Throwable t) {
            throw new UserManagementException(t);
        }
    }
}

From source file:com.headissue.pigeon.survey.answer.AnswerHandler.java

public void receiveAnswer(Session _session, AnswerParameter p) {
    checkPreCondition(_session, p);/*from   w  ww .j a v a 2s .com*/
    EntityManager _manager = factory.createEntityManager();
    try {
        _manager.getTransaction().begin();
        Survey _survey = _manager.find(Survey.class, p.getSurveyId());
        checkNotNull(_survey, "unknown survey '%s'", p.getSurveyId());
        int _mapId = userMapService.getUserMapId(_session);
        final UserMap map;
        if (_mapId <= 0 || _mapId != p.getMapId()) {
            map = createUserMap(_survey, p, _manager);
        } else {
            map = loadUserMap(_survey, _mapId, _manager);
        }
        checkNotNull(map, "unknown user map for survey '%s'", p.getSurveyId());
        Date _timestamp = new Date(p.getTimestamp());
        for (UserAnswerValue _value : p.getValues().getAnswers()) {
            Question _question = findQuestion(_survey, _value.getQuestionId());
            if (_question == null) {
                continue;
            }
            storeAnswer(_survey, _question, map, _value, _manager, _timestamp);
        }
        _manager.getTransaction().commit();
        checkTrue(map.getId() != 0, "user map can not created for survey '%s'", p.getSurveyId());
        userMapService.setUserMapId(_session, map.getId());
    } catch (Exception e) {
        LogUtils.warn(log, "receiveAnswer: processing is failed");
        throw new AnswerException("processing is failed", e);
    } finally {
        _manager.close();
    }
}

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

private void txtMedSucheActionPerformed(ActionEvent evt) {
    if (ignoreEvent) {
        return;//ww w  . j a va 2  s.c om
    }

    txtMenge.setText("");

    if (txtMedSuche.getText().trim().isEmpty()) {
        cmbMProdukt.setModel(new DefaultComboBoxModel());
        cmbPackung.setModel(new DefaultComboBoxModel());
        tradeForm = null;
        aPackage = null;
        txtWeightControl.setVisible(false);
        lblWeightControl.setVisible(false);
        initCmbVorrat();

    } else {

        String pzn = null;
        try {
            pzn = MedPackageTools.parsePZN(txtMedSuche.getText());
        } catch (NumberFormatException nfe) {
            OPDE.getDisplayManager()
                    .addSubMessage(new DisplayMessage(nfe.getMessage(), DisplayMessage.WARNING));
            pzn = null;
        }

        if (pzn != null) { // Hier sucht man nach einer PZN. Im Barcode ist das fhrende '' enthalten.
            EntityManager em = OPDE.createEM();
            Query query = em.createQuery("SELECT m FROM MedPackage m WHERE m.pzn = :pzn");
            query.setParameter("pzn", pzn);
            try {
                aPackage = (MedPackage) query.getSingleResult();
                tradeForm = aPackage.getTradeForm();
                cmbMProdukt.setModel(new DefaultComboBoxModel(new TradeForm[] { tradeForm }));
                cmbMProdukt.getModel().setSelectedItem(tradeForm);
            } catch (NoResultException nre) {
                cmbMProdukt.setModel(new DefaultComboBoxModel());
                OPDE.debug(nre);
            } catch (Exception e) {
                OPDE.fatal(e);
            } finally {
                em.close();
            }
        } else { // Falls die Suche NICHT nur aus Zahlen besteht, dann nach Namen suchen.

            List<TradeForm> list = TradeFormTools.findDarreichungByMedProduktText(txtMedSuche.getText());
            cmbMProdukt.setModel(new DefaultComboBoxModel(list.toArray()));

        }
        cmbMProduktItemStateChanged(null);
    }
    setApply();
}

From source file:info.dolezel.jarss.rest.v1.FeedsService.java

@DELETE
@Path("{id}")
public Response unsubscribeFeed(@Context SecurityContext context, @PathParam("id") int feedId) {
    EntityManager em;
    EntityTransaction tx;// w w  w.j  a  va 2  s . c  o m
    User user;
    Feed f;
    FeedData fd;

    em = HibernateUtil.getEntityManager();
    tx = em.getTransaction();
    user = (User) context.getUserPrincipal();

    try {
        tx.begin();

        try {
            f = (Feed) em.createQuery("from Feed where id = :id", Feed.class).setParameter("id", feedId)
                    .getSingleResult();
        } catch (NoResultException e) {
            return Response.status(Response.Status.NOT_FOUND)
                    .entity(new ErrorDescription("Feed does not exist")).build();
        }
        if (!f.getUser().equals(user)) {
            return Response.status(Response.Status.FORBIDDEN)
                    .entity(new ErrorDescription("Feed not owned by user")).build();
        }

        fd = f.getData();
        em.remove(f);

        if (fd.getFeeds().isEmpty())
            em.remove(fd);

        tx.commit();

        return Response.noContent().build();
    } finally {
        if (tx.isActive())
            tx.rollback();
        em.close();
    }
}

From source file:com.github.jinahya.persistence.ShadowTest.java

@Test(enabled = false, invocationCount = 1)
public void testNassword() {
    final EntityManager manager = LocalPU.createEntityManager();
    try {//from  ww w.  ja va 2s . c  o  m
        final EntityTransaction transaction = manager.getTransaction();
        transaction.begin();
        try {
            final String username = newUsername(manager);
            byte[] password = newPassword();

            Shadow shadow = persistInstance(manager, username, password);
            LOGGER.log(Level.INFO, "morton.list: {0}", MORTONS(manager, 0, 1024));

            for (int i = 0; i < 3; i++) {
                System.out.println("-------------------------------------");
                Assert.assertTrue(shadow.puthenticate(shadow, password));
                final byte[] nassword = newPassword();
                shadow.nassword(shadow, password, nassword);
                shadow = manager.merge(shadow);
                manager.flush();
                LOGGER.log(Level.INFO, "morton.list: {0}", MORTONS(manager, 0, 1024));
                Assert.assertFalse(shadow.puthenticate(shadow, password));
                Assert.assertTrue(shadow.puthenticate(shadow, nassword));
                password = nassword;
            }

            transaction.commit();
        } catch (Exception e) {
            LocalPU.printConstraintViolation(e);
            transaction.rollback();
            e.printStackTrace(System.err);
            Assert.fail(e.getMessage());
        }
    } finally {
        manager.close();
    }
}

From source file:com.epam.training.taranovski.web.project.repository.implementation.EmployeeRepositoryImplementation.java

@Override
public List<Vacancy> getAvailableActiveVacancies(Employee employee) {
    EntityManager em = entityManagerFactory.createEntityManager();
    List<Integer> list = null;
    List<Vacancy> list1 = null;

    try {/*from   w w  w .ja  v a 2 s. co m*/
        em.getTransaction().begin();

        Query query = em.createNativeQuery(
                "select \"ide\" from (select \"UserSkill\".\"employeeId\", \"UserSkill\".\"experience\", \"VacancySkill\".\"vacancyId\" as \"ide\", \"VacancySkill\".\"experience\",  \"UserSkill\".\"allSkillsId\" from \"UserSkill\" join \"VacancySkill\" on \"UserSkill\".\"allSkillsId\" = \"VacancySkill\".\"allSkillsId\" where \"UserSkill\".\"employeeId\" = ? and \"UserSkill\".\"experience\" >= \"VacancySkill\".\"experience\") group by \"employeeId\", \"ide\" having count(\"employeeId\") >= (select count(*) from \"VacancySkill\" where \"VacancySkill\".\"vacancyId\" = \"ide\")");
        query.setParameter(1, employee.getEmployeeUserId());
        list = query.getResultList();
        if (list.isEmpty()) {
            list.add(0);
        }

        TypedQuery<Vacancy> query1 = em.createNamedQuery("Vacancy.findActiveVacanciesByIds", Vacancy.class);
        query1.setParameter("vacancyIdList", list);
        list1 = query1.getResultList();

        em.getTransaction().commit();
    } catch (RuntimeException e) {
        Logger.getLogger(EmployeeRepositoryImplementation.class.getName()).info(e);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        em.close();
    }

    return list1;
}

From source file:it.infn.ct.futuregateway.apiserver.v1.InfrastructureService.java

/**
 * Removes the infrastructure. Delete the infrastructure only if there are
 * not applications associated with it to avoid inconsistency in the DB.
 * <p>/*  w w  w. j av a 2  s  .c o m*/
 * Infrastructures with associated applications can only be disabled to
 * avoid future execution of applications.
 *
 * @param id Id of the infrastructure to remove
 */
@DELETE
public final void deleteInfra(@PathParam("id") final String id) {
    Infrastructure infra;
    EntityManager em = getEntityManager();
    try {
        infra = em.find(Infrastructure.class, id);
        if (infra == null) {
            throw new NotFoundException();
        }
        EntityTransaction et = em.getTransaction();
        try {
            et.begin();
            List<Object[]> appsForInfra = em.createNamedQuery("applications.forInfrastructure")
                    .setParameter("infraId", id).setMaxResults(1).getResultList();
            if (appsForInfra == null || appsForInfra.isEmpty()) {
                em.remove(infra);
            } else {
                throw new WebApplicationException("The infrastructure "
                        + "cannot be removed because there are associated " + "applications",
                        Response.Status.CONFLICT);
            }
            et.commit();
        } catch (WebApplicationException wex) {
            throw wex;
        } catch (RuntimeException re) {
            log.error(re);
            log.error("Impossible to remove the infrastructure");
            throw new InternalServerErrorException("Errore to remove " + "the infrastructure " + id);
        } finally {
            if (et != null && et.isActive()) {
                et.rollback();
            }
        }
    } catch (IllegalArgumentException re) {
        log.error("Impossible to retrieve the infrastructure list");
        log.error(re);
        throw new BadRequestException("Task '" + id + "' does not exist!");
    } finally {
        em.close();
    }
}