sessionmanager.java

来自「RESIN 3.2 最新源码」· Java 代码 · 共 1,493 行 · 第 1/3 页

JAVA
1,493
字号
/* * Copyright (c) 1998-2008 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT.  See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * *   Free Software Foundation, Inc. *   59 Temple Place, Suite 330 *   Boston, MA 02111-1307  USA * * @author Scott Ferguson */package com.caucho.server.session;import com.caucho.config.Config;import com.caucho.config.ConfigException;import com.caucho.config.types.Period;import com.caucho.hessian.io.*;import com.caucho.management.server.SessionManagerMXBean;import com.caucho.server.cluster.Cluster;import com.caucho.server.cluster.ClusterObject;import com.caucho.server.cluster.ClusterServer;import com.caucho.server.cluster.Store;import com.caucho.server.cluster.StoreManager;import com.caucho.server.dispatch.DispatchServer;import com.caucho.server.dispatch.InvocationDecoder;import com.caucho.server.resin.Resin;import com.caucho.server.security.ServletAuthenticator;import com.caucho.server.webapp.WebApp;import com.caucho.util.Alarm;import com.caucho.util.AlarmListener;import com.caucho.util.L10N;import com.caucho.util.LruCache;import com.caucho.util.RandomUtil;import javax.naming.Context;import javax.naming.InitialContext;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSessionActivationListener;import javax.servlet.http.HttpSessionAttributeListener;import javax.servlet.http.HttpSessionEvent;import javax.servlet.http.HttpSessionListener;import java.io.*;import java.util.ArrayList;import java.util.Iterator;import java.util.logging.Level;import java.util.logging.Logger;// import com.caucho.server.http.ServletServer;// import com.caucho.server.http.VirtualHost;/** * Manages sessions in a web-webApp. */public final class SessionManager implements AlarmListener{  static protected final L10N L = new L10N(SessionManager.class);  static protected final Logger log    = Logger.getLogger(SessionManager.class.getName());  private static final int FALSE = 0;  private static final int COOKIE = 1;  private static final int TRUE = 2;  private static final int UNSET = 0;  private static final int SET_TRUE = 1;  private static final int SET_FALSE = 2;  private static final int SAVE_BEFORE_HEADERS = 0x1;  private static final int SAVE_BEFORE_FLUSH = 0x2;  private static final int SAVE_AFTER_REQUEST = 0x4;  private static final int SAVE_ON_SHUTDOWN = 0x8;    private final WebApp _webApp;  private final SessionManagerAdmin _admin;    private final Cluster _cluster;  private final int _selfIndex;    private final SessionObjectManager _objectManager;  // active sessions  private LruCache<String,SessionImpl> _sessions;  // total sessions  private int _totalSessions;    // iterator to purge sessions (to reduce gc)  private Iterator<SessionImpl> _sessionIter;  // array list for session timeout  private ArrayList<SessionImpl> _sessionList = new ArrayList<SessionImpl>();  // generate cookies  private boolean _enableSessionCookies = true;  // allow session rewriting  private boolean _enableSessionUrls = true;  private boolean _isModuloSessionId = false;  private boolean _isAppendServerIndex = false;  private boolean _isTwoDigitSessionIndex = false;    // invalidate the session after the listeners have been called  private boolean _isInvalidateAfterListener;  // maximum number of sessions  private int _sessionMax = 8192;  // how long a session will be inactive before it times out  private long _sessionTimeout = 30 * 60 * 1000;  private String _cookieName = "JSESSIONID";  private String _sslCookieName;    // Rewriting strings.  private String _sessionSuffix = ";jsessionid=";  private String _sessionPrefix;    // default cookie version  private int _cookieVersion;  private String _cookieDomain;  private long _cookieMaxAge;  private boolean _cookieSecure;  private int _isCookieHttpOnly;  private String _cookiePort;  private int _reuseSessionId = COOKIE;  private int _cookieLength = 21;  private int _sessionSaveMode = SAVE_AFTER_REQUEST;  //private SessionStore sessionStore;  private StoreManager _storeManager;  // If true, serialization errors should not be logged  // XXX: changed for JSF  private boolean _ignoreSerializationErrors = true;  private boolean _isHessianSerialization = true;  // List of the HttpSessionListeners from the configuration file  private ArrayList<HttpSessionListener> _listeners;    // List of the HttpSessionListeners from the configuration file  private ArrayList<HttpSessionActivationListener> _activationListeners;    // List of the HttpSessionAttributeListeners from the configuration file  private ArrayList<HttpSessionAttributeListener> _attributeListeners;  //  // Compatibility fields  //    private boolean _isWebAppStore; // i.e. for old-style compatibility  private Store _sessionStore;  private int _alwaysLoadSession;  private int _alwaysSaveSession;  private boolean _isClosed;  private String _distributionId;  private Alarm _alarm;  // statistics  private Object _statisticsLock = new Object();  private long _sessionCreateCount;  private long _sessionTimeoutCount;  private long _sessionInvalidateCount;  /**   * Creates and initializes a new session manager   *   * @param webApp the web-webApp webApp   */  public SessionManager(WebApp webApp)    throws Exception  {    _webApp = webApp;        _cluster = webApp.getCluster();    if (_cluster != null)      _selfIndex = _cluster.getSelfServer().getIndex();    else      _selfIndex = 0;    _objectManager = new SessionObjectManager(this);    DispatchServer server = webApp.getDispatchServer();    if (server != null) {      InvocationDecoder decoder = server.getInvocationDecoder();      _sessionSuffix = decoder.getSessionURLPrefix();      _sessionPrefix = decoder.getAlternateSessionURLPrefix();      _cookieName = decoder.getSessionCookie();      _sslCookieName = decoder.getSSLSessionCookie();    }    String hostName = webApp.getHostName();    String contextPath = webApp.getContextPath();        if (hostName == null || hostName.equals(""))      hostName = "default";    String name = hostName + contextPath;    if (_distributionId == null)      _distributionId = name;        _alarm = new Alarm(this);    _admin = new SessionManagerAdmin(this);  }  /**   * Returns the admin.   */  public SessionManagerMXBean getAdmin()  {    return _admin;  }  /**   * Returns the session prefix, ie.. ";jsessionid=".   */  public String getSessionPrefix()  {    return _sessionSuffix;  }  /**   * Returns the alternate session prefix, before the URL for wap.   */  public String getAlternateSessionPrefix()  {    return _sessionPrefix;  }  /**   * Returns the cookie version.   */  public int getCookieVersion()  {    return _cookieVersion;  }  /**   * Sets the cookie version.   */  public void setCookieVersion(int cookieVersion)  {    _cookieVersion = cookieVersion;  }  /**   * Sets the cookie ports.   */  public void setCookiePort(String port)  {    _cookiePort = port;  }  /**   * Gets the cookie ports.   */  public String getCookiePort()  {    return _cookiePort;  }  /**   * Returns the debug log   */  public Logger getDebug()  {    return log;  }  /**   * Returns the SessionManager's webApp   */  WebApp getWebApp()  {    return _webApp;  }  /**   * Returns the SessionManager's authenticator   */  ServletAuthenticator getAuthenticator()  {    return _webApp.getAuthenticator();  }    /**   * Returns the object manager   */  SessionObjectManager getObjectManager()  {    return _objectManager;  }  /**   * Sets the persistent store.   */  public void setPersistentStore(StoreManager store)    throws ConfigException  {    _storeManager = store;    if (_storeManager == null)      throw new ConfigException(L.l("unknown persistent store."));  }  /**   * True if sessions should always be loadd.   */  boolean getAlwaysLoadSession()  {    return _alwaysLoadSession == SET_TRUE;  }  /**   * True if sessions should always be loadd.   */  public void setAlwaysLoadSession(boolean load)  {    _alwaysLoadSession = load ? SET_TRUE : SET_FALSE;  }  /**   * True if sessions should always be saved.   */  boolean getAlwaysSaveSession()  {    return _alwaysSaveSession == SET_TRUE;  }  /**   * True if sessions should always be saved.   */  public void setAlwaysSaveSession(boolean save)  {    _alwaysSaveSession = save ? SET_TRUE : SET_FALSE;  }  /**   * True if sessions should be saved on shutdown.   */  public boolean isSaveOnShutdown()  {    return (_sessionSaveMode & SAVE_ON_SHUTDOWN) != 0;  }  /**   * True if sessions should only be saved on shutdown.   */  public boolean isSaveOnlyOnShutdown()  {    return (_sessionSaveMode & SAVE_ON_SHUTDOWN) == SAVE_ON_SHUTDOWN;  }  /**   * True if sessions should be saved before the HTTP headers.   */  public boolean isSaveBeforeHeaders()  {    return (_sessionSaveMode & SAVE_BEFORE_HEADERS) != 0;  }  /**   * True if sessions should be saved before each flush.   */  public boolean isSaveBeforeFlush()  {    return (_sessionSaveMode & SAVE_BEFORE_FLUSH) != 0;  }  /**   * True if sessions should be saved after the request.   */  public boolean isSaveAfterRequest()  {    return (_sessionSaveMode & SAVE_AFTER_REQUEST) != 0;  }    /**   * Determines how many digits are used to encode the server   */  boolean isTwoDigitSessionIndex()  {   return _isTwoDigitSessionIndex;  }  /**   * Sets the save-mode: before-flush, before-headers, after-request,   * on-shutdown   */  public void setSaveMode(String mode)    throws ConfigException  {    /* XXX: probably don't want to implement this.    if ("before-flush".equals(mode)) {      _sessionSaveMode = (SAVE_BEFORE_FLUSH|			  SAVE_BEFORE_HEADERS|			  SAVE_AFTER_REQUEST|			  SAVE_ON_SHUTDOWN);    }    else    */        if ("before-headers".equals(mode)) {      _sessionSaveMode = (SAVE_BEFORE_HEADERS|			  SAVE_AFTER_REQUEST|			  SAVE_ON_SHUTDOWN);    }    else if ("after-request".equals(mode)) {      _sessionSaveMode = (SAVE_AFTER_REQUEST|			  SAVE_ON_SHUTDOWN);    }    else if ("on-shutdown".equals(mode)) {      _sessionSaveMode = (SAVE_ON_SHUTDOWN);    }    else      throw new ConfigException(L.l("'{0}' is an unknown session save-mode.  Values are: before-headers, after-request, and on-shutdown.",				    mode));  }  /**   * Returns the string value of the save-mode.   */  public String getSaveMode()  {    if (isSaveBeforeFlush())      return "before-flush";    else if (isSaveBeforeHeaders())      return "before-headers";    else if (isSaveAfterRequest())      return "after-request";    else if (isSaveOnShutdown())      return "on-shutdown";    else      return "unknown";  }  /**   * True if sessions should only be saved on shutdown.   */  public void setSaveOnlyOnShutdown(boolean save)  {    log.warning("<save-only-on-shutdown> is deprecated.  Use <save-mode>on-shutdown</save-mode> instead");        if (save)      _sessionSaveMode = SAVE_ON_SHUTDOWN;  }  /**   * True if sessions should only be saved on shutdown.   */  public void setSaveOnShutdown(boolean save)  {    log.warning("<save-on-shutdown> is deprecated.  Use <save-only-on-shutdown> instead");    setSaveOnlyOnShutdown(save);  }  /**   * Sets the serialization type.   */  public void setSerializationType(String type)  {    if ("hessian".equals(type))      _isHessianSerialization = true;    else if ("java".equals(type))      _isHessianSerialization = false;    else      throw new ConfigException(L.l("'{0}' is an unknown valud for serialization-type.  The valid types are 'hessian' and 'java'.",				    type));  }  /**   * Returns true for Hessian serialization.   */  public boolean isHessianSerialization()  {    return _isHessianSerialization;  }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?