Example #1
1
  public static void showSession(HttpServletRequest req, PrintStream out) {

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

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

    out.println("Session id: " + session.getId());
    out.println(" session.isNew(): " + session.isNew());
    out.println(" session.getMaxInactiveInterval(): " + session.getMaxInactiveInterval() + " secs");
    out.println(
        " session.getCreationTime(): "
            + session.getCreationTime()
            + " ("
            + new Date(session.getCreationTime())
            + ")");
    out.println(
        " session.getLastAccessedTime(): "
            + session.getLastAccessedTime()
            + " ("
            + new Date(session.getLastAccessedTime())
            + ")");
    out.println(" req.isRequestedSessionIdFromCookie: " + req.isRequestedSessionIdFromCookie());
    out.println(" req.isRequestedSessionIdFromURL: " + req.isRequestedSessionIdFromURL());
    out.println(" req.isRequestedSessionIdValid: " + req.isRequestedSessionIdValid());

    out.println("Saved session Attributes:");
    Enumeration atts = session.getAttributeNames();
    while (atts.hasMoreElements()) {
      String name = (String) atts.nextElement();
      out.println(" " + name + ": " + session.getAttribute(name) + "<BR>");
    }
  }
Example #2
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 #3
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 #4
0
  private void unjoinChat() {
    if (thisSession.getUserProperties().containsKey("USER")) {
      LOG.debug("unjoinChat(): " + thisSession.getUserProperties().get("USER"));

      sessionService.removeOnSessionDestroyedListener(callback);

      if (isHttpSessionValid) {
        int sessionIdleTime =
            (int) ((System.currentTimeMillis() - httpSession.getLastAccessedTime()) / 1000);
        LOG.debug("Max idle timeout: " + (sessionIdleTime + defaultSessionTimeout));
        httpSession.setMaxInactiveInterval(sessionIdleTime + defaultSessionTimeout);
      }

      int userNb = usersLoggedIn.decrementAndGet();

      Message infoMsg = new Message();

      infoMsg.TYPE = "INFO";
      infoMsg.SUBTYPE = "JOIN";
      infoMsg.INFO_MSG = thisSession.getUserProperties().get("USER") + " has left the building";
      infoMsg.STATS_MSG = userNb + " User" + (userNb > 1 ? "s " : " ") + "online!";
      infoMsg.USER_LIST = buildUserList(false);

      thisSession.getUserProperties().clear();

      broadcastMessage(infoMsg, false);
    }
  }
Example #5
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String login = request.getParameter("email");
    String pwd = request.getParameter("password");
    User user = userService.getUser(login, pwd);

    if (user != null) {
      HttpSession session = request.getSession();

      long time = session.getCreationTime();
      long lastTime = session.getLastAccessedTime();
      String idSession = session.getId();

      session.setAttribute("user", user);
      response.sendRedirect("/home");

      System.out.println("session time creation " + time);
      System.out.println("session last access time " + lastTime);
      System.out.println("session id " + idSession);

      System.out.println(user.toString());
    } else {
      response.sendRedirect("/");
      System.out.println("hera lisogo");
    }
  }
  /**
   * @param request
   * @param response
   * @return
   * @throws IOException
   */
  private boolean controlURL(
      HttpServletRequest request, HttpServletResponse response, String sessionKey)
      throws IOException {

    HttpSession httpSession = request.getSession(false);
    // ** 未登录则不通过
    if (httpSession == null) {
      System.out.println("111111111111111111111111111111111111  httpSession == null");
      response.sendRedirect(REDIRECT);
      return false;
    }

    // ** 判断是否登录
    Object onlineObj = httpSession.getAttribute(sessionKey);
    if (onlineObj == null) {
      System.out.println("222222222222222222222222222222222222 onlineObj == null");
      response.sendRedirect(REDIRECT);
      return false;
    }

    // ** 最后一次访问时间大于 30 分钟
    long lastAccessed = httpSession.getLastAccessedTime();
    if (System.currentTimeMillis() - lastAccessed > 30 * 60 * 1000) {
      System.out.println("333333333333333333333333333333333333 lastAccessed > 30 * 60 * 1000");
      response.sendRedirect(REDIRECT);
      return false;
    }

    return true;
  }
Example #7
0
  /**
   * @param request the current request
   * @param response the current response
   * @param chain the chain
   * @throws IOException when something goes wrong
   * @throws ServletException when a communication failure happens
   */
  @SuppressWarnings("unchecked")
  public void doFilterInternal(
      HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpSession session = request.getSession();
    String request_uri = request.getRequestURI();
    // System.out.println("request_uri===="+request_uri);
    long sessionAccessedTime = session.getLastAccessedTime();
    long mySessionTime = 0;
    if (session.getAttribute("mySessionTime") != null)
      mySessionTime = Long.parseLong(session.getAttribute("mySessionTime").toString());

    // if(request_uri.indexOf("login.html")==-1&&request_uri.indexOf("out.html")==-1){//sessionMonitoring
    // System.out.println("==1=="+request.getContextPath()+"/error.jsp");
    // response.sendRedirect(request.getContextPath()+"/admin/sessionError.html");
    if (request_uri.indexOf("noticeLoadDesktopNotice.html") == -1
        && request_uri.indexOf("noticeLoadUnReadedNotice.html") == -1
        && request_uri.indexOf("sessionMonitoring.html") == -1) {
      session.setAttribute("mySessionTime", sessionAccessedTime);
      chain.doFilter(request, response);
    } else {
      // System.out.println("sessionAccessedTime===="+sessionAccessedTime);
      // System.out.println("mySessionTime===="+mySessionTime);
      chain.doFilter(request, response);
    }
  }
 @Test(groups = INTEGRATION)
 @SpecAssertions({@SpecAssertion(section = DECORATOR_INVOCATION, id = "acj")})
 public void testDecoratorIsInvoked() {
   httpSession.invalidate();
   assertTrue(httpSessionObserver.isDestroyed());
   assertTrue(httpSessionObserver.isDecorated());
   assertEquals(3, httpSession.getLastAccessedTime());
   assertEquals("bar", httpSession.getAttribute("foo"));
 }
 long getKeepAliveScheduleTime() throws IllegalStateException {
   int maxInactiveInterval = httpSession.getMaxInactiveInterval();
   if (maxInactiveInterval < 0) {
     return Long.MAX_VALUE;
   }
   long lastAccessedTime = Math.max(this.lastAccessedTime, httpSession.getLastAccessedTime());
   return (maxInactiveInterval * 1000)
       - (System.currentTimeMillis() - lastAccessedTime)
       - SESSION_KEEP_ALIVE_BUFFER;
 }
Example #10
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = request.getSession(true);
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Session Demo";
    String heading;
    Integer accessCount = new Integer(0);
    ;
    if (session.isNew()) {
      heading = "Welcome, Newcomer";
    } else {
      heading = "Welcome Back";
      Integer oldAccessCount = (Integer) session.getAttribute("accessCount");
      if (oldAccessCount != null) {
        accessCount = new Integer(oldAccessCount.intValue() + 1);
      }
    }
    session.setAttribute("accessCount", accessCount);

    out.println(
        "<HTML><HEAD><TITLE>"
            + title
            + "</TITLE></HEAD>\n"
            + "<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"
            + "</TABLE>\n"
            + "</BODY></HTML>");
  }
  void removeSession(String id) {
    if (!isManagementOfSessionsTurnedOn()) {
      return;
    }

    HttpSession session = sessions.remove(id);

    long lastAccessedTime = session == null ? 0 : session.getLastAccessedTime();
    int maxInactiveInterval = session == null ? 0 : session.getMaxInactiveInterval();
    getContext()
        .publishEvent(new HttpSessionDestroyed(this, id, lastAccessedTime, maxInactiveInterval));
  }
Example #12
0
 /** @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
     throws IOException, ServletException {
   try {
     HttpServletRequest req = (HttpServletRequest) request;
     HttpSession session = req.getSession(false);
     if (session != null) {
       if (log.isTraceEnabled()) log.trace("Requested: " + req.getServletPath());
       if (!req.getServletPath().matches("^/JSON-RPC$")) {
         session.setAttribute("lastAccessedTime", session.getLastAccessedTime());
       }
     }
   } catch (ClassCastException e) {
     e.printStackTrace();
   }
   chain.doFilter(request, response);
 }
  @SuppressWarnings("deprecation")
  String removeUselessSessions() {
    if (!isManagementOfSessionsTurnedOn()) {
      return CoreConstants.EMPTY;
    }

    if (sessions.isEmpty() || sessions.size() <= 0) {
      return CoreConstants.EMPTY;
    }

    Set<String> keysSet = sessions.keySet();
    if (ListUtil.isEmpty(keysSet)) {
      return CoreConstants.EMPTY;
    }
    List<String> keys = new ArrayList<String>(keysSet);

    List<String> sessionsToRemove = new ArrayList<String>();
    long currentTime = System.currentTimeMillis();
    for (String key : keys) {
      HttpSession session = sessions.get(key);
      if (session == null) {
        continue;
      }

      long idleTime = currentTime - session.getLastAccessedTime();
      if (idleTime >= 600000) {
        //	Session "was" idle for 10 minutes or more

        Object chibaManager = session.getAttribute("chiba.session.manager");
        if (chibaManager != null) {
          continue;
        }

        Object principal = session.getValue("org.apache.slide.webdav.method.principal");
        //	Checking if session was created by Slide's root user
        if (principal instanceof String && "root".equals(principal)) {
          sessionsToRemove.add(session.getId());
        }
      }
    }

    for (String sessionId : sessionsToRemove) {
      removeSession(sessionId);
    }

    return ListUtil.isEmpty(sessionsToRemove) ? CoreConstants.EMPTY : sessionsToRemove.toString();
  }
Example #14
0
 public void doGet(HttpServletRequest req, HttpServletResponse res)
     throws ServletException, IOException {
   PrintWriter pw = res.getWriter();
   HttpSession sess = req.getSession(true);
   String state = "";
   Integer count = 0;
   if (sess.isNew()) state = "New Session";
   else {
     state = "Old Session";
     Integer oldCount = (Integer) sess.getAttribute("count");
     if (oldCount != null) count = oldCount + 1;
   }
   sess.setAttribute("count", count);
   pw.println(state);
   pw.println("Session Creation Time " + new Date(sess.getCreationTime()));
   pw.println("Session LastAccess Time " + new Date(sess.getLastAccessedTime()));
   pw.println("Session value " + sess.getValue("count"));
 }
Example #15
0
  /**
   * @param req
   * @return
   */
  public static String describeRequest(HttpServletRequest req) {

    if (req == null) {
      return EMPTY;
    }

    HttpSession session = null;
    try {
      session = req.getSession();
    } catch (Exception e) {
    }

    StringBuilder body = new StringBuilder();
    body.append("Browser: " + req.getHeader("User-Agent"));

    body.append("\n\nRequest Info");
    body.append("\nRequest URI: " + req.getRequestURI());
    body.append("\nRequest URL: " + req.getRequestURL().toString());
    body.append("\nPath Info: " + req.getPathInfo());
    body.append("\nQuery String: " + req.getQueryString());

    if (session != null) {
      body.append("\n\nSession Info");
      body.append("\nSession ID: " + session.getId());
      body.append("\nSession Created: " + new Date(session.getCreationTime()).toString());
      body.append("\nSession Last Accessed: " + new Date(session.getLastAccessedTime()).toString());
    }

    body.append("\n\nUser Info");
    body.append("\nRemote User: "******"\nUser Principal: " + req.getUserPrincipal());

    body.append("\n\nServer Info");
    String hostname = "", serverInstance = "", ip = "";
    try {
      hostname = java.net.InetAddress.getLocalHost().getHostName();
      serverInstance = System.getProperty("com.sun.aas.instanceName");
      ip = java.net.InetAddress.getLocalHost().getHostAddress();
      body.append("\nInstance: " + serverInstance + " : " + ip + " : " + hostname);
    } catch (Exception e) {
    }

    return body.toString();
  }
 public void logStats(HttpSession session, GenericValue visit) {
   if (Debug.verboseOn() || session.getAttribute("org.ofbiz.log.session.stats") != null) {
     Debug.log("<===================================================================>", module);
     Debug.log("Session ID     : " + session.getId(), module);
     Debug.log("Created Time   : " + session.getCreationTime(), module);
     Debug.log("Last Access    : " + session.getLastAccessedTime(), module);
     Debug.log("Max Inactive   : " + session.getMaxInactiveInterval(), module);
     Debug.log("--------------------------------------------------------------------", module);
     Debug.log("Total Sessions : " + ControlEventListener.getTotalActiveSessions(), module);
     Debug.log("Total Active   : " + ControlEventListener.getTotalActiveSessions(), module);
     Debug.log("Total Passive  : " + ControlEventListener.getTotalPassiveSessions(), module);
     Debug.log("** note : this session has been counted as destroyed.", module);
     Debug.log("--------------------------------------------------------------------", module);
     Debug.log("Visit ID       : " + visit.getString("visitId"), module);
     Debug.log("Party ID       : " + visit.getString("partyId"), module);
     Debug.log("Client IP      : " + visit.getString("clientIpAddress"), module);
     Debug.log("Client Host    : " + visit.getString("clientHostName"), module);
     Debug.log("Client User    : "******"clientUser"), module);
     Debug.log("WebApp         : " + visit.getString("webappName"), module);
     Debug.log("Locale         : " + visit.getString("initialLocale"), module);
     Debug.log("UserAgent      : " + visit.getString("initialUserAgent"), module);
     Debug.log("Referrer       : " + visit.getString("initialReferrer"), module);
     Debug.log("Initial Req    : " + visit.getString("initialRequest"), module);
     Debug.log("Visit From     : " + visit.getString("fromDate"), module);
     Debug.log("Visit Thru     : " + visit.getString("thruDate"), module);
     Debug.log("--------------------------------------------------------------------", module);
     Debug.log("--- Start Session Attributes: ---", module);
     Enumeration<String> sesNames = null;
     try {
       sesNames = UtilGenerics.cast(session.getAttributeNames());
     } catch (IllegalStateException e) {
       Debug.log("Cannot get session attributes : " + e.getMessage(), module);
     }
     while (sesNames != null && sesNames.hasMoreElements()) {
       String attName = sesNames.nextElement();
       Debug.log(attName + ":" + session.getAttribute(attName), module);
     }
     Debug.log("--- End Session Attributes ---", module);
     Debug.log("<===================================================================>", module);
   }
 }
Example #17
0
  public static synchronized void sessionCreated(HttpSessionEvent ev) {
    HttpSession httpSession = ev.getSession();
    String id = httpSession.getId();

    // Remember HTTP-session:
    {
      lookupHttpSessionById.put(id, httpSession);
    }

    AbstractSession session = null;

    synchronized (lookupSessionById) {
      session = lookupSessionById.get(id);
    }

    if (session == null) {
      Principal userPrincipal = null;
      Date timeCreation = new Date(httpSession.getCreationTime());
      Date timeLastAccess = new Date(httpSession.getLastAccessedTime());
      List<String> urisForLastRequests = null;
      Properties properties = null;

      session =
          new DefaultSession(
              id, userPrincipal, timeCreation, timeLastAccess, urisForLastRequests, properties);

      synchronized (lookupSessionById) {
        lookupSessionById.put(id, session);

        // Update 'sessionCountMax':
        {
          int sessionCount = lookupSessionById.size();
          if (sessionCount > sessionCountMax) {
            sessionCountMax = sessionCount;
            sessionCountMaxTime = System.currentTimeMillis();
          }
        }
      }
    }
  }
Example #18
0
  protected void expandSession(AbstractSession session) throws IOException {
    if (session != null) {
      String id = session.getId();
      HttpSession httpSession = lookupHttpSessionById.get(id);

      // Set 'timeLastAccess' upon session:
      {
        if (httpSession != null) {
          Date timeLastAccess = new Date(httpSession.getLastAccessedTime());
          session.setTimeLastAccess(timeLastAccess);
        }
      }

      expandSessionPrincipal(session);

      // Set 'requestURI' upon session:
      {
        if (httpSession != null) {
          List<String> requestURIs = RequestURISessionDecorator.getRequestURIs(httpSession);
          if (requestURIs != null) {
            Collections.reverse(requestURIs); // reverse the order!
            session.setRequestURIs(requestURIs);
          }
        }
      }

      // Set 'properties' upon session:
      {
        if (httpSession != null) {
          Map<String, Object> m = PropertiesSessionDecorator.getProperties(httpSession);
          if (m != null) {
            Properties properties = convertProperties(m);
            session.setProperties(properties);
          }
        }
      }
    }
  }
Example #19
0
 public void doPost(HttpServletRequest req, HttpServletResponse res)
     throws ServletException, IOException {
   Connection con = null;
   // res.setContentType("text/html");
   // res.setHeader("Cache-Control","no-store");
   // PrintWriter out=res.getWriter();
   HttpSession session = req.getSession(false);
   String ad_user;
   ad_user = (String) session.getValue("aduser");
   java.util.Date time_comp = new java.util.Date(System.currentTimeMillis() - 20 * 60 * 1000);
   java.util.Date accessed = new java.util.Date(session.getLastAccessedTime());
   if (session == null || ad_user == null || accessed.before(time_comp)) {
     session.invalidate();
     // out.println("<H2>Your Session has expired </H2>");
     // out.println("<a href='admin.htm'>Click Here</a> To Re-Login");
     return;
   }
   String temp_list_id = req.getParameter("list_id");
   int list_id;
   try {
     list_id = Integer.parseInt(temp_list_id);
   } catch (Exception e) {
     // out.println("<H2>NO List Found</H2>");
     // out.println("<a href='javascript:history.go(-1)'>Click Here</a>  to go back to previous
     // page & try again");
     return;
   }
   try {
     con = pool.getConnection();
     Statement stmt = con.createStatement();
     File file = new File("temp.csv");
     FileWriter fout = new FileWriter(file);
     BufferedWriter bw = new BufferedWriter(fout);
     // String line="";
     bw.write("Name,Email\r\n");
     ResultSet rs = stmt.executeQuery("Select * from list_member where list_id=" + list_id);
     while (rs.next()) {
       String name = rs.getString("member_name");
       String email = rs.getString("member_email");
       bw.write(name + "," + email + "\r\n");
     }
     bw.close();
     fout.close();
     rs.close();
     // String fname=file.getName();
     // String contentType = getServletContext().getMimeType(fname);
     // System.out.println(contentType);
     res.setContentType("application/csv");
     ServletOutputStream out = res.getOutputStream();
     FileInputStream fis = new FileInputStream("temp.csv");
     byte[] buf = new byte[4 * 1024]; // 4K buffer
     int bytesRead;
     while ((bytesRead = fis.read(buf)) != -1) {
       out.write(buf, 0, bytesRead);
     }
     out.close();
   } catch (Exception e) {
     try {
       // out.println("<H2>An Error has occured: "+e.getMessage()+"</H2>");
       e.printStackTrace();
       // out.println("<br><br><a href='javascript:history.go(-1)'>Click Here</a> to go back to
       // previous page & Try Again");
       con.rollback();
     } catch (Exception ignored) {
     }
   } finally {
     if (con != null) pool.returnConnection(con);
     // out.close();
   }
 }
  public void sessionDestroyed(HttpSessionEvent event) {
    HttpSession session = event.getSession();

    // Finalize the Visit
    boolean beganTransaction = false;
    try {
      beganTransaction = TransactionUtil.begin();

      // instead of using this message, get directly from session attribute so it won't create a new
      // one: GenericValue visit = VisitHandler.getVisit(session);
      GenericValue visit = (GenericValue) session.getAttribute("visit");
      if (visit != null) {
        visit.set("thruDate", new Timestamp(session.getLastAccessedTime()));
        visit.store();
      } else {
        Debug.logWarning(
            "Could not find visit value object in session ["
                + session.getId()
                + "] that is being destroyed",
            module);
      }

      // Store the UserLoginSession
      String userLoginSessionString = getUserLoginSession(session);
      GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
      if (userLogin != null && userLoginSessionString != null) {
        GenericValue userLoginSession = null;
        userLoginSession = userLogin.getRelatedOne("UserLoginSession");

        if (userLoginSession == null) {
          userLoginSession =
              userLogin
                  .getDelegator()
                  .makeValue(
                      "UserLoginSession",
                      UtilMisc.toMap("userLoginId", userLogin.getString("userLoginId")));
          userLogin.getDelegator().create(userLoginSession);
        }
        userLoginSession.set("savedDate", UtilDateTime.nowTimestamp());
        userLoginSession.set("sessionData", userLoginSessionString);
        userLoginSession.store();
      }

      countDestroySession();
      Debug.logInfo("Destroying session: " + session.getId(), module);
      this.logStats(session, visit);
    } catch (GenericEntityException e) {
      try {
        // only rollback the transaction if we started one...
        TransactionUtil.rollback(
            beganTransaction, "Error saving information about closed HttpSession", e);
      } catch (GenericEntityException e2) {
        Debug.logError(e2, "Could not rollback transaction: " + e2.toString(), module);
      }

      Debug.logError(e, "Error in session destuction information persistence", module);
    } finally {
      // only commit the transaction if we started one... this will throw an exception if it fails
      try {
        TransactionUtil.commit(beganTransaction);
      } catch (GenericEntityException e) {
        Debug.logError(
            e, "Could not commit transaction for update visit for session destuction", module);
      }
    }
  }
Example #21
0
  public void getEnv(VariableTable vt) {
    Enumeration e = null;
    HttpServletRequest request = (HttpServletRequest) (pageContext.getRequest());
    HttpSession session = request.getSession(false);

    String db_charset = "gb2312";
    String url_charset = null;

    vt.remove("SESSION.LOGINID");
    vt.remove("SESSION.LOGINNAME");
    vt.remove("SESSION.LOGINROLE");

    if (vt.exists("WEBCHART.DB_CHARSET")) {
      db_charset = vt.getString("WEBCHART.DB_CHARSET");
    }

    if (vt.exists("WEBCHART.URL_CHARSET")) {
      url_charset = vt.getString("WEBCHART.URL_CHARSET");
    }

    if (session != null) {
      e = session.getAttributeNames();
      while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        Object value = session.getAttribute(name);
        vt.add(name, java.sql.Types.VARCHAR);
        if (value != null) vt.setValue(name, value.toString());
      }
      vt.add("SESSION.ID", java.sql.Types.VARCHAR);
      vt.setValue("SESSION.ID", session.getId());
      vt.add("SESSION.CREATE", java.sql.Types.VARCHAR);
      vt.setValue(
          "SESSION.CREATE",
          DBOperation.toString(
              new java.util.Date(session.getCreationTime()), "yyyy-MM-dd HH:mm:ss"));
      vt.add("SESSION.ACCESS", java.sql.Types.VARCHAR);
      vt.setValue(
          "SESSION.ACCESS",
          DBOperation.toString(
              new java.util.Date(session.getLastAccessedTime()), "yyyy-MM-dd HH:mm:ss"));
    }
    e = request.getParameterNames();
    while (e.hasMoreElements()) {
      String name = (String) e.nextElement();
      String value = request.getParameter(name);
      ;
      String par_values[] = request.getParameterValues(name);
      name = name.toUpperCase();
      if (name.equalsIgnoreCase("WEBCHART.SECURITY")
          || name.equalsIgnoreCase("WEBCHART.DEFAULTACCESS")
          || name.equalsIgnoreCase("WEBCHART.ALLOW")
          || name.equalsIgnoreCase("WEBCHART.DENY")
          || name.equalsIgnoreCase("WEBCHART.IPSECURITY")
          || name.equalsIgnoreCase("WEBCHART.IPACCESS")
          || name.equalsIgnoreCase("WEBCHART.IPALLOW")
          || name.equalsIgnoreCase("WEBCHART.IPDENY")
          || name.equalsIgnoreCase("WEBCHART.XSLDOC")
          || name.equalsIgnoreCase("WEBCHART.IMAGEONLY")
          || name.equalsIgnoreCase("WEBCHART.XMLDATA")
          || name.equalsIgnoreCase("WEBCHART.LOGSQL")
          || name.equalsIgnoreCase("WEBCHART.DATATYPE")
          || name.equalsIgnoreCase("WEBCHART.URLS")
          || name.equalsIgnoreCase("WEBCHART.TOPURLS")
          || name.equalsIgnoreCase("WEBCHART.TOPCURR")
          || name.equalsIgnoreCase("WEBCHART.LEFTURLS")
          || name.equalsIgnoreCase("WEBCHART.LEFTCURR")
          || name.equalsIgnoreCase("WEBCHART.INPUTS")
          || name.equalsIgnoreCase("WEBCHART.CACHE")
          || name.equalsIgnoreCase("WEBCHART.DATA")
          || name.equalsIgnoreCase("WEBCHART.CSS")
          || name.equalsIgnoreCase("WEBCHART.RELOAD")
          || name.equalsIgnoreCase("WEBCHART.EXPIRE")
          || name.equalsIgnoreCase("WEBCHART.DMLKEY")
          || name.equalsIgnoreCase("WEBCHART.ENGINE")
          || name.equalsIgnoreCase("WEBCHART.EXCELURL")
          || name.equalsIgnoreCase("WEBCHART.DBID")
          || name.equalsIgnoreCase("WEBCHART.DBIDSEED")
          || name.equalsIgnoreCase("WEBCHART.SECUREFIELDS")
          || name.equalsIgnoreCase("WEBCHART.KEEP_CACHE_IMAGE")
          || name.equalsIgnoreCase("WEBCHART.KEEP_CACHE_TIME")
          || name.startsWith("WEBCHART.SECUREMEMO")
          || name.startsWith("WEBCHART.QUERY_")
          || name.startsWith("WEBCHART.HEADHTML_")
          || name.startsWith("WEBCHART.DATAHTML_")
          || name.startsWith("WEBCHART.VARLIST_")
          || name.startsWith("WEBCHART.FORALL_")
          || name.startsWith("WEBCHART.XMLDATA_")
          || name.startsWith("WEBCHART.TABLE_")
          || name.startsWith("WEBCHART.COLUMN_")
          || name.startsWith("SESSION.")) continue;
      if (name.startsWith("WEBCHART.") && !name.equals("WEBCHART.DOCTYPE")) continue;
      vt.add(name, java.sql.Types.VARCHAR);

      if (par_values != null && par_values.length > 1) {
        StringBuffer temp = new StringBuffer();
        for (int i = 0; i < par_values.length; i++) {
          if (par_values[i] != null && par_values[i].trim().length() > 0) {
            if (temp.length() > 0) {
              temp.append(",");
            }
            temp.append(par_values[i]);
          }
        }
        value = temp.toString();
      }
      if (url_charset != null) {
        try {
          value = new String(value.getBytes(url_charset), db_charset);
        } catch (java.io.UnsupportedEncodingException uee) {
        }
        ;
      }
      vt.setValue(name, value);
    }
    vt.add("REQUEST.REMOTEADDR", java.sql.Types.VARCHAR);
    vt.setValue("REQUEST.REMOTEADDR", getClientIPAddr());
    vt.add("REQUEST.REMOTEHOST", java.sql.Types.VARCHAR);
    vt.setValue("REQUEST.REMOTEHOST", request.getRemoteAddr());
    vt.add("REQUEST.REFERER", java.sql.Types.VARCHAR);
    vt.setValue("REQUEST.REFERER", request.getHeader("Referer"));
    vt.add("REQUEST.QUERYSTRING", java.sql.Types.VARCHAR);
    vt.setValue("REQUEST.QUERYSTRING", request.getQueryString());
  }
Example #22
0
 @Override
 public long getLastAccessedTime() {
   return session.getLastAccessedTime();
 }
Example #23
0
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    // get the account and password input by the user
    String account = request.getParameter("GMail Address");
    String password = request.getParameter("password");

    request.setAttribute("account", account);

    // create a mail model with the account and password
    MailModel m = new MailModel(account, password);

    // check if the fields are filled
    if (account != null && password != null) {
      // check if the combination is valid
      if (m.validateAccount()) {
        // create a new session for the user
        HttpSession session = request.getSession(true);

        // Get last access time of this web page.
        Date lastAccessTime = new Date(session.getLastAccessedTime());

        // initiate visit count
        Integer visitCount = new Integer(0);

        // initiate userIDKey for session
        String userIDKey = new String("userID");
        String userID = new String(account);

        // check if session is new
        if (session.getAttribute("loginTime") == null) {
          // set the userIDKey userID
          session.setAttribute(userIDKey, userID);

          // set the session time out of 5 minutes
          session.setMaxInactiveInterval(300);
        } else {
          // increase the visit count
          visitCount = (Integer) session.getAttribute("loginTime");
          visitCount = visitCount + 1;
        }
        session.setAttribute("loginTime", visitCount);

        // set attributes for the session ( the account and password)
        session.setAttribute("account", account);
        session.setAttribute("password", password);
        session.setAttribute("lastLoginDate", lastAccessTime);

        // open the compose page
        RequestDispatcher rd = request.getRequestDispatcher("/composingMail.jsp");
        rd.forward(request, response);
      } else {
        // if invalid combination, ask the user to put other combinations
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("EMail Address or Password Error! Please enter again!");
        RequestDispatcher rd = request.getRequestDispatcher("/index.jsp");
        rd.include(request, response);
        out.close();
      }
    } else {
      // if the field(s) is(are) empty, ask user to fill in
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      out.println("EMail Address or Password Error! Please enter again!");
      RequestDispatcher rd = request.getRequestDispatcher("/index.jsp");
      rd.include(request, response);
      out.close();
    }
  }
Example #24
0
  protected Principal checkSessionAuthentication(final HttpServletRequest request)
      throws FrameworkException {

    String requestedSessionId = request.getRequestedSessionId();
    HttpSession session = request.getSession(false);
    boolean sessionValid = false;

    if (requestedSessionId == null) {

      // No session id requested => create new session
      AuthHelper.newSession(request);

      // we just created a totally new session, there can't
      // be a user with this session ID, so don't search.
      return null;

    } else {

      // Existing session id, check if we have an existing session
      if (session != null) {

        if (session.getId().equals(requestedSessionId)) {

          if (AuthHelper.isSessionTimedOut(session)) {

            sessionValid = false;

            // remove invalid session ID from user
            invalidateSessionId(requestedSessionId);

          } else {

            sessionValid = true;
          }
        }

      } else {

        // No existing session, create new
        session = AuthHelper.newSession(request);

        // remove invalid session ID from user
        invalidateSessionId(requestedSessionId);
      }
    }

    if (sessionValid) {

      final Principal user = AuthHelper.getPrincipalForSessionId(session.getId());
      logger.log(
          Level.FINE,
          "Valid session found: {0}, last accessed {1}, authenticated with user {2}",
          new Object[] {session, session.getLastAccessedTime(), user});

      return user;

    } else {

      final Principal user = AuthHelper.getPrincipalForSessionId(requestedSessionId);

      logger.log(
          Level.FINE,
          "Invalid session: {0}, last accessed {1}, authenticated with user {2}",
          new Object[] {session, (session != null ? session.getLastAccessedTime() : ""), user});

      if (user != null) {

        AuthHelper.doLogout(request, user);
      }

      try {
        request.logout();
        request.changeSessionId();
      } catch (Throwable t) {
      }
    }

    return null;
  }