Example usage for javax.persistence EntityManager find

List of usage examples for javax.persistence EntityManager find

Introduction

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

Prototype

public <T> T find(Class<T> entityClass, Object primaryKey);

Source Link

Document

Find by primary key.

Usage

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public void deleteCategory(int catid) {

    EntityManager entityManager = entityManagerFactory.createEntityManager();
    Category c = entityManager.find(Category.class, catid);

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();/*w  w w .j  a v  a 2 s  .c o m*/
    entityManager.remove(c);
    entityTransaction.commit();

}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public FStoreProperty readPropertyByID(int propid) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    FStoreProperty u = entityManager.find(FStoreProperty.class, propid);
    return u;//from ww  w  .  ja  v  a  2  s . co m

}

From source file:com.gigglinggnus.controllers.AdminMakeAppointmentController.java

/**
 *
 * @param request servlet request/* ww w .  j a  v  a  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 doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    EntityManager em = (EntityManager) request.getSession().getAttribute("em");

    String msg = request.getParameter("msg");
    User user = (User) (request.getSession().getAttribute("user"));
    Clock clk = (Clock) (request.getSession().getAttribute("clock"));

    if (msg.equals("lookup_student")) {
        String studId = request.getParameter("studentId");
        User student = em.find(User.class, studId);
        List<Exam> exams = student.getRegistrableExams();
        JSONObject json = new JSONObject();
        json.put("students_idNumber", studId);
        json.put("firstName", student.getFirstName());
        json.put("lastName", student.getLastName());
        JSONArray jExams = new JSONArray();
        for (Exam exam : exams) {
            JSONObject elem = new JSONObject();

            String examId = exam.getExamId();
            String termId = exam.getTerm().getTermId();
            String start = exam.getInterval().getStart().atZone(ZoneId.systemDefault()).toLocalDate()
                    .toString();
            String end = exam.getInterval().getEnd().atZone(ZoneId.systemDefault()).toLocalDate().toString();
            elem.put("examId", examId);
            elem.put("termId", termId);
            if (exam instanceof CourseExam) {
                String courseId = ((CourseExam) exam).getCourse().getCourseId();
                elem.put("courseId", courseId);
                elem.put("examType", "Course");
            } else {
                elem.put("courseId", "N/A");
                elem.put("examType", "AdHoc");
            }
            elem.put("start", start);
            elem.put("end", end);
            jExams.put(elem);
        }
        json.put("exams", jExams);
        response.getWriter().write(json.toString());
    } else if (msg.equals("exam_available_timeslots")) {
        String examId = request.getParameter("examId");
        String dateStr = request.getParameter("date");
        Exam exam = em.find(Exam.class, examId);
        LocalDate apptDate = LocalDate.parse(dateStr);
        List<LocalTime> timeslots = exam.getTimeslotsForDay(apptDate);

        JSONObject json = new JSONObject();
        json.put("examId", examId);
        JSONArray jTimeSlots = new JSONArray();
        for (LocalTime timeslot : timeslots) {
            String start = timeslot.toString();
            String end = timeslot.plus(exam.getDuration()).toString();
            JSONObject elem = new JSONObject();
            elem.put("start", start);
            elem.put("end", end);
            jTimeSlots.put(elem);
        }
        json.put("timeSlots", jTimeSlots);
        response.getWriter().write(json.toString());
    } else if (msg.equals("submit-appointment")) {
        String studId = request.getParameter("studentId");
        String examId = request.getParameter("examId");
        String stDate = request.getParameter("examDate");
        String stTime = request.getParameter("startTime") + ":00";
        String stSeat = request.getParameter("seatType");

        User student = em.find(User.class, studId);
        Exam exam = em.find(Exam.class, examId);
        LocalDate lDate = LocalDate.parse(stDate);
        LocalTime lTime = LocalTime.parse(stTime);
        Instant inst = ZonedDateTime.of(lDate, lTime, ZoneId.systemDefault()).toInstant();
        JSONObject json = new JSONObject();
        try {
            em.getTransaction().begin();
            if (stSeat.equals("normal")) {
                user.makeAppointment(student, Seating.NORMAL, exam, inst, clk);
                em.getTransaction().commit();
                json.put("success", "Appointment Made!");
                response.getWriter().write(json.toString());
            } else if (stSeat.equals("setaside")) {
                user.makeAppointment(student, Seating.SETASIDE, exam, inst, clk);
                em.getTransaction().commit();
                json.put("success", "Appointment Made!");
                response.getWriter().write(json.toString());
            } else {
                em.getTransaction().rollback();
                json.put("error", "invalid choice of seating");
                response.getWriter().write(json.toString());
            }
        } catch (Exception e) {
            em.getTransaction().rollback();
            json.put("error", e.toString());
            response.getWriter().write(json.toString());
        }
    } else {
        JSONObject json = new JSONObject();
        json.put("error", msg);
        response.getWriter().write(json.toString());
    }
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public void deleteUser(int userid) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    FStoreUser u = entityManager.find(FStoreUser.class, userid);

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();//  w  w w . j a v a2 s.com

    entityManager.remove(u);

    entityTransaction.commit();
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public void deleteProperty(int propid) {

    EntityManager entityManager = entityManagerFactory.createEntityManager();
    FStoreProperty c = entityManager.find(FStoreProperty.class, propid);

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();// w w w .  j  av  a 2  s.  c o m
    entityManager.remove(c);
    entityTransaction.commit();

}

From source file:org.drools.semantics.lang.dl.DL_9_CompilationTest.java

private Object refreshOnJPA(Object o, Object key, EntityManager em) {
    Object ret = null;/*from w  w w. j av  a 2 s  .  c o m*/
    em.getTransaction().begin();
    ret = em.find(o.getClass(), key);
    em.getTransaction().commit();
    return ret;
}

From source file:org.apache.openjpa.jdbc.meta.strats.AbstractLobTest.java

public void testSetResetAndFlush() throws IOException {
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();/*  w  w  w . j av  a2  s  .c om*/
    LobEntity le = newLobEntity(createLobData(), 1);
    em.persist(le);
    String string = createLobData2();
    changeStream(le, string);
    em.flush();
    em.getTransaction().commit();
    em.close();
    em = emf.createEntityManager();
    em.getTransaction().begin();
    LobEntity entity = (LobEntity) em.find(getLobEntityClass(), 1);
    assertEquals(string, getStreamContentAsString(entity.getStream()));
    em.getTransaction().commit();
    em.close();
}

From source file:com.webbfontaine.valuewebb.gtns.TTGTNSSynchronizer.java

@Asynchronous
public QuartzTriggerHandle findSentFCVRScheduleTask(@Expiration Date when, @IntervalCron String interval) {
    LOGGER.debug("Scheduler to upload FCVR started");
    long startTime = System.currentTimeMillis();

    synchronized (LOCK) { // allow only one async thread to do this

        EntityManager entityManager = (EntityManager) Component.getInstance("entityManager",
                ScopeType.STATELESS, true);
        List<Long> ttIDs = Utils.setDirectRead(entityManager.createNamedQuery(findSentTTIdsGH)).getResultList();

        LOGGER.debug("Found Sent TTs: {0}", ttIDs);

        if (ttIDs.isEmpty()) {
            return null;
        }//from  w  ww  .jav a 2 s .c  o m

        for (Long ttId : ttIDs) {
            TtGen ttGen = entityManager.find(TtGen.class, ttId);

            if (!ttGen.getStatus().equals(TT_SENT)) { // already processed by other thread
                continue;
            }

            FisInterface fisInterface = new FisInterface();

            LOGGER.debug("Sending request to upload FCVR for TT # {0}, FCVR Number = {1}", ttGen.getId(),
                    ttGen.getFcvrNum());
            List<String> uploadErrors = fisInterface.sendFCVRUploadRequest(ttGen);

            if (uploadErrors != null) {
                if (uploadErrors.isEmpty()) {
                    LOGGER.debug(
                            "Request to upload FCVR for TT # {0}, FCVR Number = {1} is successfully sent, setting GCNet Submission Flag 'true'",
                            ttGen.getId(), ttGen.getFcvrNum());
                    updateTTFlag(ttGen);
                } else {
                    if (!GCNetUtils.isContain(uploadErrors, FCVR_ALREADY_EXIST)) {
                        LOGGER.debug("Error(s) during upload FCVR: {0}",
                                GCNetUtils.constraintUploadErrors(uploadErrors));
                        if (!AuthenticatorBean.getDaemonIdentity().tryLogin()) {
                            LOGGER.error("Can not login with 'daemon' identity to update TTs");
                            return null;
                        }
                        updateTTForSentError(ttGen, uploadErrors);
                        AuthenticatorBean.getDaemonIdentity().logout();
                    }
                }
            }
        }
    }
    LOGGER.debug("Processing took {0} ms", System.currentTimeMillis() - startTime);

    return null;
}

From source file:de.zib.gndms.infra.system.GNDMSystemDirectory.java

@SuppressWarnings({ "OverloadedMethodsWithSameNumberOfParameters" })
public TaskAction newTaskAction(final EntityManager emParam, final String offerTypeKey)
        throws IllegalAccessException, InstantiationException, ClassNotFoundException {
    OfferType type = emParam.find(OfferType.class, offerTypeKey);
    TaskAction ta = taskActionPark.getInstance(type);
    ta.setUUIDGen(uuidGen);/*from  w ww .j a v a 2s .  c  om*/
    return ta;
}

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  ww . j  a va 2 s .c  om*/
    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();
    }
}