Example #1
1
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {

    try {

      String target = ((HttpServletRequest) request).getRequestURI();

      HttpSession session = ((HttpServletRequest) request).getSession();

      if (session == null) {
        /* まだ認証されていない */
        session = ((HttpServletRequest) request).getSession(true);
        session.setAttribute("target", target);
        ((HttpServletResponse) response).sendRedirect("/refrigerator/LoginPage");
      } else {
        Object loginCheck = session.getAttribute("login");
        if (loginCheck == null) {
          /* まだ認証されていない */
          session.setAttribute("target", target);
          ((HttpServletResponse) response).sendRedirect("/refrigerator/LoginPage");
        }
      }

      chain.doFilter(request, response);

    } catch (ServletException se) {
    } catch (IOException e) {
    }
  }
  private void processReturn(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    Account principal = this.verifyResponse(req);

    // System.out.println(principal);

    String returnURL = req.getParameter("exist_return");

    if (principal == null) {
      // this.getServletContext().getRequestDispatcher("/openid/login.xql").forward(req, resp);
      resp.sendRedirect(returnURL);
    } else {
      HttpSession session = req.getSession(true);

      // ((XQueryURLRewrite.RequestWrapper)req).setUserPrincipal(principal);

      Subject subject = new Subject();

      // TODO: hardcoded to jetty - rewrite
      // *******************************************************
      DefaultIdentityService _identityService = new DefaultIdentityService();
      UserIdentity user = _identityService.newUserIdentity(subject, principal, new String[0]);

      Authentication cached = new HttpSessionAuthentication(session, user);
      session.setAttribute(HttpSessionAuthentication.__J_AUTHENTICATED, cached);
      // *******************************************************

      resp.sendRedirect(returnURL);
    }
  }
Example #3
0
  /**
   * Parse the case id from the url and then delete it. Finally redirects the response and the
   * request to admCase.jsp
   *
   * @see DatabaseMethods#caseDelete(int)
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    DatabaseMethods dbPoint = new DatabaseMethods();
    HttpSession userSession = request.getSession();

    if (Integer.parseInt(userSession.getAttribute("isadmin").toString()) == 1) {
      int caseId = Integer.parseInt(request.getParameter("caseId"));

      int success = dbPoint.caseDelete(caseId);

      if (success != 0) {
        userSession.setAttribute("caseDelete", "1");
      } else {
        userSession.setAttribute("caseDelete", "0");
      }
    }
    RequestDispatcher rd = getServletContext().getRequestDispatcher("/admCase.jsp");
    if (rd != null) {
      rd.forward(request, response);
    }
  }
Example #4
0
  /**
   * Validates the login. Writes the isValid flag into the session along with the current user.
   *
   * @return true if OK, false if there's a problem
   */
  private boolean validateLogin(
      HttpSession session, HttpServletRequest req, HttpServletResponse res) throws Exception {

    // Creates a user database access bean.
    UserManager userManager = new UserManager();
    // (no setSession() here, since user may not exist yet)

    // Validates the login
    String username = req.getParameter("Username");
    String password = req.getParameter("Password");
    boolean isValid = userManager.isValidUser(username, password);
    boolean isAdmin = userManager.isAdmin(username);

    // To allow bootstrapping the system, if there are no users
    // yet, set this session valid, and grant admin privileges.
    if (userManager.getRecords().isEmpty()) {
      isValid = true;
      isAdmin = true;
    }

    if (isValid) {
      // Writes User object and validity flag to the session
      session.setAttribute("user", new User(username, password, isAdmin));
      session.setAttribute("isValid", new Boolean(isValid));
    } else {
      Util.putMessagePage(res, "Invalid user or password");
      return false;
    }
    return isValid;
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    try {

      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

      /*String n=request.getParameter("username");
      out.print("Welcome "+n);*/

      String name = request.getParameter("name");
      String dob = request.getParameter("dob");
      String address = request.getParameter("address");
      String email = request.getParameter("email");
      HttpSession session = request.getSession(true);
      String userid = (String) session.getAttribute("theName");
      int AccNo = 0;
      String AccMsg = "";

      DbCommunication db_comm = new DbCommunication();
      AccNo = db_comm.accountCreation(name, dob, address, email, userid);
      // db_comm.accountCreation(name,email);
      AccMsg = "Account created successfully. Account number is:" + AccNo;
      // out.println(AccMsg);

      String redirectURL = "accountCreationPage.jsp";
      response.sendRedirect(redirectURL);
      session.setAttribute("AccCreationalMsgStatus", "set");
      session.setAttribute("AccCreationalMsg", AccMsg);

    } catch (Exception e) {
      System.out.println(e);
    }
  }
Example #6
0
 public Integer setSession(HttpSession ses) {
   Integer count = (Integer) ses.getAttribute("Counter");
   if (count != null) {
     ses.setAttribute("Counter", ++count);
     return count + 1;
   } else {
     ses.setAttribute("Counter", 1);
     return 1;
   }
 }
  public static void afterRoot(
      FacesContext context, HttpServletRequest req, HttpServletResponse res) {
    HttpSession session = ((HttpServletRequest) req).getSession(false);

    if (session != null)
      session.setAttribute(ViewHandler.CHARACTER_ENCODING_KEY, res.getCharacterEncoding());
  }
Example #8
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // POST method only used for tracked login operation
    HttpSession session = request.getSession();
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();

    // Get the username and password from request
    String username = request.getParameter("id");
    String password = request.getParameter("pwd");

    Long id = 0L;
    try {
      id = Long.parseLong(username);
    } catch (Exception ex) {
    }

    if (username != null && password != null) {
      // Login into tracked system
      CTracked ctracked = db.loginTrackedFromMobile(id, password).getResult();

      if (ctracked != null) {
        // Login successful
        out.print("OK," + ctracked.getUsername());
        session.setAttribute("device_id", ctracked.getUsername());
        log.info(ctracked + " : logined!");
      }
    }
  }
Example #9
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Session Tracking Example";
    HttpSession session = request.getSession(true);
    String heading;

    Integer accessCount = (Integer) session.getAttribute("accessCount");

    if (accessCount == null) {
      accessCount = new Integer(0);
      heading = "Welcome, Newcomer";
    } else {
      heading = "Welcome Back";
      accessCount = new Integer(accessCount.intValue() + 1);
    }

    session.setAttribute("accessCount", accessCount);
    out.println(
        "<BODY BGCOLOR=\"#FDF5E6\">\n"
            + "<H1 ALIGN=\"CENTER\">"
            + heading
            + "</H1>\n"
            + "<H2>Information on Your Session:</H2>\n"
            + "<TABLE BORDER=1 ALIGN=\"CENTER\">\n"
            + "<TR BGCOLOR=\"#FFAD00\">\n"
            + "  <TH>Info Type<TH>Value\n"
            + "<TR>\n"
            + "  <TD>ID\n"
            + "  <TD>"
            + session.getId()
            + "\n"
            + "<TR>\n"
            + "  <TD>Creation Time\n"
            + "  <TD>"
            + new Date(session.getCreationTime())
            + "\n"
            + "<TR>\n"
            + "  <TD>Time of Last Access\n"
            + "  <TD>"
            + new Date(session.getLastAccessedTime())
            + "\n"
            + "<TR>\n"
            + "  <TD>Number of Previous Accesses\n"
            + "  <TD>"
            + accessCount
            + "\n"
            + "</TR>"
            + "</TABLE>\n");

    // the following two statements show how to retrieve parameters in
    // the request.  The URL format is something like:
    // http://localhost:8080/project2/servlet/ShowSession?myname=Chen%20Li
    String myname = request.getParameter("myname");
    if (myname != null) out.println("Hey " + myname + "<br><br>");

    out.println("</BODY></HTML>");
  }
Example #10
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter writer = response.getWriter();
    HttpSession session = request.getSession();

    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String type = request.getParameter("type");
    System.out.println(username + password + type);

    session.setAttribute("user", username);

    try {
      writer.println("<html>");
      writer.println("<body bgcolor=green>");
      writer.println("<center>");
      ps.setString(1, username);
      ps.setString(2, password);
      ps.setString(3, type);
      ResultSet rs = ps.executeQuery();

      if (rs.next()) {
        writer.println("<h1>LOGIN SUCCESSFUL</h1><br><br>");
        writer.println("<a href=account.html>click here to see your account</a>");
      } else {
        writer.println("<h1>LOGIN FAILED</h1><br><br>");
        writer.println("<a href=login.html>click here to login again</a>");
      }
      writer.println("</center>");
      writer.println("</body>");
      writer.println("</html>");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    String amount = request.getParameter("amount");
    String amount2 = request.getParameter("amount2");
    String amount3 = request.getParameter("amount3");
    Integer posotita = Integer.parseInt(amount);
    Integer posotita2 = Integer.parseInt(amount2);
    Integer posotita3 = Integer.parseInt(amount3);

    HttpSession session = request.getSession();

    if (session.isNew()) {
      request.setAttribute("sessionVal", "this is a new session");
    } else {
      request.setAttribute("sessionVal", "Welcome Back!");
    }

    double total = ((posotita * 18.50) + (posotita2 * 6.95) + (posotita3 * 1.29));
    session.setAttribute("totalVal", total);

    request.setAttribute("currency", total);
    request.setAttribute("from", amount);
    request.setAttribute("from2", amount2);
    request.setAttribute("from3", amount3);

    RequestDispatcher view = request.getRequestDispatcher("index.jsp");
    view.forward(request, response);
  }
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // get a connection
    ConnectionPool pool = ConnectionPool.getInstance();
    Connection connection = pool.getConnection();

    String sqlStatement = request.getParameter("sqlStatement");
    String sqlResult = "";
    try {
      // create a statement
      Statement statement = connection.createStatement();

      // parse the SQL string
      sqlStatement = sqlStatement.trim();
      if (sqlStatement.length() >= 6) {
        String sqlType = sqlStatement.substring(0, 6);
        if (sqlType.equalsIgnoreCase("select")) {
          // create the HTML for the result set
          ResultSet resultSet = statement.executeQuery(sqlStatement);
          sqlResult = SQLUtil.getHtmlTable(resultSet);
          resultSet.close();
        } else {
          int i = statement.executeUpdate(sqlStatement);
          if (i == 0) {
            sqlResult = "<p>The statement executed successfully.</p>";
          } else { // an INSERT, UPDATE, or DELETE statement
            sqlResult = "<p>The statement executed successfully.<br>" + i + " row(s) affected.</p>";
          }
        }
      }
      statement.close();
      connection.close();
    } catch (SQLException e) {
      sqlResult = "<p>Error executing the SQL statement: <br>" + e.getMessage() + "</p>";
    } finally {
      pool.freeConnection(connection);
    }

    HttpSession session = request.getSession();
    session.setAttribute("sqlResult", sqlResult);
    session.setAttribute("sqlStatement", sqlStatement);

    String url = "/index.jsp";
    getServletContext().getRequestDispatcher(url).forward(request, response);
  }
Example #13
0
  public static void showSession(HttpServletRequest req, HttpServletResponse res, PrintStream out) {

    // res.setContentType("text/html");

    // Get the current session object, create one if necessary
    HttpSession session = req.getSession();

    // Increment the hit count for this page. The value is saved
    // in this client's session under the name "snoop.count".
    Integer count = (Integer) session.getAttribute("snoop.count");
    if (count == null) {
      count = 1;
    } else count = count + 1;
    session.setAttribute("snoop.count", count);

    out.println(HtmlWriter.getInstance().getHtmlDoctypeAndOpenTag());
    out.println("<HEAD><TITLE>SessionSnoop</TITLE></HEAD>");
    out.println("<BODY><H1>Session Snoop</H1>");

    // Display the hit count for this page
    out.println(
        "You've visited this page " + count + ((!(count.intValue() != 1)) ? " time." : " times."));

    out.println("<P>");

    out.println("<H3>Here is your saved session data:</H3>");
    Enumeration atts = session.getAttributeNames();
    while (atts.hasMoreElements()) {
      String name = (String) atts.nextElement();
      out.println(name + ": " + session.getAttribute(name) + "<BR>");
    }

    out.println("<H3>Here are some vital stats on your session:</H3>");
    out.println("Session id: " + session.getId() + " <I>(keep it secret)</I><BR>");
    out.println("New session: " + session.isNew() + "<BR>");
    out.println("Timeout: " + session.getMaxInactiveInterval());
    out.println("<I>(" + session.getMaxInactiveInterval() / 60 + " minutes)</I><BR>");
    out.println("Creation time: " + session.getCreationTime());
    out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>");
    out.println("Last access time: " + session.getLastAccessedTime());
    out.println("<I>(" + new Date(session.getLastAccessedTime()) + ")</I><BR>");

    out.println(
        "Requested session ID from cookie: " + req.isRequestedSessionIdFromCookie() + "<BR>");
    out.println("Requested session ID from URL: " + req.isRequestedSessionIdFromURL() + "<BR>");
    out.println("Requested session ID valid: " + req.isRequestedSessionIdValid() + "<BR>");

    out.println("<H3>Test URL Rewriting</H3>");
    out.println("Click <A HREF=\"" + res.encodeURL(req.getRequestURI()) + "\">here</A>");
    out.println("to test that session tracking works via URL");
    out.println("rewriting even when cookies aren't supported.");

    out.println("</BODY></HTML>");
  }
Example #14
0
 public void doPost(HttpServletRequest req, HttpServletResponse res)
     throws IOException, ServletException {
   HttpSession session = req.getSession(false);
   ServletContext sc = getServletContext();
   RequestDispatcher rd;
   String strPrizeID = req.getParameter("prizeid");
   if (strPrizeID != null) {
     DataBaseConn DelPrizeDBC = new DataBaseConn();
     String sqlStr = "delete from pthwinnum where id='" + Integer.parseInt(strPrizeID) + "';";
     DelPrizeDBC.execute(sqlStr);
     DelPrizeDBC.connCloseUpdate();
   }
   PageInfoGet objPageInfoGet = new PageInfoGet();
   String strChSql = "select id from pthwinnum";
   objPageInfoGet.generInfo(req, "pthwinnum", strChSql);
   session.setAttribute("userpc", objPageInfoGet.getUserPageConn());
   session.setAttribute("bepagshow", objPageInfoGet.getBeanPageShow());
   rd = sc.getRequestDispatcher("/WEB-INF/usermanage/pth/pthprizepage.jsp");
   rd.forward(req, res);
 }
 public void doPost(HttpServletRequest req, HttpServletResponse res)
     throws IOException, ServletException {
   String uID = req.getParameter("email");
   String pass = req.getParameter("password");
   if (validate(uID, pass)) {
     System.out.println("Valid");
     HttpSession sess = req.getSession();
     String type = getType();
     sess.setAttribute("Name", getName());
     sess.setAttribute("Type", type);
     sess.setAttribute("uID", uID);
     res.sendRedirect("/loginCheck");
   } else {
     PrintWriter out = res.getWriter();
     out.println("<script type=\"text/javascript\">");
     out.println("alert('Invalid Details. Please Try Again.');");
     out.println("window.location = '/loginCheck';");
     out.println("</script>");
   }
 }
Example #16
0
 /** Get an unused ID string for storing an object in the session */
 protected String getNewSessionObjectId() {
   HttpSession session = getSession();
   synchronized (session) {
     Integer id = (Integer) getSession().getAttribute(SESSION_KEY_OBJECT_ID);
     if (id == null) {
       id = new Integer(1);
     }
     session.setAttribute(SESSION_KEY_OBJECT_ID, new Integer(id.intValue() + 1));
     return id.toString();
   }
 }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    HttpSession session = request.getSession();

    String name = request.getParameter("name");
    String ID = request.getParameter("ID");
    String email = request.getParameter("email");
    String password = request.getParameter("password");
    String position = request.getParameter("position");

    try {
      MD5Util.addNewStaff(name, Integer.parseInt(ID), email, password, position);
      session.setAttribute("AddStaff", "Yes");
    } catch (Exception e) {
      session.setAttribute("AddStaff", "No");
    }

    response.sendRedirect("/library/people.jsp");
  }
  /**
   * this is the main method of the servlet that will service all get requests.
   *
   * @param request HttpServletRequest
   * @param responce HttpServletResponce
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = null;
    try {
      try {
        session = request.getSession(true);
      } catch (Exception e) {
        Log.error(e, "PingSession2.doGet(...): error getting session");
        // rethrow the exception for handling in one place.
        throw e;
      }

      // Get the session data value
      Integer ival = (Integer) session.getAttribute("sessiontest.counter");
      // if there is not a counter then create one.
      if (ival == null) {
        ival = new Integer(1);
      } else {
        ival = new Integer(ival.intValue() + 1);
      }
      session.setAttribute("sessiontest.counter", ival);
      // if the session count is equal to five invalidate the session
      if (ival.intValue() == 5) {
        session.invalidate();
      }

      try {
        // Output the page
        response.setContentType("text/html");
        response.setHeader("SessionTrackingTest-counter", ival.toString());

        PrintWriter out = response.getWriter();
        out.println(
            "<html><head><title>Session Tracking Test 2</title></head><body><HR><BR><FONT size=\"+2\" color=\"#000066\">HTTP Session Test 2: Session create/invalidate <BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time: "
                + initTime
                + "</FONT><BR><BR>");
        hitCount++;
        out.println(
            "<B>Hit Count: " + hitCount + "<BR>Session hits: " + ival + "</B></body></html>");
      } catch (Exception e) {
        Log.error(e, "PingSession2.doGet(...): error getting session information");
        // rethrow the exception for handling in one place.
        throw e;
      }

    } catch (Exception e) {
      // log the excecption
      Log.error(e, "PingSession2.doGet(...): error.");
      // set the server responce to 500 and forward to the web app defined error page
      response.sendError(500, "PingSession2.doGet(...): error. " + e.toString());
    }
  } // end of the method
Example #19
0
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    response.setContentType("text/html;charset=windows-1252");
    /* set up the intrinsic variables using the pageContext goober:
     ** session = HttpSession
     ** application = ServletContext
     ** out = JspWriter
     ** page = this
     ** config = ServletConfig
     ** all session/app beans declared in globals.jsa
     */
    PageContext pageContext =
        JspFactory.getDefaultFactory()
            .getPageContext(this, request, response, null, true, JspWriter.DEFAULT_BUFFER, true);
    // Note: this is not emitted if the session directive == false
    HttpSession session = pageContext.getSession();
    if (pageContext.getAttribute(OracleJspRuntime.JSP_REQUEST_REDIRECTED, PageContext.REQUEST_SCOPE)
        != null) {
      pageContext.setAttribute(
          OracleJspRuntime.JSP_PAGE_DONTNOTIFY, "true", PageContext.PAGE_SCOPE);
      JspFactory.getDefaultFactory().releasePageContext(pageContext);
      return;
    }
    int __jsp_tag_starteval;
    ServletContext application = pageContext.getServletContext();
    JspWriter out = pageContext.getOut();
    _mainMib page = this;
    ServletConfig config = pageContext.getServletConfig();

    try {
      // global beans
      // end global beans

      /*@lineinfo:user-code*/
      /*@lineinfo:1^1*/
      session.setAttribute("ip", request.getParameter("ip"));

      /*@lineinfo:generated-code*/
      out.write(__oracle_jsp_text[0]);

    } catch (Throwable e) {
      try {
        if (out != null) out.clear();
      } catch (Exception clearException) {
      }
      pageContext.handlePageException(e);
    } finally {
      OracleJspRuntime.extraHandlePCFinally(pageContext, false);
      JspFactory.getDefaultFactory().releasePageContext(pageContext);
    }
  }
Example #20
0
  /** @service the servlet service request. called once for each servlet request. */
  public void service(HttpServletRequest servReq, HttpServletResponse servRes) throws IOException {
    String name;
    String value[];
    String val;

    servRes.setHeader("AUTHORIZATION", "user fred:mypassword");
    ServletOutputStream out = servRes.getOutputStream();

    HttpSession session = servReq.getSession(true);
    session.setAttribute("timemilis", new Long(System.currentTimeMillis()));
    if (session.isNew()) {
      out.println("<p> Session is new ");
    } else {
      out.println("<p> Session is not new ");
    }
    Long l = (Long) session.getAttribute("timemilis");
    out.println("<p> Session id = " + session.getId());
    out.println("<p> TimeMillis = " + l);

    out.println("<H2>Servlet Params</H2>");
    Enumeration e = servReq.getParameterNames();
    while (e.hasMoreElements()) {
      name = (String) e.nextElement();
      value = servReq.getParameterValues(name);
      out.println(name + " : ");
      for (int i = 0; i < value.length; ++i) {
        out.println(value[i]);
      }
      out.println("<p>");
    }

    out.println("<H2> Request Headers : </H2>");
    e = servReq.getHeaderNames();
    while (e.hasMoreElements()) {
      name = (String) e.nextElement();
      val = (String) servReq.getHeader(name);
      out.println("<p>" + name + " : " + val);
    }
    try {
      BufferedReader br = servReq.getReader();
      String line = null;
      while (null != (line = br.readLine())) {
        out.println(line);
      }
    } catch (IOException ie) {
      ie.printStackTrace();
    }

    session.invalidate();
  }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = request.getSession(false);
    if (session == null) {
      response.sendRedirect("login.html");
      return;
    }

    String userName = (String) session.getAttribute("userName");
    if (isMissing(userName)) {
      response.sendRedirect("login.html");
      return;
    }
    String title = request.getParameter("title");
    String link = request.getParameter("link");
    String description = request.getParameter("description");
    session.setAttribute("title", title);
    session.setAttribute("link", link);
    session.setAttribute("description", description);
    String address = "WEB-INF/view/SaveBookmarkPage.jsp";
    String urlEncoding = response.encodeURL(address);
    RequestDispatcher dispatcher = request.getRequestDispatcher(urlEncoding);
    dispatcher.forward(request, response);
  }
Example #22
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    if (request.getParameter("save") != null) {
      User newUser = new User(request.getParameter("login"), request.getParameter("password"));
      if (BaseUser.addUser(newUser)) {
        HttpSession sessions = request.getSession();
        sessions.setAttribute("userSession", newUser);
        this.forward("/successRegistration.jsp", request, response);
      } else {
        this.forward("/errorRegistration.html", request, response);
      }
    } else if (request.getParameter("cancel") != null) {
      this.forward("/login.jsp", request, response);
    }
  }
Example #23
0
 /** Get the ID with which the object is associated with the session, if any */
 protected String getSessionObjectId(Object obj) {
   HttpSession session = getSession();
   BidiMap map;
   synchronized (session) {
     map = (BidiMap) session.getAttribute(SESSION_KEY_OBJ_MAP);
     if (map == null) {
       map = new DualHashBidiMap();
       session.setAttribute(SESSION_KEY_OBJ_MAP, map);
     }
   }
   synchronized (map) {
     String id = (String) map.get(obj);
     if (id == null) {
       id = getNewSessionObjectId();
       map.put(obj, id);
     }
     return id;
   }
 }
  /**
   * Handles HTTP GET requests.
   *
   * @param request Description of the Parameter
   * @param response Description of the Parameter
   * @exception ServletException if there is a Servlet failure
   * @exception IOException if there is an IO failure
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    HttpSession session = request.getSession();

    Integer sessionCounter = (Integer) session.getAttribute("project4SessionCounter");

    if (sessionCounter == null) {
      Integer newCounter = new Integer(1);
      sessionCounter = newCounter;
    } else {
      sessionCounter++;
    }
    session.setAttribute("project4SessionCounter", sessionCounter);

    String url = "/project4Session.jsp";

    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);

    dispatcher.forward(request, response);
  }
 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   // I use "session" in order to throws the object named user bean.
   HttpSession session = request.getSession(true);
   response.setContentType("text/html");
   request.setCharacterEncoding("UTF-8");
   UserBean ub = (UserBean) session.getAttribute("user");
   if (ub == null) {
     String haveLogin = "******";
     session.setAttribute("haveLogin", haveLogin);
     response.sendRedirect("cart");
   } else {
     String mID = ub.getmID();
     String iID = (String) request.getParameter("iID");
     // String idx = (String)request.getParameter("idx");
     Connection conn = null;
     try {
       // Getting the connection from database.
       Class.forName("com.mysql.jdbc.Driver");
       /*conn = DriverManager
       .getConnection("jdbc:mysql://localhost/se?"
       		+ "user=root");*/
       conn =
           DriverManager.getConnection(
               "jdbc:mysql://localhost/user_register?"
                   + "user=sqluser&password=sqluserpw&useUnicode=true&characterEncoding=UTF-8");
       String sql = "delete from cart_item_mapping where mID=? and iID = ?";
       PreparedStatement pst = conn.prepareStatement(sql);
       // Using preparedstatement by set the parameter related to "?" symbol.
       pst.setString(1, mID);
       pst.setString(2, iID);
       pst.executeUpdate();
       pst.close();
       response.sendRedirect("ShowCartController");
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
  public boolean convalida() {
    boolean tuttoOk = true;
    Map<String, String> errori = new HashMap<String, String>();

    if ((nome == null) || nome.equals("")) {
      tuttoOk = false;
      request.setAttribute("nome", nome);
      errori.put("nome", "campo obbligatorio");
    }

    if ((descrizione == null) || descrizione.equals("")) {
      tuttoOk = false;
      request.setAttribute("descrizione", descrizione);
      errori.put("descrizione", "campo obbligatorio");
    }

    if ((codice == null) || codice.equals("")) {
      tuttoOk = false;
      request.setAttribute("codice", codice);
      errori.put("codice", "campo obbligatorio");
    }

    if (!isInteger(disponibilita)) {
      tuttoOk = false;
      request.setAttribute("disponibilita", disponibilita);
      errori.put("disponibilita", "formato non valido");
    }

    if (!isInteger(prezzo)) {
      tuttoOk = false;
      request.setAttribute("prezzo", prezzo);
      errori.put("prezzo", "formato non valido");
    }
    if (!tuttoOk) request.setAttribute("errori", errori);
    HttpSession sess = request.getSession();
    sess.setAttribute("errori", errori);
    return tuttoOk;
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {

    try {
      UserBean user = new UserBean();
      user.setType("getfrozen");
      if (request.getParameter("sort") != null) {
        String sort = (String) request.getParameter("sort");
        if (sort.equals("namabarang")) {
          user.setQuery("SELECT * FROM Barang WHERE Kategori = 'Frozen Food' order by NamaBarang");
        } else if (sort.equals("harga")) {
          user.setQuery("SELECT * FROM Barang WHERE Kategori = 'Frozen Food' order by Harga");
        } else if (sort.equals("urutkan")) {
          user.setQuery("SELECT * FROM Barang WHERE Kategori = 'Frozen Food'");
        }
      } else {
        user.setQuery("SELECT * FROM Barang WHERE Kategori = 'Frozen Food'");
      }
      user = UserDAO.login(user);
      ArrayList<Barang> frozenes = new ArrayList<Barang>();
      frozenes = user.getfrozen();
      HttpSession session = request.getSession(true);
      session.setAttribute("jumlahfrozen", frozenes.size());
      for (int i = 0; i < frozenes.size(); i++) {
        String bnama = "fnama" + (i + 1);
        String bid = "fid" + (i + 1);
        String bharga = "fharga" + (i + 1);
        String bkategori = "fkategori" + (i + 1);
        String bjumlah = "fjumlah" + (i + 1);
        session.setAttribute(bnama, frozenes.get(i).getNama());
        session.setAttribute(bid, frozenes.get(i).getId());
        session.setAttribute(bharga, frozenes.get(i).getHarga());
        session.setAttribute(bkategori, frozenes.get(i).getKategori());
        session.setAttribute(bjumlah, frozenes.get(i).getJumlah());
      }

      response.sendRedirect("Frozen.jsp?f=1&l=10");
    } catch (Throwable theException) {
      System.out.println(theException);
    }
  }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<br><h4>we are getting data</h4>");
    String code = request.getParameter("code");
    out.println("<br>code: " + code);
    out.println("<br>");
    try {
      OAuthClientRequest requestOAuth =
          OAuthClientRequest.tokenLocation("https://graph.facebook.com/oauth/access_token")
              .setGrantType(GrantType.AUTHORIZATION_CODE)
              .setClientId(apiKey)
              .setClientSecret(secretKey)
              .setRedirectURI(redirectUri)
              .setCode(code)
              .buildBodyMessage();

      OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());

      GitHubTokenResponse oAuthResponse =
          oAuthClient.accessToken(requestOAuth, GitHubTokenResponse.class);
      accessToken = oAuthResponse.getAccessToken();
      expiresIn = oAuthResponse.getExpiresIn();
    } catch (OAuthSystemException ae) {
      ae.printStackTrace();
    } catch (OAuthProblemException pe) {
      pe.printStackTrace();
    }

    // out.println("<br>Access Token: " + accessToken);
    // out.println("<br>Expires In: " + expiresIn);

    try {
      FacebookClient facebookClient = new DefaultFacebookClient(accessToken);
      myFriends = facebookClient.fetchConnection("me/friends", User.class);
      myFeeds = facebookClient.fetchConnection("me/home", Post.class);

      for (User myFriend : myFriends.getData()) {
        f.add(myFriend.getName());
        out.println("<br>id: " + myFriend.getId() + " Name: " + myFriend.getName());
      }
      //	out.println("<br>");
      out.println("<br>f count: " + f.size());
    } catch (FacebookException e) {
      e.printStackTrace();
    }

    facebookDataBean fdb = new facebookDataBean();
    fdb.setName("zishan ali khan");
    HttpSession session = request.getSession();
    if (session != null) {
      session.setAttribute("myfdb", fdb);
      session.setAttribute("yourFriends", f);
      session.setAttribute("feeds", myFeeds);
      RequestDispatcher view = request.getRequestDispatcher("result.jsp");
      view.forward(request, response);
      f.clear();
      // out.println("<br>I am in");
    } else {
      // out.println("<br>Session Over");
    }
  }
Example #29
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html");
    HttpSession session = request.getSession(false);
    String reseller = null;
    if (session != null && session.getAttribute("reseller") != null)
      reseller = "%" + session.getAttribute("reseller") + "%";
    List<LicenseData> searchResult = null;
    if (reseller != null) {
      /*  session.setAttribute("fieldsearch", true);
      session.removeAttribute("datesearch");*/

      if (request.getParameter("so") != null && !request.getParameter("so").isEmpty()) {

        log.info(
            "Search Fields : Sales Order Search "
                + request.getParameter("so")
                + " for reseller "
                + session.getAttribute("reseller"));

        searchResult = getSearchByFieldResults(reseller, request.getParameter("so"), "so");

        session.setAttribute("so", request.getParameter("so"));
        session.removeAttribute("enduser");
        session.removeAttribute("ek");
        session.setAttribute("label", "Sales Order");
        session.setAttribute("value", request.getParameter("so"));

      } else if (request.getParameter("enduser") != null
          && !request.getParameter("enduser").isEmpty()) {

        log.info(
            "Search Fields : End User Search "
                + request.getParameter("enduser")
                + " for reseller "
                + session.getAttribute("reseller"));

        searchResult =
            getSearchByFieldResults(reseller, request.getParameter("enduser"), "enduser");
        session.setAttribute("enduser", request.getParameter("enduser"));
        session.removeAttribute("so");
        session.removeAttribute("sno");
        session.removeAttribute("ek");
        session.setAttribute("label", "End User");
        session.setAttribute("value", request.getParameter("enduser"));

      } else if (request.getParameter("ek") != null && !request.getParameter("ek").isEmpty()) {

        log.info(
            "Search Fields : Entitlement Key Search "
                + request.getParameter("ek")
                + " for reseller "
                + session.getAttribute("reseller"));

        searchResult = getSearchByFieldResults(reseller, request.getParameter("ek"), "ek");
        session.setAttribute("ek", request.getParameter("ek"));
        session.removeAttribute("so");
        session.removeAttribute("sno");
        session.removeAttribute("enduser");
        session.setAttribute("label", "Entitlement Key");
        session.setAttribute("value", request.getParameter("ek"));

      } else if (request.getParameter("sno") != null && !request.getParameter("sno").isEmpty()) {

        log.info(
            "Search Fields : Serial Number Search "
                + request.getParameter("sno")
                + " for reseller "
                + session.getAttribute("reseller"));

        searchResult = getSearchByFieldResults(reseller, request.getParameter("sno"), "sno");
        session.setAttribute("sno", request.getParameter("sno"));
        session.removeAttribute("ek");
        session.removeAttribute("so");
        session.removeAttribute("enduser");
        request.setAttribute("sno", 1);
        session.setAttribute("label", "Serial Number");
        session.setAttribute("value", request.getParameter("sno"));

      } else if (request.getParameter("po") != null && !request.getParameter("po").isEmpty()) {

        log.info(
            "Search Fields : Purchase Order Search "
                + request.getParameter("po")
                + " for reseller "
                + session.getAttribute("reseller"));

        searchResult = getSearchByFieldResults(reseller, request.getParameter("po"), "po");
        session.setAttribute("po", request.getParameter("po"));
        session.setAttribute("label", "Purchase Order");
        session.setAttribute("value", request.getParameter("po"));

      } else if (request.getParameter("hm") != null && !request.getParameter("hm").isEmpty()) {

        log.info(
            "Search Fields : HM ID Search "
                + request.getParameter("hm")
                + " for reseller "
                + session.getAttribute("hm"));

        searchResult = getSearchByFieldResults(reseller, request.getParameter("hm"), "hm");
        session.setAttribute("hm", request.getParameter("hm"));
        session.setAttribute("label", "Hive Manager ID");
        session.setAttribute("value", request.getParameter("hm"));
      }

      session.setAttribute("fieldSearchList", searchResult);
      String nextJSP = "/viewFieldSearchResult.jsp";
      RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
      dispatcher.forward(request, response);
    } else {

      log.info("Search Fields : Reseller Blank  ");
      String nextJSP = "/login.jsp";
      RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
      dispatcher.forward(request, response);
    }
  }
Example #30
0
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = request.getSession();

    // All request in GET method must be certificated
    Object obj = session.getAttribute("device_id");

    if (!(obj instanceof Long)) {
      // Client must be login first, then use Mobile service
      response.setStatus(404);
      return;
    }

    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();

    // Here is tracked's id
    Long device_id = (Long) obj;

    // Determine operation type
    String op = request.getParameter("op");
    if (op == null) op = "";

    // Get current track
    Long track_id = null;
    obj = session.getAttribute("track_id");
    if (obj instanceof Long) {
      track_id = (Long) obj;
    }

    if (op.equals("logout")) {
      // Client request a logout operation
      session.removeAttribute("device_id");
      session.removeAttribute("track_id");
      out.print("OK," + device_id);
    } else if (op.equals("latlng")) {
      // Client insert update it's location in latitude/longitude

      // If it's a first waypoint, create a new track
      if (track_id == null) {
        track_id = db.newTrack(device_id).getResult().getTrackID();
        session.setAttribute("track_id", track_id);
      }

      // Parse latitude, longitude from request
      double lat = Double.parseDouble(request.getParameter("lat"));
      double lng = Double.parseDouble(request.getParameter("lng"));

      long speed = -1L;
      try {
        // Try to get speed from request
        speed = Long.parseLong(request.getParameter("spd"));
      } catch (Exception ex) {
      }

      if (speed < 0) {
        // Client don't send speed to server
        try {
          // Calculate speed manually
          double lastLat = (Double) session.getAttribute("latitude");
          double lastLng = (Double) session.getAttribute("longitude");
          long time = (Long) session.getAttribute("time");
          long distance = Utils.getDistance(lastLat, lastLng, lat, lng);
          speed = distance * 1000 / Math.abs(time - System.currentTimeMillis());
        } catch (Exception ex) {
          speed = 0L;
        }
      }

      // Insert new point into server
      ServiceResult<CWaypoint> result = db.insertWaypoint(track_id, lat, lng, speed);
      CWaypoint cwaypoint = result.getResult();
      if (result.isOK()) {
        // OK,latitude,longitude,speed(m/s),time,trackid
        session.setAttribute("latitude", lat);
        session.setAttribute("longitude", lng);
        session.setAttribute("time", cwaypoint.getTime().getTime());
        out.print(
            "OK,"
                + cwaypoint.getLat()
                + ","
                + cwaypoint.getLng()
                + ","
                + cwaypoint.getSpeed()
                + ","
                + cwaypoint.getTime().getTime()
                + ","
                + cwaypoint.getTrackID());
      }
    } else if (op.equals("cellid")) {
      // Client send it's location by cellular technique
      if (track_id == null) {
        track_id = db.newTrack(device_id).getResult().getTrackID();
        session.setAttribute("track_id", track_id);
      }

      try {
        int cell = Integer.parseInt(request.getParameter("cell"));
        int lac = Integer.parseInt(request.getParameter("lac"));
        Geocode geocode = Utils.getLocation(cell, lac);
        out.println(geocode.getLatitude() + "," + geocode.getLongitude());
      } catch (Exception ex) {
      }

      // TODO Implements cellular method to calculate location of a mobile
      out.println("Not implement");
    } else if (op.equals("newtrack")) {
      // Client request to create a new track
      track_id = db.newTrack(device_id).getResult().getTrackID();
      session.setAttribute("track_id", track_id);
      out.print("OK," + track_id);
    } else if (op.equals("changepass")) {
      String newpass = request.getParameter("newpass");
      if (newpass != null) {
        CTracked ctracked = new CTracked();
        ctracked.setUsername(device_id);
        ctracked.setPassword(newpass);
        if (db.updateTracked(ctracked).isOK()) {
          out.println("OK," + device_id);
        }
      }
    } else if (op.equals("config")) {
      CTracked ctracked = db.getTracked(device_id).getResult();
      Integer interval = ctracked.getIntervalGps();
      if (interval == null) interval = 10;
      out.print("OK," + interval + ",");
      byte[] b = ctracked.getSchedule();
      if (b == null) {
        for (int i = 0; i < 23; i++) {
          out.print("1.");
        }
        out.println(1);
      } else {
        for (int i = 0; i < 23; i++) {
          out.print(b[i] + ".");
        }
        out.println(b[23]);
      }
    } else if (op.equals("amilogin")) {
      out.println("OK");
    }
  }