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:ViewAgentFeedback.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w w  w.java  2s . 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 {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    HttpSession hs = request.getSession();
    try {
        Login ln = (Login) hs.getAttribute("user");
        System.out.println("uid is -------" + ln);

        SessionFactory sf = util.NewHibernateUtil.getSessionFactory();
        Session ss = sf.openSession();

        Criteria cr1 = ss.createCriteria(AgentDetail.class);
        cr1.add(Restrictions.eq("uId", ln));
        ArrayList<AgentDetail> adl = (ArrayList<AgentDetail>) cr1.list();

        if (!adl.isEmpty()) {
            AgentDetail ad = adl.get(0);
            System.out.print("adl not empty and the aid is :" + ad.getAId());

            Criteria cr = ss.createCriteria(AgentFeedback.class);
            cr.add(Restrictions.eq("aId", ad));
            ArrayList<AgentFeedback> afL = (ArrayList<AgentFeedback>) cr.list();

            if (!afL.isEmpty()) {

                // HttpSession hs1=request.getSession();
                System.out.println("adl size:" + adl.size() + "afl size:" + afL.size());
                System.out.println("inside the servlet else");
                System.out.println("inside the servlet else11");

                request.setAttribute("afL", afL);
                System.out.println("inside the servlet else222");

            }
        }
        RequestDispatcher rd = request.getRequestDispatcher("myfeedback_sample.jsp");
        System.out.println("forwarding");
        rd.forward(request, response);

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

From source file:forgotpassword.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w  w w  .  j  av  a  2s.  com*/
 *
 * @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 {
        String mail = request.getParameter("mail");
        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session s = sf.openSession();
        Transaction tr = s.beginTransaction();

        Criteria c = s.createCriteria(Patient.class);
        c.add(Restrictions.eq("emailId", mail));
        ArrayList<Patient> al = (ArrayList<Patient>) c.list();

        String name = "";
        if (al.size() > 0) {
            Patient p = al.get(0);
            Login l = p.getUsedId();
            name = l.getPassword();

            //name=l.getPassword();
            System.out.println("---------------------" + name);
            String subject = "Forgot Password - Cardiac:";
            String content = "Your password" + name;

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

            if (new MailUtil().sendMail(recipients, subject, content)) {
                RequestDispatcher rd = request.getRequestDispatcher("forgetpassword_refresh.jsp");
                rd.forward(request, response);
            }
        } else {

            String msg = "plz enter the correct email";
            request.setAttribute("msg", msg);
            RequestDispatcher rd = request.getRequestDispatcher("forgotpassword.jsp");
            rd.forward(request, response);
        }
        tr.commit();
    } catch (HibernateException he) {
        out.println(he.getMessage());
    }
}

From source file:Loading.java

private void CargarHibernate(int x, String txt) {
    lblMsg.setText(txt);/*from  w ww.  j  ava  2s.  c o  m*/
    this.update(this.getGraphics());

    try {
        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session sesion = sf.openSession(); // Pruebo la conexion !!
    } catch (ExceptionInInitializerError e) {
        JOptionPane.showMessageDialog(this, "Error de Hibernate \n " + e.getException().getMessage(),
                "Error de Conexion", JOptionPane.ERROR_MESSAGE);
        e.printStackTrace();
        System.exit(1);
    } catch (NoClassDefFoundError e) {
        JOptionPane.showMessageDialog(this, "No se cargaron las libreras de Hibernate \n " + e.getMessage(),
                "Error de Conexion", JOptionPane.ERROR_MESSAGE);
        e.printStackTrace();
        System.exit(1);
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Error en la conexion a la base de datos \n " + e.getMessage(),
                "Error de Conexion", JOptionPane.ERROR_MESSAGE);
        e.printStackTrace();
        System.exit(1);
    }

    setProgress(jpb.getValue() + x);
    this.update(this.getGraphics());
}

From source file:getlab.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w  w  w.j a v a  2  s. 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();
        String code = "";

        Criteria cr = ss.createCriteria(Lab.class);
        ArrayList<Lab> all = (ArrayList<Lab>) cr.list();
        //            request.setAttribute("dlist", all);
        Criteria cr1 = ss.createCriteria(Lab.class);
        cr1.add(Restrictions.eq("status", "ACTIVE"));
        if (request.getParameter("sort") != null) {
            String so = request.getParameter("sort");
            if (so.equals("1")) {
                cr1.addOrder(Order.asc("labName"));
            } else if (so.equals("2")) {
                cr1.addOrder(Order.desc("labName"));
            }
            //.add( Restrictions.like("name", "F%")
            //.addOrder( Order.asc("name") )
            //.addOrder( Order.desc("age") )
            //.setMaxResults(50)

            //                cr.add(Restrictions.eq("password", request.getParameter("password")));
        }
        if (request.getParameter("search") != null) {
            String so = request.getParameter("search");
            cr1.add(Restrictions.like("labName", so + "%"));
        }
        ArrayList<Lab> all1 = (ArrayList<Lab>) cr1.list();
        if (all1.size() > 0) {
            for (int i = 0; i < all1.size(); i++) {
                Lab dd = all1.get(i);
                out.println("<li class=\"author-comments\" style=\"margin-top: 36px\">\n"
                        + "                                <div class=\"media\">\n"
                        + "                                    <div class=\"media-left\">    \n"
                        + "                                        <img alt=\"img\" src=\"images/Lab-Icon-245x300.png\" class=\"media-object news-img\">      \n"
                        + "                                    </div>\n"
                        + "                                    <div class=\"media-body\">\n"
                        + "                                        <h4 class=\"author-name\">" + dd.getLabName()
                        + "</h4>\n" + "                                        <a target='_blank' href='http://"
                        + dd.getWebsite() + "'> <span class=\"comments-date\">" + dd.getWebsite()
                        + "</span> </a>\n" + "                                        <p>"
                        + dd.getAddressid().getCityId().getCityName() + "</p>\n"
                        + "                                        <p class=\"fa fa-check-circle\" style=\"color: green\">"
                        + dd.getStatus() + "</p>\n"
                        + "                                        <div class=\"ui heart rating\" data-rating=\"1\" data-max-rating=\"3\"></div>\n"
                        + "                                        <a class=\"reply-btn\" href=\"take_test?labid="
                        + dd.getLId() + "\">Take Appointment</a>\n"
                        + "                                    </div>\n"
                        + "                                </div>\n" + "                            </li>");
            }

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

From source file:doc_view_patient_allreport.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w w  w .  ja v a2 s .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("pid") != null) {

                int pid = Integer.parseInt(request.getParameter("pid"));

                //                 Calculationmeteredata cal = (Calculationmeteredata) ss.get(Calculationmeteredata.class, pid);
                Criteria cr = ss.createCriteria(Calculationmeteredata.class);
                cr.add(Restrictions.eq("pId", new Patient(pid)));

                ArrayList<Calculationmeteredata> da = (ArrayList<Calculationmeteredata>) cr.list();
                if (da.size() > 0) {
                    request.setAttribute("da", da);
                }
                tr.commit();
                RequestDispatcher rd = request.getRequestDispatcher("doctor_view_system_report.jsp");
                rd.forward(request, response);

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

    } catch (HibernateException he) {
        out.println(he.getMessage());
    } finally {
        out.close();
    }
}

From source file:viewTask.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from ww  w . ja  v  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();
    String path = "";
    try {
        HttpSession hs = request.getSession();
        SessionFactory sf = NewHibernateUtil.getSessionFactory();
        Session ss = sf.openSession();
        Transaction tr = ss.beginTransaction();

        int userId = Integer.parseInt(hs.getAttribute("userId").toString());
        String page = request.getParameter("page").toString();
        LoginInfo user_id_to = new LoginInfo();
        user_id_to.setUserId(userId);

        Criteria cr = ss.createCriteria(TaskDetails.class);
        cr.add(Restrictions.eq("userIdTo", user_id_to));
        ArrayList<TaskDetails> TaskList = (ArrayList<TaskDetails>) cr.list();
        System.out.println(TaskList.size());

        int i = 0;
        UserInfo ui = null;
        Criteria cr1 = ss.createCriteria(UserInfo.class);
        ArrayList<UserInfo> uiList = new ArrayList<UserInfo>();
        for (i = 0; i < TaskList.size(); i++) {
            cr1.add(Restrictions.eq("userId", TaskList.get(i).getUserIdFrom()));
            System.out.println("criteria " + i);
            ui = (UserInfo) cr1.list().get(0);
            uiList.add(ui);
        }

        request.setAttribute("TaskList", TaskList);
        request.setAttribute("uiList", uiList);
        request.setAttribute("page", page);

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

    } catch (Exception e) {
        path = "FailureDRO.jsp";
        System.out.println(e.getMessage());
        RequestDispatcher rd = request.getRequestDispatcher(path);
        rd.forward(request, response);
    }
}

From source file:admin_add_doctors.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w ww.j av a  2  s  . 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("admin") != null) {
            Admin a = (Admin) hs.getAttribute("admin");

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

                int apid = Integer.parseInt(request.getParameter("dId"));
                Doctor doc1 = (Doctor) ss.get(Doctor.class, apid);
                if (request.getParameter("status").equals("approve")) {

                    doc1.setStatus("ACTIVE");

                    ss.update(doc1);

                    String subject = "Your Appointment is Approved.!";
                    String content = "Hi, Dr." + doc1.getDFirstname() + " " + doc1.getDLastname() + "\n"
                            + "Your Request has been approved by Admin" + ".\n";
                    String mail = doc1.getEmailId();

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

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

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

                } else if (request.getParameter("status").equals("reject")) {
                    doc1.setStatus("REJECTED");
                    ss.update(doc1);
                    String subject = "Your Request is Rejected.!";
                    String content = "Hi, " + doc1.getDFirstname() + " " + doc1.getDLastname()
                            + "Your Request to join Cardiac Countermeasure has been rejected by admin"
                            + ".\n anil ";
                    String mail = doc1.getEmailId();

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

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

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

            }

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

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

        out.println(he.getMessage());
    } finally {
        out.close();
    }
}

From source file:systemgeneratedreport.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  w  w  . j a va  2 s. com*/
 *
 * @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("patient") != null) {

            Patient p1 = (Patient) hs.getAttribute("patient");
            if (request.getParameter("calcid") != null) {

                int calcid = Integer.parseInt(request.getParameter("calcid"));

                Calculationmeteredata cm1 = (Calculationmeteredata) ss.get(Calculationmeteredata.class, calcid);
                String color = "red";

                if (cm1.getCalculationmeteredataId() != null) {

                    String gender = "MALE";
                    Criteria optcr = ss.createCriteria(PatientfactorAnswer.class);
                    optcr.add(Restrictions.eq("calculationmeteredataId", cm1));
                    ArrayList<PatientfactorAnswer> anslist = (ArrayList<PatientfactorAnswer>) optcr.list();
                    if (anslist.size() > 0) {

                        FactorOption agefac = new FactorOption();
                        for (PatientfactorAnswer opp : anslist) {
                            if (opp.getFactorId().equals(new FactorDetails(1))) {
                                if (opp.getFactorOptionId().getFoptionId().equals(16)) {
                                    gender = "FEMALE";
                                }
                                System.out.println("Gender is :" + gender + opp.getFactorOptionId());
                            }
                            if (opp.getFactorId().equals(new FactorDetails(2))) {
                                agefac = opp.getFactorOptionId();
                                System.out.println("Age is :" + agefac.getFactorOption());
                            }
                        }
                        if (gender.equals("MALE")) {
                            //                        Set Chart Data   
                            String[] chartdata = new String[4];
                            String[] rchartdata = new String[4];

                            Criteria cr01 = ss.createCriteria(AbsulateRiskMale.class);
                            cr01.add(Restrictions.eq("foptionid", agefac));
                            cr01.setProjection(Projections.max("green"));
                            if (cr01.uniqueResult() != null) {
                                chartdata[0] = cr01.uniqueResult().toString();
                                int cdata = Integer.parseInt(chartdata[0]);
                                if (cdata >= cm1.getMetervalue()) {
                                    color = "green";
                                }
                            }
                            Criteria cr02 = ss.createCriteria(AbsulateRiskMale.class);
                            cr02.add(Restrictions.eq("foptionid", agefac));
                            cr02.setProjection(Projections.max("violet"));
                            if (cr02.uniqueResult() != null) {
                                chartdata[1] = cr02.uniqueResult().toString();
                                int cdata = Integer.parseInt(chartdata[1]);
                                if (cdata >= cm1.getMetervalue()) {
                                    color = "violet";
                                }
                            }
                            System.out.println(chartdata[1]);
                            System.out.println(color);
                            Criteria cr03 = ss.createCriteria(AbsulateRiskMale.class);
                            cr03.add(Restrictions.eq("foptionid", agefac));
                            cr03.setProjection(Projections.max("yellow"));
                            if (cr03.uniqueResult() != null) {
                                chartdata[2] = cr03.uniqueResult().toString();
                                int cdata = Integer.parseInt(chartdata[2]);
                                if (cdata >= cm1.getMetervalue()) {
                                    color = "yellow";
                                }
                            }
                            chartdata[3] = "54";

                            //                                RchartData create
                            Criteria cr010 = ss.createCriteria(AbsulateRiskMale.class);
                            cr010.add(Restrictions.eq("foptionid", agefac));
                            cr010.setProjection(Projections.max("rGreen"));
                            if (cr010.uniqueResult() != null) {
                                rchartdata[0] = cr010.uniqueResult().toString();
                            }
                            Criteria cr020 = ss.createCriteria(AbsulateRiskMale.class);
                            cr020.add(Restrictions.eq("foptionid", agefac));
                            cr020.setProjection(Projections.max("rViolet"));
                            if (cr020.uniqueResult() != null) {
                                rchartdata[1] = cr020.uniqueResult().toString();

                            }
                            System.out.println(chartdata[1]);
                            System.out.println(color);
                            Criteria cr030 = ss.createCriteria(AbsulateRiskMale.class);
                            cr030.add(Restrictions.eq("foptionid", agefac));
                            cr030.setProjection(Projections.max("rYellow"));
                            if (cr030.uniqueResult() != null) {
                                rchartdata[2] = cr030.uniqueResult().toString();

                            }
                            rchartdata[3] = "30";

                            request.setAttribute("rchartdata", rchartdata);
                            request.setAttribute("chartdata", chartdata);

                        } else if (gender.equals("FEMALE")) {
                            //                        Set Chart Data   
                            String[] chartdata = new String[4];
                            String[] rchartdata = new String[4];

                            Criteria cr01 = ss.createCriteria(AbsoluteRiskFemale.class);
                            cr01.add(Restrictions.eq("foptionid", agefac));
                            cr01.setProjection(Projections.max("green"));
                            if (cr01.uniqueResult() != null) {
                                chartdata[0] = cr01.uniqueResult().toString();
                                int cdata = Integer.parseInt(chartdata[0]);
                                if (cdata >= cm1.getMetervalue()) {
                                    color = "green";
                                }
                            }
                            Criteria cr02 = ss.createCriteria(AbsoluteRiskFemale.class);
                            cr02.add(Restrictions.eq("foptionid", agefac));
                            cr02.setProjection(Projections.max("violet"));
                            if (cr02.uniqueResult() != null) {
                                chartdata[1] = cr02.uniqueResult().toString();
                                int cdata = Integer.parseInt(chartdata[1]);
                                if (cdata >= cm1.getMetervalue()) {
                                    color = "violet";
                                }
                            }
                            Criteria cr03 = ss.createCriteria(AbsoluteRiskFemale.class);
                            cr03.add(Restrictions.eq("foptionid", agefac));
                            cr03.setProjection(Projections.max("yellow"));
                            if (cr03.uniqueResult() != null) {
                                chartdata[2] = cr03.uniqueResult().toString();
                                int cdata = Integer.parseInt(chartdata[2]);
                                if (cdata >= cm1.getMetervalue()) {
                                    color = "yellow";
                                }
                            }
                            chartdata[3] = "30";

                            //                                RchartData create
                            Criteria cr010 = ss.createCriteria(AbsoluteRiskFemale.class);
                            cr010.add(Restrictions.eq("foptionid", agefac));
                            cr010.setProjection(Projections.max("rGreen"));
                            if (cr010.uniqueResult() != null) {
                                rchartdata[0] = cr010.uniqueResult().toString();
                            }
                            Criteria cr020 = ss.createCriteria(AbsoluteRiskFemale.class);
                            cr020.add(Restrictions.eq("foptionid", agefac));
                            cr020.setProjection(Projections.max("rViolet"));
                            if (cr020.uniqueResult() != null) {
                                rchartdata[1] = cr020.uniqueResult().toString();

                            }
                            System.out.println(chartdata[1]);
                            System.out.println(color);
                            Criteria cr030 = ss.createCriteria(AbsoluteRiskFemale.class);
                            cr030.add(Restrictions.eq("foptionid", agefac));
                            cr030.setProjection(Projections.max("rYellow"));
                            if (cr030.uniqueResult() != null) {
                                rchartdata[2] = cr030.uniqueResult().toString();

                            }
                            rchartdata[3] = "20";

                            request.setAttribute("rchartdata", rchartdata);
                            request.setAttribute("chartdata", chartdata);
                        }
                        Criteria testcr = ss.createCriteria(TestRecommend.class);
                        testcr.add(Restrictions.eq("color", color));
                        ArrayList<TestRecommend> tlist = (ArrayList<TestRecommend>) testcr.list();
                        if (tlist.size() > 0) {
                            request.setAttribute("testlist", tlist);
                        }

                        request.setAttribute("calcdata", cm1);
                        request.setAttribute("anslist", anslist);
                    }
                }
                tr.commit();
                RequestDispatcher rd = request.getRequestDispatcher("system_generated_report1.jsp");
                rd.forward(request, response);
            }
        }

        else {

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

From source file:submitaction.java

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

    String username = (String) session.getAttribute("username");
    String dpimage = (String) session.getAttribute("dpimage");

    if (username == null)
        response.sendRedirect("login.jsp");
    else {

        String problemcode = (String) request.getParameter("q");
        String contestcode = (String) request.getParameter("c");
        String contestpath = Path.getArgPath("contests", contestcode);
        String userpath = Path.getArgPath("users", username);

        /* =========================== user not registered : redirect to index page ====================*/
        Connection con = null;
        Config c = new Config();
        int check = 0;
        Timestamp sdate = null, edate = null, ts = null;
        try {

            con = c.getcon();
            Statement stmt7 = con.createStatement();
            Statement stmt8 = con.createStatement();

            String sq = "Select count(*) as col from " + contestcode + "ranking where userid='" + username
                    + "'";
            String sq2 = "Select * from ContestInfo where contestcode='" + contestcode + "'";
            ResultSet rs8 = stmt8.executeQuery(sq2);
            if (rs8.next()) {
                sdate = rs8.getTimestamp("starttime");
                edate = rs8.getTimestamp("endtime");
            }
            java.util.Date date = new java.util.Date();
            ts = new Timestamp(date.getTime());

            //out.println(sq);
            ResultSet rs7 = stmt7.executeQuery(sq);
            if (rs7.next())
                check = Integer.parseInt(rs7.getString("col"));

        } catch (Exception e) {
        }

        if (!(ts.compareTo(sdate) > 0 && ts.compareTo(edate) < 0))
            response.sendRedirect("contestshow.jsp?c=PRACTICE");
        else if (check == 0)
            response.sendRedirect("index.jsp?register=True");
        else {
            /* ========================== get browsefile or editorfile  ==================== */

            Part filePart = null;
            String browsefile = null, ext = null, editorfile = null, language = null;
            int l = 0;
            try {
                MultipartRequest m = new MultipartRequest(request, userpath);
                filePart = request.getPart("test2");
                browsefile = (String) m.getFilesystemName("test2");

                editorfile = (String) m.getParameter("test1");

                language = (String) m.getParameter("language");

                HashMap<String, String> map = new HashMap<String, String>();
                map.put("AWK", "awk");
                map.put("Bash", "sh");
                map.put("C++", "cpp");
                map.put("C", "c");
                map.put("C#", "cs");
                map.put("Java", "java");
                map.put("Haskell", "hs");
                map.put("Perl", "pl");
                map.put("Pike", "pike");
                map.put("Python2.7", "py");
                map.put("Python3", "py");
                map.put("PHP", "php");
                map.put("Pascal", "pas");
                map.put("Ruby", "rb");
                ext = (String) map.get(language);
                l = editorfile.length();
            } catch (Exception e) {
                out.print("hi");
                out.flush();
            }

            if (l == 0 && browsefile == null) {
                //no file selected 
                response.sendRedirect("submit.jsp?q=" + problemcode + "&c=" + contestcode);
            } else {

                BufferedReader br = null;
                BufferedWriter bout = null;

                SessionFactory factory = new ConnectionProvider().getSessionFactory();
                Session s = factory.openSession();
                String id = "", st = "";
                Query q = null;
                Object[] ob = null;
                Transaction t = null;
                /* ==================== unique name : get from id table ============= */

                try {

                    st = "FROM Id id";
                    q = s.createQuery(st);
                    List<Id> users = q.list();
                    ob = users.toArray();
                    int preid = ((Id) ob[0]).getId();
                    id = "" + (preid + 1);
                    t = s.beginTransaction();
                    s.delete((Id) ob[0]);
                    s.saveOrUpdate(new Id(preid + 1));
                    t.commit();
                } catch (Exception e) {
                }

                /* ================== rename filenames and create folder and copy files in env =========== */
                //out.print(browsefile);out.flush();
                String browsefilepath = userpath + browsefile;
                String problempath = Path.getArgPath("contests", contestcode, problemcode); // for stdin.txt

                String codefilename = "Main" + id;

                //       rename procedure
                File file = new File(browsefilepath);
                // File (or directory) with new name
                File file2 = new File(userpath + codefilename + "." + ext);
                // Rename file (or directory)
                boolean success = file.renameTo(file2);

                //creating new folder for each sumission in env dir.

                String envPath = Path.getArgPath("env", codefilename);
                File dir = new File(envPath);
                if (!dir.exists()) {
                    dir.mkdir();
                }

                // copy file to env folder inside mkdir folder
                String userfilepath = userpath + codefilename + "." + ext;
                envPath = envPath + ("Main" + id + "." + ext);

                try {

                    if (editorfile.length() != 0) {
                        //out.print("this running");
                        bout = new BufferedWriter(new FileWriter(userfilepath), 10000);
                        bout.write(editorfile);
                        bout.close();

                        bout = new BufferedWriter(new FileWriter(envPath), 10000);
                        bout.write(editorfile);
                        bout.close();

                    } else {
                        br = new BufferedReader(new FileReader(userfilepath));
                        bout = new BufferedWriter(new FileWriter(envPath), 10000);
                        String line = "";
                        while ((line = br.readLine()) != null) {
                            bout.write(line + "\n");
                            bout.flush();
                        }
                        bout.flush();
                        bout.close();
                        br.close();
                    }

                } catch (Exception e) {
                }

                /* ======================= Running judge now  | ranking update  | status update ============ */

                // out.print((String)m.getParameter("language"));out.flush();
                Problems now = null;
                Date d = null;
                try {
                    st = "FROM Problems S WHERE S.problemcode='" + (String) request.getParameter("q") + "'";
                    q = s.createQuery(st);
                    List<Problems> ques = q.list();
                    ob = ques.toArray();
                    now = (Problems) ob[0];
                    d = new Date();
                    //out.print(now.toString());out.flush();

                } catch (Exception e) {
                    out.print("msg1=" + e.getMessage());
                }

                try {
                    Timestamp tmp = new Timestamp(d.getTime());

                    //out.println(language);
                    Q queue = new Q(codefilename, username, language, ext, problempath, "unjudge",
                            Double.parseDouble(now.getTimelimit()), "null", tmp, 0, 0, contestcode, 0,
                            problemcode, now.getTestfiles());
                    //do the judge work ;
                    t = s.beginTransaction();
                    s.saveOrUpdate(queue);
                    t.commit();
                } catch (Exception ex) {
                    out.print("msg2=" + ex.getMessage());
                } finally {
                    s.close();
                    factory.close();
                }

                // Show exit code of process
                //         out.println("Procefdsfdsfdsss exited with code = ");
                try {

                    //judge the solution         
                    //out.print("judge process starts "); out.flush();
                    final String[] cmd = { "/bin/bash", "-c", "cd " + Path.getPath() + " ; python judge.py" };
                    Runtime.getRuntime().exec(cmd);
                    //p.waitFor();

                    // inner class to run process without wait  outside main thread
                    /*  new Thread(new Runnable() {
                           public void run() {
                             try
                             {
                                 Runtime.getRuntime().exec(cmd);
                                 //p.waitFor();
                             }catch(Exception e){}
                       }
                     }).start(); 
                            
                    */
                    String problemid = (String) request.getParameter("q");
                    response.sendRedirect(
                            "status.jsp?q=" + problemid + "&c=" + contestcode + "&code=" + codefilename);
                    /* int chk = 0;   
                     while(chk == 0)
                     {
                            Thread.sleep(1);   
                            String query="Select count(*) as ch , status from " + contestcode+"submissions where username='"+username + "' and codefilename='"+codefilename+"'";
                            //out.println(query);
                                   
                            String pid = ""+problemid.charAt(problemid.length()-1);
                            //out.println(query);
                            ResultSet rs = stmt.executeQuery(query);
                            if(rs.next()){
                                chk = Integer.parseInt(rs.getString("ch"));
                                if(chk == 0)
                                 continue;
                                        
                                out.print("<style>#loading{visibility: hidden;</style>");              
                                out.println(rs.getString("status"));
                                        
                                if(rs.getString("status").compareTo("Accepted")==0)
                                {
                                    String sq = "Select * from "+contestcode+"ranking where userid='"+username+"'";
                                    //out.println(sq);
                                    ResultSet rs6 = stmt6.executeQuery(sq);
                                    if(rs6.next())
                                    {
                                        //out.println("hhhdsffsdkbhn");
                                        if(rs6.getString(pid+"score").compareTo("0") == 0)
                                        {
                    query = "UPDATE "+contestcode+"ranking SET "+pid+"score=100.0, "+pid+"time="+tc+" where userid='"+username+"'"; 
                    //out.println(query);
                    stmt2.executeUpdate(query);
                                        }
                                    }
                                }
                                else{
                                    String sql = "Select * from "+contestcode+"ranking where userid='"+username+"'";
                                    //out.println(sql);
                                    ResultSet rs3 = stmt2.executeQuery(sql);
                                    if(rs3.next())
                                    {
                                        //out.println("hhhdsffsdkbhn");
                                        if(rs3.getString(pid+"score").compareTo("0") == 0)
                                        {
                    int penalty = Integer.parseInt(rs3.getString(pid+"penalty"));
                    penalty += 1;
                    query = "UPDATE "+contestcode+"ranking SET "+pid+"penalty="+penalty+" where userid='"+username+"'";
                     //out.println(query);
                    stmt3.executeUpdate(query);
                                        }
                                    }
                                                
                                }
                                        
                                String sql = "Select * from "+contestcode+"ranking where userid='"+username+"'";
                                ResultSet rs5 = stmt5.executeQuery(sql);
                                //out.println("hi"+nop);
                                int total_penalty = 0;
                                Double total_score=0.0;
                                long total_time = 0;
                                char ch='A';
                                if(rs5.next())
                                {
                                    //out.println(rs5.getString("Apenalty"));
                            
                                    for(int i=0;i<nop;i++,ch++)
                                    {
                                        //out.println(ch);
                                        total_penalty += Integer.parseInt(rs5.getString(ch+"penalty"));
                                        total_score += Double.parseDouble(rs5.getString(ch+"score"));
                                        total_time += Long.parseLong(rs5.getString(ch+"time"));
                                        //out.println(total_penalty+" "+total_score+" "+total_time);
                                    }
                                    //out.println("hello");
                                    total_time += total_penalty * 20000*60;
                                    //Timestamp nt = new Timestamp(total_time);
                                    query = "UPDATE "+contestcode+"ranking SET penalty="+total_penalty+", score="+total_score+", time="+total_time+" where userid='"+username+"'";
                                    //out.println(query);
                                    stmt4.executeUpdate(query);
                                    out.flush();
                                }
                            }
                     }//while
                    */
                    con.close();
                    //  response.sendRedirect("index.jsp");
                } catch (Exception e) {
                } finally {
                    out.close();
                }

                /*
                        
                    out.print("<style>#loading{visibility: hidden;</style>");
                }
                          
                */
            }
        } //inner else due to sendRedirect
    } //else due to sendRedirect
}

From source file:agentstatus.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w  ww  .  ja v a2 s  . 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();

        int id = Integer.parseInt(request.getParameter("id"));

        int agentid = Integer.parseInt(request.getParameter("aid"));

        // Touroperator to = (Touroperator)se.get(Touroperator.class, spid);

        AgentDetail ad = (AgentDetail) ss.get(AgentDetail.class, agentid);

        if (id == 0) {
            //Accepted
            out.print(agentid + "accepted");
            AgentDetail ad2 = new AgentDetail();
            ad2.setAAddress1(ad.getAAddress1());
            ad2.setAAddress2(ad.getAAddress2());
            ad2.setAArea(ad.getAArea());
            ad2.setACity(ad.getACity());
            ad2.setACompanyname(ad.getACompanyname());
            ad2.setADescription(ad.getADescription());
            ad2.setAEmail(ad.getAEmail());
            ad2.setAFname(ad.getAFname());
            ad2.setALname(ad.getALname());
            ad2.setAId(ad.getAId());
            ad2.setAImg(ad.getAImg());
            ad2.setANo(ad.getANo());
            ad2.setARating(ad.getARating());
            ad2.setAState(ad.getAState());
            ad2.setUId(ad.getUId());
            ad2.setAWorkx(ad.getAWorkx());
            ad2.setAStatus("Accepted");

            ss.evict(ad);
            ss.update(ad2);
            tr.commit();

        } else if (id == 1) {
            //Denied
            out.print(agentid + "denied");
            ss.delete(ad);
            tr.commit();

        }

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