sessionimpl.java

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

JAVA
1,394
字号
/* * 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.hessian.io.*;import com.caucho.server.webapp.WebApp;import com.caucho.server.cluster.ClusterObject;import com.caucho.server.cluster.ObjectManager;import com.caucho.server.cluster.Store;import com.caucho.server.security.AbstractAuthenticator;import com.caucho.server.security.ServletAuthenticator;import com.caucho.util.Alarm;import com.caucho.util.CacheListener;import com.caucho.util.L10N;import com.caucho.vfs.IOExceptionWrapper;import javax.servlet.ServletContext;import javax.servlet.http.*;import java.io.*;import java.security.Principal;import java.util.*;import java.util.logging.Level;import java.util.logging.Logger;/** * Implements a HTTP session. */public class SessionImpl implements HttpSession, CacheListener {  static protected final Logger log    = Logger.getLogger(SessionImpl.class.getName());  static final L10N L = new L10N(SessionImpl.class);  static final String LOGIN = "caucho.login";  // the session's identifier  private String _id;  // the owning session manager  protected SessionManager _manager;  // the session objectStore  // Map containing the actual values.  protected Map<String,Object> _values;  // time the session was created  private long _creationTime;  // time the session was last accessed  long _accessTime;  // maximum time the session may stay alive.  long _maxInactiveInterval;  // true if the session is new  private boolean _isNew = true;  // true if the session is still valid, i.e. not invalidated  boolean _isValid = true;  // true if the session is closing  boolean _isClosing = false;  // true if the session is being closed from an invalidation  boolean _isInvalidating = false;  //To protect for threading  private int _useCount;  private ClusterObject _clusterObject;  // The logged-in user  private Principal _user;  /**   * Create a new session object.   *   * @param manager the owning session manager.   * @param id the session identifier.   * @param creationTime the time in milliseconds when the session was created.   */  public SessionImpl(SessionManager manager, String id, long creationTime)  {    _manager = manager;    _creationTime = creationTime;    _accessTime = creationTime;    _maxInactiveInterval = manager.getSessionTimeout();    _id = id;    // Finds the owning JVM from the session encoding    ObjectManager objectManager = manager.getObjectManager();    _clusterObject = objectManager.createClusterObject(id);     _values = createValueMap();    if (log.isLoggable(Level.FINE))      log.fine(this + " new");  }  /**   * Returns the time the session was created.   */  public long getCreationTime()  {    // this test forced by TCK    if (! _isValid)      throw new IllegalStateException(L.l("{0}: can't call getCreationTime() when session is no longer valid.",                                          this));    return _creationTime;  }  /**   * Returns the session identifier.   */  public String getId()  {    return _id;  }  /**   * Returns the index of the owning srun for distributed sessions.   */  int getSrunIndex()  {    if (_clusterObject != null)      return _clusterObject.getPrimaryIndex();    else      return 0;  }  /**   * Sets the cluster object.   */  void setClusterObject(ClusterObject clusterObject)  {    _clusterObject = clusterObject;    if (clusterObject != null)      clusterObject.objectInvalidated();  }  /**   * Returns the last objectAccess time.   */  public long getLastAccessedTime()  {    // this test forced by TCK    if (! _isValid)      throw new IllegalStateException(L.l("{0}: can't call getLastAccessedTime() when session is no longer valid.",                                          this));    return _accessTime;  }  /**   * Returns the time the session is allowed to be alive.   *   * @return time allowed to live in seconds   */  public int getMaxInactiveInterval()  {    if (Long.MAX_VALUE / 2 <= _maxInactiveInterval)      return -1;    else      return (int) (_maxInactiveInterval / 1000);  }  /**   * Sets the maximum time a session is allowed to be alive.   *   * @param value time allowed to live in seconds   */  public void setMaxInactiveInterval(int value)  {    if (value < 0)      _maxInactiveInterval = Long.MAX_VALUE / 2;    else      _maxInactiveInterval = ((long) value) * 1000;    if (_clusterObject != null)      _clusterObject.setExpireInterval(_maxInactiveInterval);  }  /**   * Returns the session context.   *   * @deprecated   */  public HttpSessionContext getSessionContext()  {    return null;  }  /**   * Returns the servlet context.   */  public ServletContext getServletContext()  {    return _manager.getWebApp();  }  /**   * Returns the session manager.   */  public SessionManager getManager()  {    return _manager;  }  /**   * Returns the authenticator   */  public ServletAuthenticator getAuthenticator()  {    return _manager.getWebApp().getAuthenticator();  }  /**   * Returns the user   */  public Principal getUser()  {    if (_user != null)      return _user;    if (_isValid) {      Object user = getAttribute(LOGIN);      if (user instanceof Principal)	_user = (Principal) user;      else if (user instanceof LoginPrincipal)	_user = ((LoginPrincipal) user).getUser();    }    return _user;  }  /**   * Sets the user   */  public void setUser(Principal user)  {    _user = user;    if (user == null)      removeAttribute(LOGIN);    else if (user instanceof java.io.Serializable)      setAttribute(LOGIN, user);    else      setAttribute(LOGIN, new LoginPrincipal(user));  }  /**   * Returns the named attribute from the session.   */  public Object getAttribute(String name)  {    if (! _isValid)      throw new IllegalStateException(L.l("{0}: can't call getAttribute() when session is no longer valid.",                                          this));    synchronized (_values) {      Object value = _values.get(name);      return value;    }  }  /**   * Sets a session attribute.  If the value is a listener, notify it   * of the objectModified.  If the value has changed mark the session as changed   * for persistent sessions.   *   * @param name the name of the attribute   * @param value the value of the attribute   */  public void setAttribute(String name, Object value)  {    if (! _isValid)      throw new IllegalStateException(L.l("{0}: can't call setAttribute(String, Object) when session is no longer valid.", this));    Object oldValue;    if (value != null	&& ! (value instanceof Serializable)	&& log.isLoggable(Level.FINE)) {      log.fine(L.l("{0} attribute '{1}' value is non-serializable type '{2}'",		   this, name, value.getClass().getName()));    }    synchronized (_values) {      if (value != null)        oldValue = _values.put(name, value);      else        oldValue = _values.remove(name);    }    // server/017p    if (_clusterObject != null) // && value != oldValue)      _clusterObject.objectModified();    if (oldValue instanceof HttpSessionBindingListener) {      HttpSessionBindingListener listener;      listener = (HttpSessionBindingListener) oldValue;      listener.valueUnbound(new HttpSessionBindingEvent(SessionImpl.this,							name, oldValue));    }    if (value instanceof HttpSessionBindingListener) {      HttpSessionBindingListener listener;      listener = (HttpSessionBindingListener) value;      listener.valueBound(new HttpSessionBindingEvent(SessionImpl.this,						      name, value));    }    // Notify the attribute listeners    ArrayList listeners = _manager.getAttributeListeners();        if (listeners != null && listeners.size() > 0) {      HttpSessionBindingEvent event;      if (oldValue != null)        event = new HttpSessionBindingEvent(this, name, oldValue);      else        event = new HttpSessionBindingEvent(this, name, value);      for (int i = 0; i < listeners.size(); i++) {        HttpSessionAttributeListener listener;        listener = (HttpSessionAttributeListener) listeners.get(i);        if (oldValue != null)          listener.attributeReplaced(event);        else          listener.attributeAdded(event);      }    }  }  /**   * Create the map used to objectStore values.   */  protected Map<String,Object> createValueMap()  {    return new Hashtable<String,Object>(8);  }  /**   * Remove a session attribute.  If the value is a listener, notify it   * of the objectModified.   *   * @param name the name of the attribute to objectRemove   */  public void removeAttribute(String name)  {    if (! _isValid)      throw new IllegalStateException(L.l("{0}: can't call removeAttribute(String) when session is no longer valid.", this));    Object oldValue;    synchronized (_values) {      oldValue = _values.remove(name);    }    if (_clusterObject != null && oldValue != null)      _clusterObject.objectModified();    notifyValueUnbound(name, oldValue);  }  /**   * Return an enumeration of all the sessions' attribute names.   *   * @return enumeration of the attribute names.   */  public Enumeration getAttributeNames()  {    synchronized (_values) {      if (! _isValid)	throw new IllegalStateException(L.l("{0} can't call getAttributeNames() when session is no longer valid.", this));      return Collections.enumeration(_values.keySet());    }  }  /**   * @deprecated   */  public Object getValue(String name)  {    return getAttribute(name);  }  /**   * @deprecated   */  public void putValue(String name, Object value)  {    setAttribute(name, value);  }  /**   * @deprecated   */  public void removeValue(String name)  {    removeAttribute(name);  }  /**   * @deprecated   */  public String []getValueNames()  {    synchronized (_values) {      if (! _isValid)	throw new IllegalStateException(L.l("{0} can't call getValueNames() when session is no longer valid.", this));      if (_values == null)	return new String[0];      String []s = new String[_values.size()];      Enumeration e = getAttributeNames();      int count = 0;      while (e.hasMoreElements())	s[count++] = (String) e.nextElement();      return s;    }  }  /**   * Returns true if the session is new.   */  public boolean isNew()  {    if (! _isValid)      throw new IllegalStateException(L.l("{0} can't call isNew() when session is no longer valid.", this));    return _isNew;  }  /**

⌨️ 快捷键说明

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