Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   //
   //  ========================================================================
   //  Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd.
   //  ------------------------------------------------------------------------
   //  All rights reserved. This program and the accompanying materials
   //  are made available under the terms of the Eclipse Public License v1.0
   //  and Apache License v2.0 which accompanies this distribution.
   //
   //      The Eclipse Public License is available at
  //      http://www.eclipse.org/legal/epl-v10.html
  //
  //      The Apache License v2.0 is available at
  //      http://www.opensource.org/licenses/apache2.0.php
  //
  //  You may elect to redistribute this code under either of these licenses.
  //  ========================================================================
  //
  
  package org.eclipse.jetty.server.session;
  
  import static java.lang.Math.round;
  
  import java.util.Arrays;
  import java.util.HashSet;
  import java.util.HashMap;
  import java.util.List;
  import java.util.Map;
  import java.util.Set;
  
  
  
  /* ------------------------------------------------------------ */
An Abstract implementation of SessionManager. The partial implementation of SessionManager interface provides the majority of the handling required to implement a SessionManager. Concrete implementations of SessionManager based on AbstractSessionManager need only implement the newSession method to return a specialised version of the Session inner class that provides an attribute Map.

  
  @SuppressWarnings("deprecation")
  public abstract class AbstractSessionManager extends AbstractLifeCycle implements SessionManager
  {
      final static Logger __log = .;
  
          Collections.unmodifiableSet(
              new HashSet<SessionTrackingMode>(
                      Arrays.asList(new SessionTrackingMode[]{.,.})));
          
      public final static String SESSION_KNOWN_ONLY_TO_AUTHENTICATED="org.eclipse.jetty.security.sessionKnownOnlytoAuthenticated";
      
      /* ------------------------------------------------------------ */
      public final static int __distantFuture=60*60*24*7*52*20;
  
      {
          public HttpSession getSession(String sessionId)
          {
              return null;
          }
          
          @SuppressWarnings({ "rawtypes""unchecked" })
          public Enumeration getIds()
          {
              return Collections.enumeration(.);
          }
      };
      
      private boolean _usingCookies=true;
  
      /* ------------------------------------------------------------ */
      // Setting of max inactive interval for new sessions
     // -1 means no timeout
     protected int _dftMaxIdleSecs=-1;
     protected SessionHandler _sessionHandler;
     protected boolean _httpOnly=false;
     protected SessionIdManager _sessionIdManager;
     protected boolean _secureCookies=false;
     protected boolean _secureRequestOnly=true;
 
 
     protected ClassLoader _loader;
     protected ContextHandler.Context _context;
     protected String _sessionDomain;
     protected String _sessionPath;
     protected int _maxCookieAge=-1;
     protected int _refreshCookieAge;
     protected boolean _nodeIdInSessionId;
     protected boolean _checkingRemoteSessionIdEncoding;
     protected String _sessionComment;
 
 
     private boolean _usingURLs;
     
     protected final CounterStatistic _sessionsStats = new CounterStatistic();
     protected final SampleStatistic _sessionTimeStats = new SampleStatistic();
     
     
     /* ------------------------------------------------------------ */
     public static HttpSession renewSession (HttpServletRequest requestHttpSession httpSessionboolean authenticated)
     {
         Map<String,Objectattributes = new HashMap<StringObject>();
 
         for (Enumeration<Stringe=httpSession.getAttributeNames();e.hasMoreElements();)
         {
             String name=e.nextElement();
             attributes.put(name,httpSession.getAttribute(name));
             httpSession.removeAttribute(name);
         }
 
         httpSession.invalidate();       
         httpSession = request.getSession(true);
         if (authenticated)
             httpSession.setAttribute(.);
         for (Map.Entry<StringObjectentryattributes.entrySet())
             httpSession.setAttribute(entry.getKey(),entry.getValue());
         return httpSession;
     }
     
     /* ------------------------------------------------------------ */
     public AbstractSessionManager()
     {
     }
 
     /* ------------------------------------------------------------ */
     public ContextHandler.Context getContext()
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
     {
         return .getContextHandler();
     }
     
     public String getSessionPath()
     {
         return ;
     }
 
     public int getMaxCookieAge()
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
     public HttpCookie access(HttpSession session,boolean secure)
     {
         long now=System.currentTimeMillis();
 
         AbstractSession s = ((SessionIf)session).getSession();
 
        if (s.access(now))
        {
             // Do we need to refresh the cookie?
             if (isUsingCookies() &&
                 (s.isIdChanged() ||
                 (getSessionCookieConfig().getMaxAge()>0 && getRefreshCookieAge()>0 && ((now-s.getCookieSetTime())/1000>getRefreshCookieAge()))
                 )
                )
             {
                 HttpCookie cookie=getSessionCookie(session,==null?"/":(.getContextPath()),secure);
                 s.cookieSet();
                 s.setIdChanged(false);
                 return cookie;
             }
         }
         return null;
     }
 
     /* ------------------------------------------------------------ */
     public void addEventListener(EventListener listener)
     {
         if (listener instanceof HttpSessionAttributeListener)
             .add((HttpSessionAttributeListener)listener);
         if (listener instanceof HttpSessionListener)
             .add((HttpSessionListener)listener);
     }
 
     /* ------------------------------------------------------------ */
     public void clearEventListeners()
     {
         .clear();
     }
 
     /* ------------------------------------------------------------ */
     public void complete(HttpSession session)
     {
         AbstractSession s = ((SessionIf)session).getSession();
         s.complete();
     }
 
     /* ------------------------------------------------------------ */
     @Override
     public void doStart() throws Exception
     {
         =ContextHandler.getCurrentContext();
         =Thread.currentThread().getContextClassLoader();
 
         if (==null)
         {
             final Server server=getSessionHandler().getServer();
             synchronized (server)
             {
                 =server.getSessionIdManager();
                 if (==null)
                 {
                     =new HashSessionIdManager();
                     server.setSessionIdManager();
                 }
             }
         }
         if (!.isStarted())
             .start();
 
         // Look for a session cookie name
         if (!=null)
         {
             if (tmp!=null)
                 =tmp;
 
             if (tmp!=null)
                 setSessionIdPathParameterName(tmp);
 
             // set up the max session cookie age if it isn't already
             if (==-1)
             {
                 tmp=.getInitParameter(.);
                 if (tmp!=null)
                     =Integer.parseInt(tmp.trim());
             }
 
             // set up the session domain if it isn't already
             if (==null)
 
             // set up the sessionPath if it isn't already
             if (==null)
             
             if (tmp!=null)
                 =Boolean.parseBoolean(tmp);
         }
 
         super.doStart();
     }
 
     /* ------------------------------------------------------------ */
     @Override
     public void doStop() throws Exception
     {
         super.doStop();
 
         invalidateSessions();
 
         =null;
     }
 
     /* ------------------------------------------------------------ */
    

Returns:
Returns the httpOnly.
 
     public boolean getHttpOnly()
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
     public HttpSession getHttpSession(String nodeId)
     {
         String cluster_id = getSessionIdManager().getClusterId(nodeId);
 
         AbstractSession session = getSession(cluster_id);
         if (session!=null && !session.getNodeId().equals(nodeId))
             session.setIdChanged(true);
         return session;
     }
 
     /* ------------------------------------------------------------ */
    

Deprecated:
Use getSessionIdManager()
Returns:
Returns the metaManager used for cross context session management
 
     public SessionIdManager getIdManager()
     {
         return getSessionIdManager();
     }
     
     /* ------------------------------------------------------------ */
    

Returns:
Returns the SessionIdManager used for cross context session management
 
     {
         return ;
     }
 
 
     /* ------------------------------------------------------------ */
    

Returns:
seconds
 
     @Override
     public int getMaxInactiveInterval()
     {
         return ;
     }
     
     /* ------------------------------------------------------------ */
    
 
     @Deprecated
     public int getMaxSessions()
     {
         return getSessionsMax();
     }
 
     /* ------------------------------------------------------------ */
    

Returns:
maximum number of sessions
 
     public int getSessionsMax()
     {
         return (int).getMax();
     }
 
     /* ------------------------------------------------------------ */
    

Returns:
total number of sessions
 
     public int getSessionsTotal()
     {
         return (int).getTotal();
     }
 
     /* ------------------------------------------------------------ */
    

Deprecated:
use getSessionIdManager()
 
     @Deprecated
     public SessionIdManager getMetaManager()
     {
         return getSessionIdManager();
     }
 
     /* ------------------------------------------------------------ */
    

Deprecated:
always returns 0. no replacement available.
 
     @Deprecated
     public int getMinSessions()
     {
         return 0;
     }
 
     /* ------------------------------------------------------------ */
     public int getRefreshCookieAge()
     {
         return ;
     }
 
 
     /* ------------------------------------------------------------ */
    

Returns:
same as SessionCookieConfig.getSecure(). If true, session cookies are ALWAYS marked as secure. If false, a session cookie is ONLY marked as secure if _secureRequestOnly == true and it is a HTTPS request.
 
     public boolean getSecureCookies()
     {
         return ;
     }
     
     /* ------------------------------------------------------------ */
    

Returns:
true if session cookie is to be marked as secure only on HTTPS requests
 
     public boolean isSecureRequestOnly()
     {
         return ;
     }
     
     
     /* ------------------------------------------------------------ */
    

Returns:
if true, session cookie will be marked as secure only iff HTTPS request. Can be overridden by setting SessionCookieConfig.setSecure(true), in which case the session cookie will be marked as secure on both HTTPS and HTTP.
 
     public void setSecureRequestOnly(boolean secureRequestOnly)
     {
          = secureRequestOnly;
     }
 
     
     
     /* ------------------------------------------------------------ */
     public String getSessionCookie()
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
    
A sessioncookie is marked as secure IFF any of the following conditions are true:
  1. SessionCookieConfig.setSecure == true
  2. SessionCookieConfig.setSecure == false && _secureRequestOnly==true && request is HTTPS
According to SessionCookieConfig javadoc, case 1 can be used when: "... even though the request that initiated the session came over HTTP, is to support a topology where the web container is front-ended by an SSL offloading load balancer. In this case, the traffic between the client and the load balancer will be over HTTPS, whereas the traffic between the load balancer and the web container will be over HTTP." For case 2, you can use _secureRequestOnly to determine if you want the Servlet Spec 3.0 default behaviour when SessionCookieConfig.setSecure==false, which is: "they shall be marked as secure only if the request that initiated the corresponding session was also secure" The default for _secureRequestOnly is true, which gives the above behaviour. If you set it to false, then a session cookie is NEVER marked as secure, even if the initiating request was secure.

 
     public HttpCookie getSessionCookie(HttpSession sessionString contextPathboolean requestIsSecure)
     {
         if (isUsingCookies())
         {
             String sessionPath = (==null) ? contextPath : ;
             sessionPath = (sessionPath==null||sessionPath.length()==0) ? "/" : sessionPath;
             String id = getNodeId(session);
             HttpCookie cookie = null;
             if ( == null)
             {
                 cookie = new HttpCookie(
                                         ,
                                         id,
                                         ,
                                         sessionPath,
                                         .getMaxAge(),
                                         .isHttpOnly(),
                                         .isSecure() || (isSecureRequestOnly() && requestIsSecure));                  
             }
             else
             {
                 cookie = new HttpCookie(
                                         ,
                                         id,
                                         ,
                                         sessionPath,
                                         .getMaxAge(),
                                         .isHttpOnly(),
                                         .isSecure() || (isSecureRequestOnly() && requestIsSecure),
                                         ,
                                         1);    
             }
 
             return cookie;
         }
         return null;
     }
 
     public String getSessionDomain()
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
    

Returns:
Returns the sessionHandler.
 
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
    

Deprecated:
Need to review if it is needed.
 
     @SuppressWarnings("rawtypes")
     public Map getSessionMap()
     {
         throw new UnsupportedOperationException();
     }
 
    
 
     /* ------------------------------------------------------------ */
     public int getSessions()
     {
         return (int).getCurrent();
     }
 
     /* ------------------------------------------------------------ */
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
    

Returns:
Returns the usingCookies.
 
     public boolean isUsingCookies()
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
     public boolean isValid(HttpSession session)
     {
         AbstractSession s = ((SessionIf)session).getSession();
         return s.isValid();
     }
 
     /* ------------------------------------------------------------ */
     public String getClusterId(HttpSession session)
     {
         AbstractSession s = ((SessionIf)session).getSession();
         return s.getClusterId();
     }
 
     /* ------------------------------------------------------------ */
     public String getNodeId(HttpSession session)
     {
         AbstractSession s = ((SessionIf)session).getSession();
         return s.getNodeId();
     }
 
     /* ------------------------------------------------------------ */
    
Create a new HttpSession for a request
 
     public HttpSession newHttpSession(HttpServletRequest request)
     {
         AbstractSession session=newSession(request);
         session.setMaxInactiveInterval();
         addSession(session,true);
         return session;
     }
 
     /* ------------------------------------------------------------ */
     public void removeEventListener(EventListener listener)
     {
         if (listener instanceof HttpSessionAttributeListener)
             .remove(listener);
         if (listener instanceof HttpSessionListener)
             .remove(listener);
     }
     
     /* ------------------------------------------------------------ */
    

See also:
statsReset()
 
     @Deprecated
     public void resetStats()
     {
         statsReset();
     }
 
     /* ------------------------------------------------------------ */
    
Reset statistics values
 
     public void statsReset()
     {
         .reset(getSessions());
         .reset();
     }
 
     /* ------------------------------------------------------------ */
    

Parameters:
httpOnly The httpOnly to set.
 
     public void setHttpOnly(boolean httpOnly)
     {
         =httpOnly;
     }
 
     /* ------------------------------------------------------------ */
    

Deprecated:
use setSessionIdManager(org.eclipse.jetty.server.SessionIdManager)
Parameters:
metaManager The metaManager used for cross context session management.
 
     public void setIdManager(SessionIdManager metaManager)
     {
         setSessionIdManager(metaManager);
     }
     
     /* ------------------------------------------------------------ */
    

Parameters:
metaManager The metaManager used for cross context session management.
 
     public void setSessionIdManager(SessionIdManager metaManager)
     {
         =metaManager;
     }
 
 
 
     /* ------------------------------------------------------------ */
    

Parameters:
seconds
 
     public void setMaxInactiveInterval(int seconds)
     {
         =seconds;
     }
 
 
     /* ------------------------------------------------------------ */
     public void setRefreshCookieAge(int ageInSeconds)
     {
         =ageInSeconds;
     }
 
 
 
     public void setSessionCookie(String cookieName)
     {
         =cookieName;
     }
 
 
 
     /* ------------------------------------------------------------ */
    

Parameters:
sessionHandler The sessionHandler to set.
 
     public void setSessionHandler(SessionHandler sessionHandler)
     {
         =sessionHandler;
     }
 
  
     /* ------------------------------------------------------------ */
     public void setSessionIdPathParameterName(String param)
     {
          =(param==null||"none".equals(param))?null:param;
          =(param==null||"none".equals(param))?null:(";" +"=");
     }
     /* ------------------------------------------------------------ */
    

Parameters:
usingCookies The usingCookies to set.
 
     public void setUsingCookies(boolean usingCookies)
     {
         =usingCookies;
     }
 
 
     protected abstract void addSession(AbstractSession session);
 
     /* ------------------------------------------------------------ */
    
Add the session Registers the session with this manager and registers the session ID with the sessionIDManager;
 
     protected void addSession(AbstractSession sessionboolean created)
     {
         synchronized ()
         {
             .addSession(session);
             addSession(session);
         }
 
         if (created)
         {
             .increment();
             if (!=null)
             {
                 HttpSessionEvent event=new HttpSessionEvent(session);
                 for (HttpSessionListener listener : )
                     listener.sessionCreated(event);
             }
         }
     }
 
     /* ------------------------------------------------------------ */
    
Get a known existing session

Parameters:
idInCluster The session ID in the cluster, stripped of any worker name.
Returns:
A Session or null if none exists.
 
     public abstract AbstractSession getSession(String idInCluster);
 
     protected abstract void invalidateSessions() throws Exception;
 
 
     /* ------------------------------------------------------------ */
    
Create a new session instance

Parameters:
request
Returns:
the new session
 
     protected abstract AbstractSession newSession(HttpServletRequest request);
 
 
     /* ------------------------------------------------------------ */
    

Returns:
true if the cluster node id (worker id) is returned as part of the session id by javax.servlet.http.HttpSession.getId(). Default is false.
 
     public boolean isNodeIdInSessionId()
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
    

Parameters:
nodeIdInSessionId true if the cluster node id (worker id) will be returned as part of the session id by javax.servlet.http.HttpSession.getId(). Default is false.
 
     public void setNodeIdInSessionId(boolean nodeIdInSessionId)
     {
         =nodeIdInSessionId;
     }
 
     /* ------------------------------------------------------------ */
    
Remove session from manager

 
     public void removeSession(HttpSession sessionboolean invalidate)
     {
         AbstractSession s = ((SessionIf)session).getSession();
         removeSession(s,invalidate);
     }
 
     /* ------------------------------------------------------------ */
    
Remove session from manager

 
     public void removeSession(AbstractSession sessionboolean invalidate)
     {
         // Remove session from context and global maps
         boolean removed = removeSession(session.getClusterId());
         
         if (removed)
         {
             .decrement();
             .set(round((System.currentTimeMillis() - session.getCreationTime())/1000.0));
             
             // Remove session from all context and global id maps
             .removeSession(session);
             if (invalidate)
                 .invalidateAll(session.getClusterId());
             
             if (invalidate && !=null)
             {
                 HttpSessionEvent event=new HttpSessionEvent(session);
                 for (HttpSessionListener listener : )
                     listener.sessionDestroyed(event);
             }
         }
     }
 
     /* ------------------------------------------------------------ */
     protected abstract boolean removeSession(String idInCluster);
     
     /* ------------------------------------------------------------ */
    

Returns:
maximum amount of time session remained valid
 
     public long getSessionTimeMax()
     {
         return .getMax();
     }
 
     /* ------------------------------------------------------------ */
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
     {
         return Collections.unmodifiableSet();
     }
 
     /* ------------------------------------------------------------ */
     @Override
     public void setSessionTrackingModes(Set<SessionTrackingModesessionTrackingModes)
     {
         =new HashSet<SessionTrackingMode>(sessionTrackingModes);
     }
 
     /* ------------------------------------------------------------ */
     @Override
     public boolean isUsingURLs()
     {
         return ;
     }
 
 
     /* ------------------------------------------------------------ */
     {
         return ;
     } 
 
     /* ------------------------------------------------------------ */
     private SessionCookieConfig _cookieConfig =
         new SessionCookieConfig()
         {
             @Override
             public String getComment()
             {
                 return ;
             }
 
             @Override
             public String getDomain()
             {
                 return ;
             }
 
             @Override
             public int getMaxAge()
             {
                 return ;
             }
 
             @Override
             public String getName()
             {
                 return ;
             }
 
             @Override
             public String getPath()
             {
                 return ;
             }
 
             @Override
             public boolean isHttpOnly()
             {
                 return ;
             }
 
             @Override
             public boolean isSecure()
             {
                 return ;
             }
 
             @Override
             public void setComment(String comment)
             {
                  = comment
             }
 
             @Override
             public void setDomain(String domain)
             {
                 =domain;
             }
 
             @Override
             public void setHttpOnly(boolean httpOnly)
             {
                 =httpOnly;
             }
 
             @Override
             public void setMaxAge(int maxAge)
             {
                 =maxAge;
             }
 
             @Override
             public void setName(String name)
             {
                 =name;
             }
 
             @Override
             public void setPath(String path)
             {
                 =path;
             }
 
             @Override
             public void setSecure(boolean secure)
             {
                 =secure;
             }
         
         };
 
 
     /* ------------------------------------------------------------ */
    

Returns:
total amount of time all sessions remained valid
 
     public long getSessionTimeTotal()
     {
         return .getTotal();
     }
     
     /* ------------------------------------------------------------ */
    

Returns:
mean amount of time session remained valid
 
     public double getSessionTimeMean()
     {
         return .getMean();
     }
     
     /* ------------------------------------------------------------ */
    

Returns:
standard deviation of amount of time session remained valid
 
     public double getSessionTimeStdDev()
     {
         return .getStdDev();
     }
 
     /* ------------------------------------------------------------ */
    
 
     public boolean isCheckingRemoteSessionIdEncoding()
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
    
 
     public void setCheckingRemoteSessionIdEncoding(boolean remote)
     {
         =remote;
     }
     
     /* ------------------------------------------------------------ */
     /* ------------------------------------------------------------ */
     /* ------------------------------------------------------------ */
    
Interface that any session wrapper should implement so that SessionManager may access the Jetty session implementation.
    public interface SessionIf extends HttpSession
    {
        public AbstractSession getSession();
    }
    public void doSessionAttributeListeners(AbstractSession sessionString nameObject oldObject value)
    {
        if (!.isEmpty())
        {
            HttpSessionBindingEvent event=new HttpSessionBindingEvent(session,name,old==null?value:old);
            for (HttpSessionAttributeListener l : )
            {
                if (old==null)
                    l.attributeAdded(event);
                else if (value==null)
                    l.attributeRemoved(event);
                else
                    l.attributeReplaced(event);
            }
        }
    }