Java Code Examples for javax.servlet.http.HttpSession#getLastAccessedTime()

The following examples show how to use javax.servlet.http.HttpSession#getLastAccessedTime() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private JSONObject sessionToJsonObject(HttpServletRequest request) {
    long creationTime = 0;
    long lastAccessedTime = 0;
    int maxInactiveInterval = 0;

    HttpSession httpSession = request.getSession(false);
    if (httpSession != null) {
        creationTime = httpSession.getCreationTime();
        lastAccessedTime = httpSession.getLastAccessedTime();
        maxInactiveInterval = httpSession.getMaxInactiveInterval();
    }

    JSONObject sessionInfo = new JSONObject();
    sessionInfo.accumulate("creationTime", creationTime);
    sessionInfo.accumulate("lastAccessedTime", lastAccessedTime);
    sessionInfo.accumulate("maxInactiveInterval", maxInactiveInterval);
    
    return sessionInfo;
}
 
Example 2
/**
 * Expire the sessions that have been inactive for more than configured expiration time.
 */
synchronized void expireOldSessions() {
  long now = _time.milliseconds();
  Iterator<Map.Entry<HttpSession, SessionInfo>> iter = _inProgressSessions.entrySet().iterator();
  while (iter.hasNext()) {
    Map.Entry<HttpSession, SessionInfo> entry = iter.next();
    HttpSession session = entry.getKey();
    SessionInfo info = entry.getValue();
    if (LOG.isTraceEnabled()) {
      LOG.trace("Session {} was last accessed at {}, age is {} ms", session, session.getLastAccessedTime(),
                now - session.getLastAccessedTime());
    }
    if (now >= session.getLastAccessedTime() + _sessionExpiryMs) {
      LOG.info("Expiring session {}.", session);
      iter.remove();
      session.invalidate();
      _sessionLifetimeTimer.update(System.nanoTime() - info.requestStartTimeNs(), TimeUnit.NANOSECONDS);
      if (info.lastFuture().isDone() && info.executionTime() > 0) {
        _successfulRequestExecutionTimer.get(info.endPoint()).update(info.executionTime(), TimeUnit.NANOSECONDS);
      } else {
        info.lastFuture().cancel(true);
      }
    }
  }
}
 
Example 3
private void expireOldSessions() {
  long now = _time.milliseconds();
  synchronized (_sessionKeyToUserTaskIdMap) {
    Iterator<Map.Entry<SessionKey, UUID>> iter = _sessionKeyToUserTaskIdMap.entrySet().iterator();
    while (iter.hasNext()) {
      Map.Entry<SessionKey, UUID> entry = iter.next();
      SessionKey sessionKey = entry.getKey();
      HttpSession session = sessionKey.httpSession();
      try {
        if (LOG.isTraceEnabled()) {
          LOG.trace("Session {} was last accessed at {}, age is {} ms.", session, session.getLastAccessedTime(),
                    now - session.getLastAccessedTime());
        }
        if (now >= session.getLastAccessedTime() + _sessionExpiryMs) {
          LOG.info("Expiring the session associated with {}.", sessionKey);
          session.invalidate();
          iter.remove();
        }
      } catch (IllegalStateException e) {
        LOG.info("Already expired the session associated with {}.", sessionKey);
        iter.remove();
      }
    }
  }
}
 
Example 4
Source Project: javamelody   File: SessionListener.java    License: Apache License 2.0 6 votes vote down vote up
void unregisterSessionIfNeeded(HttpSession session) {
	if (session != null) {
		try {
			session.getCreationTime();

			// https://issues.jenkins-ci.org/browse/JENKINS-20532
			// https://bugs.eclipse.org/bugs/show_bug.cgi?id=413019
			session.getLastAccessedTime();
		} catch (final IllegalStateException e) {
			// session.getCreationTime() lance IllegalStateException si la session est invalidée
			synchronized (session) {
				sessionDestroyed(new HttpSessionEvent(session));
			}
		}
	}
}
 
Example 5
/**
 * Returns the portlet session.
 * <p>
 * Note that since portlet request instance is created everytime the portlet
 * container receives an incoming request, the portlet session instance held
 * by the request instance is also re-created for each incoming request.
 * </p>
 */
@Override
public PortletSession getPortletSession(boolean create) {
   if (isDebug) {
      LOG.debug("Retrieving portlet session (create=" + create + ")");
   }

   if ((cachedPortletSession == null) || cachedPortletSession.isInvalidated()) {

      //
      // It is critical that we don't retrieve the portlet session until the
      // cross context dispatch has been completed. If we do then we risk
      // having a cached version which is invalid for the context within
      // which it exists.
      //
   
      if (portletConfig == null) {
         throw new IllegalStateException(EXCEPTIONS.getString("error.session.illegalState"));
      }
   
      //
      // We must make sure that if the session has been invalidated (perhaps
      // through setMaxIntervalTimeout()) and the underlying request
      // returns null that we no longer use the cached version.
      // We have to check (ourselves) if the session has exceeded its max
      // inactive interval. If so, we should invalidate the underlying
      // HttpSession and recreate a new one (if the create flag is set to
      // true) -- We just cannot depend on the implementation of
      // javax.servlet.http.HttpSession!
      //
   
      HttpSession httpSession = getServletRequest().getSession(create);
      if (httpSession != null) {
         // HttpSession is not null does NOT mean that it is valid.
         int maxInactiveInterval = httpSession.getMaxInactiveInterval();
         long lastAccesstime = httpSession.getLastAccessedTime();// lastAccesstime checks added for PLUTO-436
         if (maxInactiveInterval >= 0 && lastAccesstime > 0) { // < 0 => Never expires.
            long maxInactiveTime = httpSession.getMaxInactiveInterval() * 1000L;
            long currentInactiveTime = System.currentTimeMillis() - lastAccesstime;
            if (currentInactiveTime > maxInactiveTime) {
               if (isDebug) {
                  LOG.debug("The underlying HttpSession is expired and " + "should be invalidated.");
               }
               httpSession.invalidate();
               httpSession = getServletRequest().getSession(create);
               // Added for PLUTO-436
               // a cached portletSession is no longer useable.
               // a new one will be created below.
            }
         }
      }
   
      if (httpSession == null) {
         if (isDebug) {
            LOG.debug("The underlying HttpSession is not available: " + "no session will be returned.");
         }
         return null;
      }
   
      //
      // If we reach here, we are sure that the underlying HttpSession is
      // available. If we haven't created and cached a portlet session
      // instance, we will create and cache one now.
      //
   
      final ContainerServices containerServices = container.getContainerServices();
      final PortletEnvironmentService portletEnvironmentService = containerServices.getPortletEnvironmentService();

      cachedPortletSession = new CachedPortletSessionImpl(portletEnvironmentService.createPortletSession(
          portletConfig.getPortletContext(), getPortletWindow(), httpSession));

      if (CachedPortletSessionUtil.INVALIDATED_SESSIONS.containsKey(httpSession.getId())) {

         synchronized (httpSession) {
            Enumeration<String> attributeNames = httpSession.getAttributeNames();
            if (attributeNames.hasMoreElements()) {
               while (attributeNames.hasMoreElements()) {
                  String attributeName = attributeNames.nextElement();
                  httpSession.removeAttribute(attributeName);
               }
               CachedPortletSessionUtil.INVALIDATED_SESSIONS.remove(httpSession.getId());
            }
         }
      }
   }

   return cachedPortletSession;
}
 
Example 6
Source Project: jease   File: TableModel.java    License: GNU General Public License v3.0 5 votes vote down vote up
private long getLastAccessedTime(User user) {
	long lastAccessedTime = 0;
	for (HttpSession session : JeaseSessionListener.getSessions()) {
		if (user.equals(session.getAttribute(user.getClass().toString()))
				&& lastAccessedTime < session.getLastAccessedTime()) {
			lastAccessedTime = session.getLastAccessedTime();
		}
	}
	return lastAccessedTime;
}
 
Example 7
Source Project: hasor   File: WebUdfSource.java    License: Apache License 2.0 5 votes vote down vote up
/** 返回客户端发送与之关联的请求的最后一次时间. */
public static long sessionLastAccessedTime() {
    HttpSession httpSession = FxWebInterceptor.servletSession();
    if (httpSession == null) {
        return 0;
    }
    return httpSession.getLastAccessedTime();
}
 
Example 8
Source Project: olat   File: OLATHttpSessionListener.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void sessionDestroyed(HttpSessionEvent se) {
    final HttpSession session = se.getSession();
    final int duration = (int) ((System.currentTimeMillis() - session.getCreationTime()) / 1000);
    final int inactivity = (int) ((System.currentTimeMillis() - session.getLastAccessedTime()) / 1000);
    final String sessionInfo = "[id=" + se.getSession().getId() + ", timeout=" + se.getSession().getMaxInactiveInterval() + "s, duration=" + duration
            + "s, inactivity=" + inactivity + "s]";
    final boolean expired = inactivity >= session.getMaxInactiveInterval();
    if (expired) {
        log.debug("HTTP session timed out " + sessionInfo);
    } else {
        log.debug("HTTP session closed " + sessionInfo);
    }
}
 
Example 9
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	// 如果不存在 session 会话,则创建一个 session 对象
	HttpSession session = request.getSession(true);
	// 获取 session 创建时间
	Date createTime = new Date(session.getCreationTime());
	// 获取该网页的最后一次访问时间
	Date lastAccessTime = new Date(session.getLastAccessedTime());

	// 设置日期输出的格式
	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	String title = "Servlet Session 实例";
	Integer visitCount = new Integer(0);
	String visitCountKey = new String("visitCount");
	String userIDKey = new String("userID");
	String userID = new String("admin");

	// 检查网页上是否有新的访问者
	if (session.isNew()) {
		session.setAttribute(userIDKey, userID);
	} else {
		visitCount = (Integer) session.getAttribute(visitCountKey);
		visitCount = visitCount + 1;
		userID = (String) session.getAttribute(userIDKey);
	}
	session.setAttribute(visitCountKey, visitCount);

	// 设置响应内容类型
	response.setContentType("text/html;charset=UTF-8");
	PrintWriter out = response.getWriter();

	String docType = "<!DOCTYPE html>\n";
	out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n"
		+ "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n"
		+ "<h2 align=\"center\">Session 信息</h2>\n" + "<table border=\"1\" align=\"center\">\n"
		+ "<tr bgcolor=\"#949494\">\n" + "  <th>Session 信息</th><th>值</th></tr>\n" + "<tr>\n" + "  <td>id</td>\n"
		+ "  <td>" + session.getId() + "</td></tr>\n" + "<tr>\n" + "  <td>创建时间</td>\n" + "  <td>"
		+ df.format(createTime) + "  </td></tr>\n" + "<tr>\n" + "  <td>最后访问时间</td>\n" + "  <td>"
		+ df.format(lastAccessTime) + "  </td></tr>\n" + "<tr>\n" + "  <td>用户 ID</td>\n" + "  <td>" + userID
		+ "  </td></tr>\n" + "<tr>\n" + "  <td>访问统计:</td>\n" + "  <td>" + visitCount + "</td></tr>\n"
		+ "</table>\n" + "</body></html>");
}