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

The following examples show how to use javax.servlet.http.HttpSession#getMaxInactiveInterval() . 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
Source File: SessionController.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
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
Source File: UserSession.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * @param hreq
 * @return associated user session
 */
public static UserSession getUserSession(HttpServletRequest hreq) {
    // get existing or create new session
    final HttpSession httpSession = hreq.getSession(true);
    if (httpSession.isNew()) {
        // set a possibly changed session timeout interval
        int currentSessionTimeout = httpSession.getMaxInactiveInterval();
        if (currentSessionTimeout != getGlobalSessionTimeout()) {
            httpSession.setMaxInactiveInterval(getGlobalSessionTimeout());
            if (log.isDebugEnabled()) {
                log.debug("HTTP session timeout changed [id=" + httpSession.getId() + ": " + currentSessionTimeout + "s => " + getGlobalSessionTimeout() + "s]");
            }
        }
    }

    return getUserSession(httpSession);
}
 
Example 3
Source File: PortletRequestContextImpl.java    From portals-pluto with Apache License 2.0 6 votes vote down vote up
/**
 * 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 4
Source File: ApplicationBean.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * @return the interval of keepAlive tag
 */
public Long getInterval() {
    if (interval == null) {
        FacesContext ctx = getFacesContext();
        HttpSession httpSession = (HttpSession) ctx.getExternalContext()
                .getSession(false);
        int maxInactiveInterval = httpSession.getMaxInactiveInterval();
        // To keep session alive, the interval value is 1 minute less than
        // session timeout.
        long intervalValue = (long) maxInactiveInterval * 1000 - 60000L;
        interval = Long.valueOf(intervalValue);
    }
    return interval;
}
 
Example 5
Source File: ApplicationBean.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * @return the interval of keepAlive tag
 */
public Long getInterval() {
    if (interval == null) {
        FacesContext ctx = getFacesContext();
        HttpSession httpSession = (HttpSession) ctx.getExternalContext()
                .getSession(false);
        int maxInactiveInterval = httpSession.getMaxInactiveInterval();
        // To keep session alive, the interval value is 1 minute less than
        // session timeout.
        long intervalValue = (long) maxInactiveInterval * 1000 - 60000L;
        interval = Long.valueOf(intervalValue);
    }
    return interval;
}
 
Example 6
Source File: DashboardController.java    From find with MIT License 5 votes vote down vote up
@RequestMapping(method = RequestMethod.POST, value = DASHBOARD_KEEP_ALIVE)
@ResponseBody
public int keepAlive(final HttpServletRequest request, final HttpSession session) {
    final String logMessage = Optional
        // "referer" will be null if the config was reloaded by typing the endpoint URL
        // into the browser, rather than by clicking the reload button
        .ofNullable(request.getHeader(HttpHeaders.REFERER))
        .flatMap(this::getDecodedDashboardNameFromUrl)
        .map(dashboardName -> "Session extended by fullscreen dashboard " + dashboardName)
        .orElse("Session extended by fullscreen dashboard.");

    log.info(logMessage);

    return session.getMaxInactiveInterval();
}
 
Example 7
Source File: LogoutPanel.java    From webanno with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if auto-logout is enabled. For Winstone, we get a max session length of 0, so here it
 * is disabled.
 */
private int getAutoLogoutTime()
{
    int duration = 0;
    Request request = RequestCycle.get().getRequest();
    if (request instanceof ServletWebRequest) {
        HttpSession session = ((ServletWebRequest) request).getContainerRequest().getSession();
        if (session != null) {
            duration = session.getMaxInactiveInterval();
        }
    }        
    return duration;
}
 
Example 8
Source File: NamedLock.java    From ontopia with Apache License 2.0 5 votes vote down vote up
public void setExpiry(HttpSession session) {
  if (!NamedLockManager.usesTimedLockExpiry(session))
    return;

  this.timestamp = System.currentTimeMillis()
      + (session.getMaxInactiveInterval() * 1000);
}
 
Example 9
Source File: OLATHttpSessionListener.java    From olat with 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 10
Source File: UIKeepSessionAlive.java    From XPagesExtensionLibrary with Apache License 2.0 5 votes vote down vote up
private int getSessionMaxInactiveInterval(HttpSession session) {
    try {
        return session.getMaxInactiveInterval();
    } catch(UnsupportedOperationException ex) {
        // For the unit tests - should not happen in prod
        return 30 * 60;
    }
}
 
Example 11
Source File: LoginController.java    From spring-data-rest-acl with Apache License 2.0 5 votes vote down vote up
/**
 * api to set session timeout for current HttpSession. timeoutInSeconds is
 * optional parameter. If not set, will be defaulted to 24 hours (86400s)
 * 
 * @param timeoutInSeconds
 * @param httpSession
 * @return
 */
@RequestMapping(method = RequestMethod.PUT, value = "/loginsession/timeout")
public @ResponseBody
String setSessionTimeout(
		@RequestParam(value = "timeoutInSeconds", defaultValue = "86400") int timeoutInSeconds,
		HttpSession httpSession) {
	httpSession.setMaxInactiveInterval(timeoutInSeconds);
	return "httpSession timeout set to:"
			+ httpSession.getMaxInactiveInterval();
}
 
Example 12
Source File: ViewingSessionUtil.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the BIRT viewing session manager for the current HTTP session. If none is
 * available, creates one.
 * 
 * @param request
 *            request
 * @param create
 *            create flag, if true and no BIRT viewing session manager exists in the
 *            session, then create one.
 * @return instance of BIRT viewing session manager associated with the current HTTP
 *         session
 */
public static IViewingSessionManager getSessionManager(
		HttpServletRequest request, boolean create )
{
	HttpSession httpSession = request.getSession( create );
	if ( httpSession != null )
	{
		IViewingSessionManager sessionManager = (IViewingSessionManager) httpSession
				.getAttribute( IBirtConstants.ATTRIBUTE_VIEWING_SESSION_MANAGER );
		if ( sessionManager == null && create )
		{
			long aSessionTimeout = defaultConfig.getSessionTimeout( );
			if ( aSessionTimeout == 0l )
			{
				// defaults to the master session value
				aSessionTimeout = httpSession.getMaxInactiveInterval( );
				// infinite session is not allowed because it would cause
				// the cache to increase without ever being cleaned
				if ( aSessionTimeout <= 0 )
				{
					aSessionTimeout = ViewingSessionConfig.DEFAULT_SESSION_TIMEOUT;
				}					
				defaultConfig.setSessionTimeout( aSessionTimeout );
			}
			sessionManager = new ViewingSessionManager(viewingCache,
					httpSession.getId( ),
					defaultConfig
					);
			httpSession.setAttribute(
					IBirtConstants.ATTRIBUTE_VIEWING_SESSION_MANAGER,
					sessionManager );
		}
		return sessionManager;
	}
	else
	{
		return null;
	}
}
 
Example 13
Source File: SessionIdUserTokenParser.java    From hsweb-framework with Apache License 2.0 4 votes vote down vote up
@Override
public ParsedToken parseToken(HttpServletRequest request) {

    HttpSession session = request.getSession(false);

    if (session != null) {
        String sessionId = session.getId();
        UserToken token = userTokenManager.getByToken(sessionId);
        long interval = session.getMaxInactiveInterval();
        //当前已登录token已失效但是session未失效
        if (token != null && token.isExpired()) {
            String userId = token.getUserId();
            return new AuthorizedToken() {
                @Override
                public String getUserId() {
                    return userId;
                }

                @Override
                public String getToken() {
                    return sessionId;
                }

                @Override
                public String getType() {
                    return TOKEN_TYPE_SESSION_ID;
                }

                @Override
                public long getMaxInactiveInterval() {
                    return interval;
                }
            };
        }
        return new ParsedToken() {
            @Override
            public String getToken() {
                return session.getId();
            }

            @Override
            public String getType() {
                return TOKEN_TYPE_SESSION_ID;
            }
        };
    }
    return null;
}
 
Example 14
Source File: SessionBean.java    From yawl with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void resetSessionTimeout() {
    HttpSession session = getExternalSession();
     if (defaultSessionTimeoutValue != session.getMaxInactiveInterval()) {
         session.setMaxInactiveInterval(defaultSessionTimeoutValue);
     }
}
 
Example 15
Source File: SessionBean.java    From yawl with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void resetSessionTimeout() {
    HttpSession session = getExternalSession();
     if (defaultSessionTimeoutValue != session.getMaxInactiveInterval()) {
         session.setMaxInactiveInterval(defaultSessionTimeoutValue);
     }
}
 
Example 16
Source File: SessionRestController.java    From tutorials with MIT License 4 votes vote down vote up
@GetMapping("/session-max-interval")
public String retrieveMaxSessionInactiveInterval(HttpSession session) {
    return "Max Inactive Interval before Session expires: " + session.getMaxInactiveInterval();
}