Example usage for org.hibernate SessionFactory openSession

List of usage examples for org.hibernate SessionFactory openSession

Introduction

In this page you can find the example usage for org.hibernate SessionFactory openSession.

Prototype

Session openSession() throws HibernateException;

Source Link

Document

Open a Session .

Usage

From source file:lab_view_approved_appointment.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w ww.j  av  a2s .c om*/
 *
 * @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 {
    response.setContentType("text/html;charset=UTF-8");

    PrintWriter out = response.getWriter();

    try {

        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session ss = sf.openSession();
        Transaction tr = ss.beginTransaction();
        HttpSession hs = request.getSession();

        if (hs.getAttribute("lab") != null) {
            Lab a = (Lab) hs.getAttribute("lab");

            if (request.getParameter("status") != null && request.getParameter("appoid") != null) {

                int apid = Integer.parseInt(request.getParameter("appoid"));
                LabAppointment lab1 = (LabAppointment) ss.get(LabAppointment.class, apid);
                if (request.getParameter("status").equals("cancel")) {
                    lab1.setStatus("CANCELLED");
                    ss.update(lab1);
                    request.setAttribute("msg", "Appointment cancelled..!");
                } else if (request.getParameter("status").equals("update")) {
                    //                        doc1.setStatus("CANCELLED");
                    lab1.setDate(request.getParameter("apdate"));
                    lab1.setTime(request.getParameter("aptime"));
                    ss.update(lab1);
                    request.setAttribute("msg", "Appointment Updated..!");
                }

            }

            Criteria cr = ss.createCriteria(LabAppointment.class);
            cr.add(Restrictions.eq("lId", a));
            cr.add(Restrictions.eq("status", "APPROVED"));
            ArrayList<LabAppointment> da = (ArrayList<LabAppointment>) cr.list();
            if (da.size() > 0) {
                request.setAttribute("da", da);
            }

            tr.commit();
            RequestDispatcher rd = request.getRequestDispatcher("Lab_Approved_appointment.jsp");
            rd.forward(request, response);
        } else {
            tr.commit();
            RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
            rd.forward(request, response);
        }

    }

    catch (HibernateException he) {
        he.getMessage();
    }

    finally {
        out.close();
    }
}

From source file:agentfeedbacklist_serv.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w  ww  .  ja  va 2  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 {
        SessionFactory sf = NewHibernateUtil.getSessionFactory();
        Session ss = sf.openSession();
        Transaction tr = ss.beginTransaction();

        Criteria cr = ss.createCriteria(AgentFeedback.class);

        ArrayList<AgentFeedback> afl = (ArrayList<AgentFeedback>) cr.list();

        if (!afl.isEmpty()) {
            request.setAttribute("afl", afl);
            RequestDispatcher rd = request.getRequestDispatcher("agentfeedbacklist.jsp");
            rd.forward(request, response);
        }

    } catch (HibernateException e) {
        out.print(e.getMessage());
    }
}

From source file:saajResponse.java

private void saveEmployee(Employee e) {
    Configuration cfg = new Configuration();
    SessionFactory sessionFactory = cfg.configure().buildSessionFactory();
    Session session = sessionFactory.openSession();
    session.save(e);/* w ww. ja va  2 s  .c o m*/
    session.beginTransaction();
    session.persist(e);
    session.getTransaction().commit();
    System.out.println("Emplyoee saved");
}

From source file:doc_view_approved_appointment.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w  ww .  j  ava  2s.c o  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 {
    response.setContentType("text/html;charset=UTF-8");

    PrintWriter out = response.getWriter();

    try {

        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session ss = sf.openSession();
        Transaction tr = ss.beginTransaction();
        HttpSession hs = request.getSession();

        if (hs.getAttribute("doctor") != null) {
            Doctor a = (Doctor) hs.getAttribute("doctor");

            if (request.getParameter("status") != null && request.getParameter("appoid") != null) {

                int apid = Integer.parseInt(request.getParameter("appoid"));
                DoctorAppointment doc1 = (DoctorAppointment) ss.get(DoctorAppointment.class, apid);
                if (request.getParameter("status").equals("cancel")) {
                    doc1.setStatus("CANCELLED");
                    ss.update(doc1);

                    String subject = "Appointment Canceled.!";
                    String content = "Hi, " + doc1.getPId().getPFirstname() + " "
                            + "Your appointment has been Canceled by Dr." + doc1.getDId().getDFirstname()
                            + " due to some reasons and we are sorry for that kindly take new appointment ASAP."
                            + ".\n ";
                    String mail = doc1.getPId().getEmailId();

                    String[] recipients = new String[] { mail };
                    //String[] bccRecipients = new String[]{"sunilkotadiya777@gmail.com"};  

                    if (new MailUtil().sendMail(recipients, subject, content)) {

                    }
                    request.setAttribute("msg", "Appointment cancelled..!");
                } else if (request.getParameter("status").equals("update")) {
                    //                        doc1.setStatus("CANCELLED");
                    doc1.setDate(request.getParameter("apdate"));
                    doc1.setTime(request.getParameter("aptime"));
                    ss.update(doc1);

                    String subject = "Appointment time changed.!";
                    String content = "Hi, " + doc1.getPId().getPFirstname() + " "
                            + "Your appointment has been rescheduled by Dr." + doc1.getDId().getDFirstname()
                            + " due to some reasons kindly note new time" + "  " + "Date : " + doc1.getDate()
                            + "\n" + "Time : " + doc1.getTime() + "\n";
                    String mail = doc1.getPId().getEmailId();

                    String[] recipients = new String[] { mail };
                    //String[] bccRecipients = new String[]{"sunilkotadiya777@gmail.com"};  

                    if (new MailUtil().sendMail(recipients, subject, content)) {

                    }
                    request.setAttribute("msg", "Appointment Updated..!");
                }

            }

            Criteria cr = ss.createCriteria(DoctorAppointment.class);
            cr.add(Restrictions.eq("dId", a));
            cr.add(Restrictions.eq("status", "APPROVED"));
            ArrayList<DoctorAppointment> da = (ArrayList<DoctorAppointment>) cr.list();
            if (da.size() > 0) {
                request.setAttribute("da", da);
            }

            tr.commit();
            RequestDispatcher rd = request.getRequestDispatcher("doc_approved_appointment.jsp");
            rd.forward(request, response);
        } else {
            tr.commit();
            RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
            rd.forward(request, response);
        }

    } catch (HibernateException he) {
        he.getMessage();
    } finally {

        out.close();
    }
}

From source file:searchServ.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w w  w.  j  a v a2s .c o 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, Exception {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        String replaceText = request.getParameter("game_search");
        String replaced = replaceSpace(replaceText);
        //co-optimus scrape
        Document doc = Jsoup.connect("http://api.co-optimus.com/games.php?search=true&name=".concat(replaced))
                .get();
        String htmlString = doc.toString();
        doc = Jsoup.parse(htmlString, "", Parser.xmlParser());
        boolean foundOptimus = false;
        boolean foundCheapShark = false;

        Element span = doc.select("games > game > title").first();
        if (span != null) {
            System.out.println("exists!");
            foundOptimus = true;

            String title = doc.getElementsByTag("title").text();
            String genre = doc.getElementsByTag("genre").text();
            int local = Integer.parseInt(doc.getElementsByTag("local").text());
            int online = Integer.parseInt(doc.getElementsByTag("online").text());

            System.out.println(title + genre + local + online);
            //Cheapshark scrape 

            String normalPrice = "";
            String salePrice = "";
            String savings = "";
            int metacriticScore = 0;

            String urlString = ("http://www.cheapshark.com/api/1.0/deals?storeID=6&desc=0&title="
                    .concat(replaced).concat("&pageSize=5")).trim(); //just a string
            try {

                String jsonS = readUrl(urlString);
                JSONArray jsonA = new JSONArray(jsonS);
                if (jsonA.length() != 0) {
                    System.out.println("debug: inside for loop");
                    for (int i = 0; i < jsonA.length(); i++) {
                        if ((jsonA.getJSONObject(i).getString("title")).toLowerCase()
                                .equals(replaceText.toLowerCase())) {
                            normalPrice = jsonA.getJSONObject(i).getString("normalPrice");
                            salePrice = jsonA.getJSONObject(i).getString("salePrice");
                            savings = jsonA.getJSONObject(i).getString("savings");
                            metacriticScore = Integer
                                    .parseInt(jsonA.getJSONObject(i).getString("metacriticScore"));
                            foundCheapShark = true;
                        }
                    }
                } else {
                    //break exectution
                    System.out.println("no results found on cheapshark");
                }

                System.out.println(normalPrice);
                System.out.println(salePrice);
                System.out.println(savings);
                System.out.println(metacriticScore);

            } catch (JSONException e) {
                e.printStackTrace();
            }

            WishListItem wli = new WishListItem(title, genre, local, online, normalPrice, salePrice, savings,
                    metacriticScore);
            request.setAttribute("wish", wli);
            response.sendRedirect(request.getContextPath() + "/result.jsp");
            if (foundCheapShark) {
                //save search wli to database
                SessionFactory sf = HibernateUtil.getSessionFactory();
                Session session = sf.openSession();
                session.beginTransaction();

                if (gameExists(wli.getTitle()) == null) {
                    int id = (int) session.save(wli);
                    wli.setId(id);
                    session.getTransaction().commit();
                    session.close();
                    //RequestDispatcher rdp = request.getRequestDispatcher("/success.jsp");
                    //rdp.forward(request, response);
                } else {
                    //something about user already exists
                    //RequestDispatcher rdp = request.getRequestDispatcher("/fail.jsp");
                    //rdp.forward(request, response);
                    System.out.println("Game already exists in database!");
                }
            }
        } else {
            System.out.println("No game found on co-optimus");
        }
        //System.out.println("debug");

    }
}

From source file:searchServ.java

public static SystemUser gameExists(String gameName) {
    SessionFactory sf = HibernateUtil.getSessionFactory();
    Session session = sf.openSession();
    Criteria crit = session.createCriteria(WishListItem.class);
    Criterion cond1 = Restrictions.eq("title", gameName);
    crit.add(Restrictions.and(cond1));//from  w ww  .  j a v a  2s  .  com
    return (SystemUser) crit.uniqueResult();
}

From source file:agentlist_serv.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w  w  w. j a v a 2s .c o 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 {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        SessionFactory sf = NewHibernateUtil.getSessionFactory();
        Session ss = sf.openSession();
        Transaction tr = ss.beginTransaction();

        Criteria cr = ss.createCriteria(AgentDetail.class);

        ArrayList<AgentDetail> adl = (ArrayList<AgentDetail>) cr.list();

        if (!adl.isEmpty()) {
            request.setAttribute("adl", adl);
            RequestDispatcher rd = request.getRequestDispatcher("agentlist.jsp");
            rd.forward(request, response);
        }

    } catch (HibernateException e) {
        out.print(e.getMessage());
    }
}

From source file:lab_mytest.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w ww  .ja  v a  2s  .c  om
 *
 * @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 {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session ss = sf.openSession();
        Transaction tr = ss.beginTransaction();
        HttpSession hs = request.getSession();
        if (hs.getAttribute("lab") != null) {
            Lab lb = (Lab) hs.getAttribute("lab");

            if (request.getParameter("price") != null && request.getParameter("ltid") != null) {
                int ltid = Integer.parseInt(request.getParameter("ltid"));
                Double price = Double.parseDouble(request.getParameter("price"));
                Labtest lt = (Labtest) ss.get(Labtest.class, ltid);
                lt.setTestFees(price);
                ss.update(lt);
                request.setAttribute("msg", "Test price updated.!");
            }

            Criteria cr = ss.createCriteria(Labtest.class);
            cr.add(Restrictions.eq("lId", lb));
            ArrayList<Labtest> ltest = (ArrayList<Labtest>) cr.list();
            if (ltest.size() > 0) {
                request.setAttribute("ltest", ltest);
            }
            tr.commit();
            RequestDispatcher rd = request.getRequestDispatcher("lab_mytest.jsp");
            rd.forward(request, response);

        } else {
            tr.commit();
            RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
            rd.forward(request, response);
        }

    }
}

From source file:cust_update.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w  w w  . j  a v a 2s  . c o  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, FileUploadException {
    response.setContentType("text/html;charset=UTF-8");

    HttpSession hs = request.getSession();
    PrintWriter out = response.getWriter();
    try {

        if (hs.getAttribute("user") != null) {
            Login ln = (Login) hs.getAttribute("user");

            System.out.println(ln.getUId());
            String firstn = "";
            String lastn = "";
            String un = "";
            String state = "";
            String city = "";
            int id = 0;
            String e = "";

            String num = "";
            String p = "";
            String custphoto = "";
            String custname = "";
            String area = "";

            // creates FileItem instances which keep their content in a temporary file on disk
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);

            //get the list of all fields from request
            List<FileItem> fields = upload.parseRequest(request);
            // iterates the object of list
            Iterator<FileItem> it = fields.iterator();
            //getting objects one by one
            while (it.hasNext()) {
                //assigning coming object if list to object of FileItem
                FileItem fileItem = it.next();
                //check whether field is form field or not
                boolean isFormField = fileItem.isFormField();

                if (isFormField) {
                    //get the filed name 
                    String fieldName = fileItem.getFieldName();

                    if (fieldName.equals("fname")) {
                        firstn = fileItem.getString();
                        System.out.println(firstn);
                    } else if (fieldName.equals("id")) {
                        id = Integer.parseInt(fileItem.getString());
                    } else if (fieldName.equals("lname")) {
                        lastn = fileItem.getString();
                        System.out.println(lastn);
                    } else if (fieldName.equals("uname")) {
                        un = fileItem.getString();
                        System.out.println(un);
                    } else if (fieldName.equals("state")) {
                        state = fileItem.getString();
                        System.out.println(state);
                    } else if (fieldName.equals("city")) {
                        city = fileItem.getString();
                        System.out.println(city);
                    } else if (fieldName.equals("area")) {
                        area = fileItem.getString();
                    } else if (fieldName.equals("email")) {
                        e = fileItem.getString();
                        System.out.println(e);
                    }

                    else if (fieldName.equals("number")) {
                        num = fileItem.getString();
                        System.out.println(num);

                    } else if (fieldName.equals("pwd")) {
                        p = fileItem.getString();
                        System.out.println(p);
                    }

                } else {

                    //getting name of file
                    custphoto = new File(fileItem.getName()).getName();
                    //get the extension of file by diving name into substring
                    //  String extension=custphoto.substring(custphoto.indexOf(".")+1,custphoto.length());;
                    //rename file...concate name and extension
                    // custphoto=ln.getUId()+"."+extension;

                    System.out.println(custphoto);
                    try {

                        // FOR UBUNTU add GETRESOURCE  and GETPATH

                        String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/profilepic/";
                        // String filePath=  this.getServletContext().getResource("/images/profilepic").getPath()+"\\";
                        System.out.println("====" + fp);
                        fileItem.write(new File(fp + custphoto));
                    } catch (Exception ex) {
                        out.println(ex.toString());
                    }

                }

            }

            SessionFactory sf = NewHibernateUtil.getSessionFactory();
            Session ss = sf.openSession();
            Transaction tr = ss.beginTransaction();
            //            
            //             String op="";
            //                cr.add(Restrictions.eq("sId", Integer.parseInt(state)));
            //            ArrayList<StateMaster> ar = (ArrayList<StateMaster>)cr.list();
            //            if(ar.isEmpty()){
            //                
            //            }else{
            //                StateMaster sm = ar.get(0);
            //                op=sm.getSName();
            //                
            //            }

            CustomerDetail cd1 = (CustomerDetail) ss.get(CustomerDetail.class, id);
            System.out.println("cid is " + cd1.getCId());
            CustomerDetail cd = new CustomerDetail();

            cd.setUId(cd1.getUId());
            cd.setCId(cd1.getCId());
            cd.setCFname(firstn);
            cd.setCLname(lastn);
            cd.setCNum(num);
            cd.setCEmail(e);
            cd.setCState(state);
            cd.setCCity(city);
            cd.setCArea(area);
            cd.setCImg(custphoto);

            ss.evict(cd1);
            ss.update(cd);

            tr.commit();

            RequestDispatcher rd = request.getRequestDispatcher("customerprofile.jsp");
            rd.forward(request, response);

        }

    }

    catch (HibernateException e) {
        out.println(e.getMessage());
    }

}

From source file:SaveTransactionServ.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {/*from  w  w w .j a va  2s .c  o m*/

        String TransactionId = request.getParameter("txn_id");
        String grossAmount = request.getParameter("payment_gross");
        String paymentStatus = request.getParameter("payment_status");
        String orderId = request.getParameter("custom");

        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session ss = sf.openSession();
        Transaction tr = ss.beginTransaction();

        HttpSession hs = request.getSession();
        OrderDetails od = (OrderDetails) hs.getAttribute("OrderDetails");
        String path = "";
        if (paymentStatus.equals("Completed")) {
            System.out.println("Inside Iff Block");
            OrderDetails od2 = new OrderDetails();
            od2.setOrderId(od.getOrderId());
            od2.setAmount(od.getAmount());
            od2.setPid(od.getPid());
            od2.setQty(od.getQty());
            od2.setUserid(od.getUserid());
            od2.setTstatus("Success");

            ss.saveOrUpdate(od2);

            TransactionDetails td = new TransactionDetails();
            td.setTransactionID(request.getParameter("txn_id"));
            td.setStatus(paymentStatus);
            td.setOrderID(od2);
            ss.save(td);

            tr.commit();
            path = "PayPalResponse.jsp";
        } else {
            TransactionDetails td = new TransactionDetails();
            td.setTransactionID(request.getParameter("txn_id"));
            td.setTransactionID(paymentStatus);
            td.setOrderID(od);
            ss.save(td);

            tr.commit();
            path = "PaymentFailed.jsp";
        }

        RequestDispatcher rd = request.getRequestDispatcher(path);
        rd.forward(request, response);

    } catch (HibernateException e) {
        out.println(e.getMessage());

    }
}