FileDocCategorySizeDatePackage
StandardSession.javaAPI DocApache Tomcat 6.0.1456653Fri Jul 20 04:20:32 BST 2007org.apache.catalina.session

StandardSession

public class StandardSession extends Object implements Serializable, HttpSession, org.apache.catalina.Session
Standard implementation of the Session interface. This object is serializable, so that it can be stored in persistent storage or transferred to a different JVM for distributable session support.

IMPLEMENTATION NOTE: An instance of this class represents both the internal (Session) and application level (HttpSession) view of the session. However, because the class itself is not declared public, Java logic outside of the org.apache.catalina.session package cannot cast an HttpSession view of this instance back to a Session view.

IMPLEMENTATION NOTE: If you add fields to this class, you must make sure that you carry them over in the read/writeObject methods so that this class is properly serialized.

author
Craig R. McClanahan
author
Sean Legassick
author
Jon S. Stevens
version
$Revision: 505593 $ $Date: 2007-02-10 01:54:56 +0100 (sam., 10 févr. 2007) $

Fields Summary
protected static final boolean
ACTIVITY_CHECK
protected static final String[]
EMPTY_ARRAY
Type array.
protected static final String
NOT_SERIALIZED
The dummy attribute value serialized when a NotSerializableException is encountered in writeObject().
protected Map
attributes
The collection of user data attributes associated with this Session.
protected transient String
authType
The authentication type used to authenticate our cached Principal, if any. NOTE: This value is not included in the serialized version of this object.
protected transient Method
containerEventMethod
The java.lang.Method for the fireContainerEvent() method of the org.apache.catalina.core.StandardContext method, if our Context implementation is of this class. This value is computed dynamically the first time it is needed, or after a session reload (since it is declared transient).
protected static final Class[]
containerEventTypes
The method signature for the fireContainerEvent method.
protected long
creationTime
The time this session was created, in milliseconds since midnight, January 1, 1970 GMT.
protected static final String[]
excludedAttributes
Set of attribute names which are not allowed to be persisted.
protected transient boolean
expiring
We are currently processing a session expiration, so bypass certain IllegalStateException tests. NOTE: This value is not included in the serialized version of this object.
protected transient StandardSessionFacade
facade
The facade associated with this session. NOTE: This value is not included in the serialized version of this object.
protected String
id
The session identifier of this Session.
protected static final String
info
Descriptive information describing this Session implementation.
protected long
lastAccessedTime
The last accessed time for this Session.
protected transient ArrayList
listeners
The session event listeners for this Session.
protected transient org.apache.catalina.Manager
manager
The Manager with which this Session is associated.
protected int
maxInactiveInterval
The maximum time interval, in seconds, between client requests before the servlet container may invalidate this session. A negative time indicates that the session should never time out.
protected boolean
isNew
Flag indicating whether this session is new or not.
protected boolean
isValid
Flag indicating whether this session is valid or not.
protected transient Map
notes
Internal notes associated with this session by Catalina components and event listeners. IMPLEMENTATION NOTE: This object is not saved and restored across session serializations!
protected transient Principal
principal
The authenticated Principal associated with this session, if any. IMPLEMENTATION NOTE: This object is not saved and restored across session serializations!
protected static org.apache.catalina.util.StringManager
sm
The string manager for this package.
protected static HttpSessionContext
sessionContext
The HTTP session context associated with this session.
protected transient PropertyChangeSupport
support
The property change support for this component. NOTE: This value is not included in the serialized version of this object.
protected long
thisAccessedTime
The current accessed time for this session.
protected transient AtomicInteger
accessCount
The access count for this session.
Constructors Summary
public StandardSession(org.apache.catalina.Manager manager)
Construct a new Session associated with the specified Manager.

param
manager The manager with which this Session is associated



    // ----------------------------------------------------------- Constructors


                            
       

        super();
        this.manager = manager;

        // Initialize access count
        if (ACTIVITY_CHECK) {
            accessCount = new AtomicInteger();
        }

    
Methods Summary
public voidaccess()
Update the accessed time information for this session. This method should be called by the context when a request comes in for a particular session, even if the application does not reference it.


        this.lastAccessedTime = this.thisAccessedTime;
        this.thisAccessedTime = System.currentTimeMillis();
        
        if (ACTIVITY_CHECK) {
            accessCount.incrementAndGet();
        }

    
public voidactivate()
Perform internal processing required to activate this session.


        // Initialize access count
        if (ACTIVITY_CHECK) {
            accessCount = new AtomicInteger();
        }
        
        // Notify interested session event listeners
        fireSessionEvent(Session.SESSION_ACTIVATED_EVENT, null);

        // Notify ActivationListeners
        HttpSessionEvent event = null;
        String keys[] = keys();
        for (int i = 0; i < keys.length; i++) {
            Object attribute = attributes.get(keys[i]);
            if (attribute instanceof HttpSessionActivationListener) {
                if (event == null)
                    event = new HttpSessionEvent(getSession());
                try {
                    ((HttpSessionActivationListener)attribute)
                        .sessionDidActivate(event);
                } catch (Throwable t) {
                    manager.getContainer().getLogger().error
                        (sm.getString("standardSession.attributeEvent"), t);
                }
            }
        }

    
public voidaddSessionListener(org.apache.catalina.SessionListener listener)
Add a session event listener to this component.


        listeners.add(listener);

    
public voidendAccess()
End the access.


        isNew = false;

        if (ACTIVITY_CHECK) {
            accessCount.decrementAndGet();
        }

    
protected booleanexclude(java.lang.String name)
Exclude attribute that cannot be serialized.

param
name the attribute's name


        for (int i = 0; i < excludedAttributes.length; i++) {
            if (name.equalsIgnoreCase(excludedAttributes[i]))
                return true;
        }

        return false;
    
public voidexpire()
Perform the internal processing required to invalidate this session, without triggering an exception if the session has already expired.


        expire(true);

    
public voidexpire(boolean notify)
Perform the internal processing required to invalidate this session, without triggering an exception if the session has already expired.

param
notify Should we notify listeners about the demise of this session?


        // Mark this session as "being expired" if needed
        if (expiring)
            return;

        synchronized (this) {

            if (manager == null)
                return;

            expiring = true;
        
            // Notify interested application event listeners
            // FIXME - Assumes we call listeners in reverse order
            Context context = (Context) manager.getContainer();
            Object listeners[] = context.getApplicationLifecycleListeners();
            if (notify && (listeners != null)) {
                HttpSessionEvent event =
                    new HttpSessionEvent(getSession());
                for (int i = 0; i < listeners.length; i++) {
                    int j = (listeners.length - 1) - i;
                    if (!(listeners[j] instanceof HttpSessionListener))
                        continue;
                    HttpSessionListener listener =
                        (HttpSessionListener) listeners[j];
                    try {
                        fireContainerEvent(context,
                                           "beforeSessionDestroyed",
                                           listener);
                        listener.sessionDestroyed(event);
                        fireContainerEvent(context,
                                           "afterSessionDestroyed",
                                           listener);
                    } catch (Throwable t) {
                        try {
                            fireContainerEvent(context,
                                               "afterSessionDestroyed",
                                               listener);
                        } catch (Exception e) {
                            ;
                        }
                        manager.getContainer().getLogger().error
                            (sm.getString("standardSession.sessionEvent"), t);
                    }
                }
            }
            if (ACTIVITY_CHECK) {
                accessCount.set(0);
            }
            setValid(false);

            /*
             * Compute how long this session has been alive, and update
             * session manager's related properties accordingly
             */
            long timeNow = System.currentTimeMillis();
            int timeAlive = (int) ((timeNow - creationTime)/1000);
            synchronized (manager) {
                if (timeAlive > manager.getSessionMaxAliveTime()) {
                    manager.setSessionMaxAliveTime(timeAlive);
                }
                int numExpired = manager.getExpiredSessions();
                numExpired++;
                manager.setExpiredSessions(numExpired);
                int average = manager.getSessionAverageAliveTime();
                average = ((average * (numExpired-1)) + timeAlive)/numExpired;
                manager.setSessionAverageAliveTime(average);
            }

            // Remove this session from our manager's active sessions
            manager.remove(this);

            // Notify interested session event listeners
            if (notify) {
                fireSessionEvent(Session.SESSION_DESTROYED_EVENT, null);
            }

            // We have completed expire of this session
            expiring = false;

            // Unbind any objects associated with this session
            String keys[] = keys();
            for (int i = 0; i < keys.length; i++)
                removeAttributeInternal(keys[i], notify);

        }

    
protected voidfireContainerEvent(org.apache.catalina.Context context, java.lang.String type, java.lang.Object data)
Fire container events if the Context implementation is the org.apache.catalina.core.StandardContext.

param
context Context for which to fire events
param
type Event type
param
data Event data
exception
Exception occurred during event firing


        if (!"org.apache.catalina.core.StandardContext".equals
            (context.getClass().getName())) {
            return; // Container events are not supported
        }
        // NOTE:  Race condition is harmless, so do not synchronize
        if (containerEventMethod == null) {
            containerEventMethod =
                context.getClass().getMethod("fireContainerEvent",
                                             containerEventTypes);
        }
        Object containerEventParams[] = new Object[2];
        containerEventParams[0] = type;
        containerEventParams[1] = data;
        containerEventMethod.invoke(context, containerEventParams);

    
public voidfireSessionEvent(java.lang.String type, java.lang.Object data)
Notify all session event listeners that a particular event has occurred for this Session. The default implementation performs this notification synchronously using the calling thread.

param
type Event type
param
data Event data

        if (listeners.size() < 1)
            return;
        SessionEvent event = new SessionEvent(this, type, data);
        SessionListener list[] = new SessionListener[0];
        synchronized (listeners) {
            list = (SessionListener[]) listeners.toArray(list);
        }

        for (int i = 0; i < list.length; i++){
            ((SessionListener) list[i]).sessionEvent(event);
        }

    
public java.lang.ObjectgetAttribute(java.lang.String name)
Return the object bound with the specified name in this session, or null if no object is bound with that name.

param
name Name of the attribute to be returned
exception
IllegalStateException if this method is called on an invalidated session


        if (!isValidInternal())
            throw new IllegalStateException
                (sm.getString("standardSession.getAttribute.ise"));

        return (attributes.get(name));

    
public java.util.EnumerationgetAttributeNames()
Return an Enumeration of String objects containing the names of the objects bound to this session.

exception
IllegalStateException if this method is called on an invalidated session


        if (!isValidInternal())
            throw new IllegalStateException
                (sm.getString("standardSession.getAttributeNames.ise"));

        return (new Enumerator(attributes.keySet(), true));

    
public java.lang.StringgetAuthType()
Return the authentication type used to authenticate our cached Principal, if any.


    
    // ----------------------------------------------------- Session Properties


                     
       

        return (this.authType);

    
public longgetCreationTime()
Return the time when this session was created, in milliseconds since midnight, January 1, 1970 GMT.

exception
IllegalStateException if this method is called on an invalidated session


        if (!isValidInternal())
            throw new IllegalStateException
                (sm.getString("standardSession.getCreationTime.ise"));

        return (this.creationTime);

    
public java.lang.StringgetId()
Return the session identifier for this session.


        return (this.id);

    
public java.lang.StringgetIdInternal()
Return the session identifier for this session.


        return (this.id);

    
public java.lang.StringgetInfo()
Return descriptive information about this Session implementation and the corresponding version number, in the format <description>/<version>.


        return (info);

    
public longgetLastAccessedTime()
Return the last time the client sent a request associated with this session, as the number of milliseconds since midnight, January 1, 1970 GMT. Actions that your application takes, such as getting or setting a value associated with the session, do not affect the access time.


        if (!isValidInternal()) {
            throw new IllegalStateException
                (sm.getString("standardSession.getLastAccessedTime.ise"));
        }

        return (this.lastAccessedTime);
    
public longgetLastAccessedTimeInternal()
Return the last client access time without invalidation check

see
#getLastAccessedTime().

        return (this.lastAccessedTime);
    
public org.apache.catalina.ManagergetManager()
Return the Manager within which this Session is valid.


        return (this.manager);

    
public intgetMaxInactiveInterval()
Return the maximum time interval, in seconds, between client requests before the servlet container will invalidate the session. A negative time indicates that the session should never time out.


        return (this.maxInactiveInterval);

    
public java.lang.ObjectgetNote(java.lang.String name)
Return the object bound with the specified name to the internal notes for this session, or null if no such binding exists.

param
name Name of the note to be returned


        return (notes.get(name));

    
public java.util.IteratorgetNoteNames()
Return an Iterator containing the String names of all notes bindings that exist for this session.


        return (notes.keySet().iterator());

    
public java.security.PrincipalgetPrincipal()
Return the authenticated Principal that is associated with this Session. This provides an Authenticator with a means to cache a previously authenticated Principal, and avoid potentially expensive Realm.authenticate() calls on every request. If there is no current associated Principal, return null.


        return (this.principal);

    
public javax.servlet.ServletContextgetServletContext()
Return the ServletContext to which this session belongs.


        if (manager == null)
            return (null);
        Context context = (Context) manager.getContainer();
        if (context == null)
            return (null);
        else
            return (context.getServletContext());

    
public javax.servlet.http.HttpSessiongetSession()
Return the HttpSession for which this object is the facade.


        if (facade == null){
            if (SecurityUtil.isPackageProtectionEnabled()){
                final StandardSession fsession = this;
                facade = (StandardSessionFacade)AccessController.doPrivileged(new PrivilegedAction(){
                    public Object run(){
                        return new StandardSessionFacade(fsession);
                    }
                });
            } else {
                facade = new StandardSessionFacade(this);
            }
        }
        return (facade);

    
public javax.servlet.http.HttpSessionContextgetSessionContext()
Return the session context with which this session is associated.

deprecated
As of Version 2.1, this method is deprecated and has no replacement. It will be removed in a future version of the Java Servlet API.


        if (sessionContext == null)
            sessionContext = new StandardSessionContext();
        return (sessionContext);

    
public java.lang.ObjectgetValue(java.lang.String name)
Return the object bound with the specified name in this session, or null if no object is bound with that name.

param
name Name of the value to be returned
exception
IllegalStateException if this method is called on an invalidated session
deprecated
As of Version 2.2, this method is replaced by getAttribute()


        return (getAttribute(name));

    
public java.lang.String[]getValueNames()
Return the set of names of objects bound to this session. If there are no such objects, a zero-length array is returned.

exception
IllegalStateException if this method is called on an invalidated session
deprecated
As of Version 2.2, this method is replaced by getAttributeNames()


        if (!isValidInternal())
            throw new IllegalStateException
                (sm.getString("standardSession.getValueNames.ise"));

        return (keys());

    
public voidinvalidate()
Invalidates this session and unbinds any objects bound to it.

exception
IllegalStateException if this method is called on an invalidated session


        if (!isValidInternal())
            throw new IllegalStateException
                (sm.getString("standardSession.invalidate.ise"));

        // Cause this session to expire
        expire();

    
public booleanisNew()
Return true if the client does not yet know about the session, or if the client chooses not to join the session. For example, if the server used only cookie-based sessions, and the client has disabled the use of cookies, then a session would be new on each request.

exception
IllegalStateException if this method is called on an invalidated session


        if (!isValidInternal())
            throw new IllegalStateException
                (sm.getString("standardSession.isNew.ise"));

        return (this.isNew);

    
public booleanisValid()
Return the isValid flag for this session.


        if (this.expiring) {
            return true;
        }

        if (!this.isValid) {
            return false;
        }

        if (ACTIVITY_CHECK && accessCount.get() > 0) {
            return true;
        }

        if (maxInactiveInterval >= 0) { 
            long timeNow = System.currentTimeMillis();
            int timeIdle = (int) ((timeNow - thisAccessedTime) / 1000L);
            if (timeIdle >= maxInactiveInterval) {
                expire(true);
            }
        }

        return (this.isValid);
    
protected booleanisValidInternal()
Return the isValid flag for this session without any expiration check.

        return (this.isValid || this.expiring);
    
protected java.lang.String[]keys()
Return the names of all currently defined session attributes as an array of Strings. If there are no defined attributes, a zero-length array is returned.


        return ((String[]) attributes.keySet().toArray(EMPTY_ARRAY));

    
public voidpassivate()
Perform the internal processing required to passivate this session.


        // Notify interested session event listeners
        fireSessionEvent(Session.SESSION_PASSIVATED_EVENT, null);

        // Notify ActivationListeners
        HttpSessionEvent event = null;
        String keys[] = keys();
        for (int i = 0; i < keys.length; i++) {
            Object attribute = attributes.get(keys[i]);
            if (attribute instanceof HttpSessionActivationListener) {
                if (event == null)
                    event = new HttpSessionEvent(getSession());
                try {
                    ((HttpSessionActivationListener)attribute)
                        .sessionWillPassivate(event);
                } catch (Throwable t) {
                    manager.getContainer().getLogger().error
                        (sm.getString("standardSession.attributeEvent"), t);
                }
            }
        }

    
public voidputValue(java.lang.String name, java.lang.Object value)
Bind an object to this session, using the specified name. If an object of the same name is already bound to this session, the object is replaced.

After this method executes, and if the object implements HttpSessionBindingListener, the container calls valueBound() on the object.

param
name Name to which the object is bound, cannot be null
param
value Object to be bound, cannot be null
exception
IllegalStateException if this method is called on an invalidated session
deprecated
As of Version 2.2, this method is replaced by setAttribute()


        setAttribute(name, value);

    
protected voidreadObject(java.io.ObjectInputStream stream)
Read a serialized version of this session object from the specified object input stream.

IMPLEMENTATION NOTE: The reference to the owning Manager is not restored by this method, and must be set explicitly.

param
stream The input stream to read from
exception
ClassNotFoundException if an unknown class is specified
exception
IOException if an input/output error occurs


        // Deserialize the scalar instance variables (except Manager)
        authType = null;        // Transient only
        creationTime = ((Long) stream.readObject()).longValue();
        lastAccessedTime = ((Long) stream.readObject()).longValue();
        maxInactiveInterval = ((Integer) stream.readObject()).intValue();
        isNew = ((Boolean) stream.readObject()).booleanValue();
        isValid = ((Boolean) stream.readObject()).booleanValue();
        thisAccessedTime = ((Long) stream.readObject()).longValue();
        principal = null;        // Transient only
        //        setId((String) stream.readObject());
        id = (String) stream.readObject();
        if (manager.getContainer().getLogger().isDebugEnabled())
            manager.getContainer().getLogger().debug
                ("readObject() loading session " + id);

        // Deserialize the attribute count and attribute values
        if (attributes == null)
            attributes = new Hashtable();
        int n = ((Integer) stream.readObject()).intValue();
        boolean isValidSave = isValid;
        isValid = true;
        for (int i = 0; i < n; i++) {
            String name = (String) stream.readObject();
            Object value = (Object) stream.readObject();
            if ((value instanceof String) && (value.equals(NOT_SERIALIZED)))
                continue;
            if (manager.getContainer().getLogger().isDebugEnabled())
                manager.getContainer().getLogger().debug("  loading attribute '" + name +
                    "' with value '" + value + "'");
            attributes.put(name, value);
        }
        isValid = isValidSave;

        if (listeners == null) {
            listeners = new ArrayList();
        }

        if (notes == null) {
            notes = new Hashtable();
        }
    
public voidreadObjectData(java.io.ObjectInputStream stream)
Read a serialized version of the contents of this session object from the specified object input stream, without requiring that the StandardSession itself have been serialized.

param
stream The object input stream to read from
exception
ClassNotFoundException if an unknown class is specified
exception
IOException if an input/output error occurs


        readObject(stream);

    
public voidrecycle()
Release all object references, and initialize instance variables, in preparation for reuse of this object.


        // Reset the instance variables associated with this Session
        attributes.clear();
        setAuthType(null);
        creationTime = 0L;
        expiring = false;
        id = null;
        lastAccessedTime = 0L;
        maxInactiveInterval = -1;
        notes.clear();
        setPrincipal(null);
        isNew = false;
        isValid = false;
        manager = null;

    
public voidremoveAttribute(java.lang.String name)
Remove the object bound with the specified name from this session. If the session does not have an object bound with this name, this method does nothing.

After this method executes, and if the object implements HttpSessionBindingListener, the container calls valueUnbound() on the object.

param
name Name of the object to remove from this session.
exception
IllegalStateException if this method is called on an invalidated session


        removeAttribute(name, true);

    
public voidremoveAttribute(java.lang.String name, boolean notify)
Remove the object bound with the specified name from this session. If the session does not have an object bound with this name, this method does nothing.

After this method executes, and if the object implements HttpSessionBindingListener, the container calls valueUnbound() on the object.

param
name Name of the object to remove from this session.
param
notify Should we notify interested listeners that this attribute is being removed?
exception
IllegalStateException if this method is called on an invalidated session


        // Validate our current state
        if (!isValidInternal())
            throw new IllegalStateException
                (sm.getString("standardSession.removeAttribute.ise"));

        removeAttributeInternal(name, notify);

    
protected voidremoveAttributeInternal(java.lang.String name, boolean notify)
Remove the object bound with the specified name from this session. If the session does not have an object bound with this name, this method does nothing.

After this method executes, and if the object implements HttpSessionBindingListener, the container calls valueUnbound() on the object.

param
name Name of the object to remove from this session.
param
notify Should we notify interested listeners that this attribute is being removed?


        // Remove this attribute from our collection
        Object value = attributes.remove(name);

        // Do we need to do valueUnbound() and attributeRemoved() notification?
        if (!notify || (value == null)) {
            return;
        }

        // Call the valueUnbound() method if necessary
        HttpSessionBindingEvent event = null;
        if (value instanceof HttpSessionBindingListener) {
            event = new HttpSessionBindingEvent(getSession(), name, value);
            ((HttpSessionBindingListener) value).valueUnbound(event);
        }

        // Notify interested application event listeners
        Context context = (Context) manager.getContainer();
        Object listeners[] = context.getApplicationEventListeners();
        if (listeners == null)
            return;
        for (int i = 0; i < listeners.length; i++) {
            if (!(listeners[i] instanceof HttpSessionAttributeListener))
                continue;
            HttpSessionAttributeListener listener =
                (HttpSessionAttributeListener) listeners[i];
            try {
                fireContainerEvent(context,
                                   "beforeSessionAttributeRemoved",
                                   listener);
                if (event == null) {
                    event = new HttpSessionBindingEvent
                        (getSession(), name, value);
                }
                listener.attributeRemoved(event);
                fireContainerEvent(context,
                                   "afterSessionAttributeRemoved",
                                   listener);
            } catch (Throwable t) {
                try {
                    fireContainerEvent(context,
                                       "afterSessionAttributeRemoved",
                                       listener);
                } catch (Exception e) {
                    ;
                }
                manager.getContainer().getLogger().error
                    (sm.getString("standardSession.attributeEvent"), t);
            }
        }

    
public voidremoveNote(java.lang.String name)
Remove any object bound to the specified name in the internal notes for this session.

param
name Name of the note to be removed


        notes.remove(name);

    
public voidremoveSessionListener(org.apache.catalina.SessionListener listener)
Remove a session event listener from this component.


        listeners.remove(listener);

    
public voidremoveValue(java.lang.String name)
Remove the object bound with the specified name from this session. If the session does not have an object bound with this name, this method does nothing.

After this method executes, and if the object implements HttpSessionBindingListener, the container calls valueUnbound() on the object.

param
name Name of the object to remove from this session.
exception
IllegalStateException if this method is called on an invalidated session
deprecated
As of Version 2.2, this method is replaced by removeAttribute()


        removeAttribute(name);

    
public voidsetAttribute(java.lang.String name, java.lang.Object value)
Bind an object to this session, using the specified name. If an object of the same name is already bound to this session, the object is replaced.

After this method executes, and if the object implements HttpSessionBindingListener, the container calls valueBound() on the object.

param
name Name to which the object is bound, cannot be null
param
value Object to be bound, cannot be null
exception
IllegalArgumentException if an attempt is made to add a non-serializable object in an environment marked distributable.
exception
IllegalStateException if this method is called on an invalidated session

        setAttribute(name,value,true);
    
public voidsetAttribute(java.lang.String name, java.lang.Object value, boolean notify)
Bind an object to this session, using the specified name. If an object of the same name is already bound to this session, the object is replaced.

After this method executes, and if the object implements HttpSessionBindingListener, the container calls valueBound() on the object.

param
name Name to which the object is bound, cannot be null
param
value Object to be bound, cannot be null
param
notify whether to notify session listeners
exception
IllegalArgumentException if an attempt is made to add a non-serializable object in an environment marked distributable.
exception
IllegalStateException if this method is called on an invalidated session


        // Name cannot be null
        if (name == null)
            throw new IllegalArgumentException
                (sm.getString("standardSession.setAttribute.namenull"));

        // Null value is the same as removeAttribute()
        if (value == null) {
            removeAttribute(name);
            return;
        }

        // Validate our current state
        if (!isValidInternal())
            throw new IllegalStateException
                (sm.getString("standardSession.setAttribute.ise"));
        if ((manager != null) && manager.getDistributable() &&
          !(value instanceof Serializable))
            throw new IllegalArgumentException
                (sm.getString("standardSession.setAttribute.iae"));

        // Construct an event with the new value
        HttpSessionBindingEvent event = null;

        // Call the valueBound() method if necessary
        if (notify && value instanceof HttpSessionBindingListener) {
            // Don't call any notification if replacing with the same value
            Object oldValue = attributes.get(name);
            if (value != oldValue) {
                event = new HttpSessionBindingEvent(getSession(), name, value);
                try {
                    ((HttpSessionBindingListener) value).valueBound(event);
                } catch (Throwable t){
                    manager.getContainer().getLogger().error
                    (sm.getString("standardSession.bindingEvent"), t); 
                }
            }
        }

        // Replace or add this attribute
        Object unbound = attributes.put(name, value);

        // Call the valueUnbound() method if necessary
        if (notify && (unbound != null) && (unbound != value) &&
            (unbound instanceof HttpSessionBindingListener)) {
            try {
                ((HttpSessionBindingListener) unbound).valueUnbound
                    (new HttpSessionBindingEvent(getSession(), name));
            } catch (Throwable t) {
                manager.getContainer().getLogger().error
                    (sm.getString("standardSession.bindingEvent"), t);
            }
        }
        
        if ( !notify ) return;
        
        // Notify interested application event listeners
        Context context = (Context) manager.getContainer();
        Object listeners[] = context.getApplicationEventListeners();
        if (listeners == null)
            return;
        for (int i = 0; i < listeners.length; i++) {
            if (!(listeners[i] instanceof HttpSessionAttributeListener))
                continue;
            HttpSessionAttributeListener listener =
                (HttpSessionAttributeListener) listeners[i];
            try {
                if (unbound != null) {
                    fireContainerEvent(context,
                                       "beforeSessionAttributeReplaced",
                                       listener);
                    if (event == null) {
                        event = new HttpSessionBindingEvent
                            (getSession(), name, unbound);
                    }
                    listener.attributeReplaced(event);
                    fireContainerEvent(context,
                                       "afterSessionAttributeReplaced",
                                       listener);
                } else {
                    fireContainerEvent(context,
                                       "beforeSessionAttributeAdded",
                                       listener);
                    if (event == null) {
                        event = new HttpSessionBindingEvent
                            (getSession(), name, value);
                    }
                    listener.attributeAdded(event);
                    fireContainerEvent(context,
                                       "afterSessionAttributeAdded",
                                       listener);
                }
            } catch (Throwable t) {
                try {
                    if (unbound != null) {
                        fireContainerEvent(context,
                                           "afterSessionAttributeReplaced",
                                           listener);
                    } else {
                        fireContainerEvent(context,
                                           "afterSessionAttributeAdded",
                                           listener);
                    }
                } catch (Exception e) {
                    ;
                }
                manager.getContainer().getLogger().error
                    (sm.getString("standardSession.attributeEvent"), t);
            }
        }

    
public voidsetAuthType(java.lang.String authType)
Set the authentication type used to authenticate our cached Principal, if any.

param
authType The new cached authentication type


        String oldAuthType = this.authType;
        this.authType = authType;
        support.firePropertyChange("authType", oldAuthType, this.authType);

    
public voidsetCreationTime(long time)
Set the creation time for this session. This method is called by the Manager when an existing Session instance is reused.

param
time The new creation time


        this.creationTime = time;
        this.lastAccessedTime = time;
        this.thisAccessedTime = time;

    
public voidsetId(java.lang.String id)
Set the session identifier for this session.

param
id The new session identifier


        if ((this.id != null) && (manager != null))
            manager.remove(this);

        this.id = id;

        if (manager != null)
            manager.add(this);
        tellNew();
    
public voidsetManager(org.apache.catalina.Manager manager)
Set the Manager within which this Session is valid.

param
manager The new Manager


        this.manager = manager;

    
public voidsetMaxInactiveInterval(int interval)
Set the maximum time interval, in seconds, between client requests before the servlet container will invalidate the session. A negative time indicates that the session should never time out.

param
interval The new maximum interval


        this.maxInactiveInterval = interval;
        if (isValid && interval == 0) {
            expire();
        }

    
public voidsetNew(boolean isNew)
Set the isNew flag for this session.

param
isNew The new value for the isNew flag


        this.isNew = isNew;

    
public voidsetNote(java.lang.String name, java.lang.Object value)
Bind an object to a specified name in the internal notes associated with this session, replacing any existing binding for this name.

param
name Name to which the object should be bound
param
value Object to be bound to the specified name


        notes.put(name, value);

    
public voidsetPrincipal(java.security.Principal principal)
Set the authenticated Principal that is associated with this Session. This provides an Authenticator with a means to cache a previously authenticated Principal, and avoid potentially expensive Realm.authenticate() calls on every request.

param
principal The new Principal, or null if none


        Principal oldPrincipal = this.principal;
        this.principal = principal;
        support.firePropertyChange("principal", oldPrincipal, this.principal);

    
public voidsetValid(boolean isValid)
Set the isValid flag for this session.

param
isValid The new value for the isValid flag

        this.isValid = isValid;
    
public voidtellNew()
Inform the listeners about the new session.


        // Notify interested session event listeners
        fireSessionEvent(Session.SESSION_CREATED_EVENT, null);

        // Notify interested application event listeners
        Context context = (Context) manager.getContainer();
        Object listeners[] = context.getApplicationLifecycleListeners();
        if (listeners != null) {
            HttpSessionEvent event =
                new HttpSessionEvent(getSession());
            for (int i = 0; i < listeners.length; i++) {
                if (!(listeners[i] instanceof HttpSessionListener))
                    continue;
                HttpSessionListener listener =
                    (HttpSessionListener) listeners[i];
                try {
                    fireContainerEvent(context,
                                       "beforeSessionCreated",
                                       listener);
                    listener.sessionCreated(event);
                    fireContainerEvent(context,
                                       "afterSessionCreated",
                                       listener);
                } catch (Throwable t) {
                    try {
                        fireContainerEvent(context,
                                           "afterSessionCreated",
                                           listener);
                    } catch (Exception e) {
                        ;
                    }
                    manager.getContainer().getLogger().error
                        (sm.getString("standardSession.sessionEvent"), t);
                }
            }
        }

    
public java.lang.StringtoString()
Return a string representation of this object.


        StringBuffer sb = new StringBuffer();
        sb.append("StandardSession[");
        sb.append(id);
        sb.append("]");
        return (sb.toString());

    
protected voidwriteObject(java.io.ObjectOutputStream stream)
Write a serialized version of this session object to the specified object output stream.

IMPLEMENTATION NOTE: The owning Manager will not be stored in the serialized representation of this Session. After calling readObject(), you must set the associated Manager explicitly.

IMPLEMENTATION NOTE: Any attribute that is not Serializable will be unbound from the session, with appropriate actions if it implements HttpSessionBindingListener. If you do not want any such attributes, be sure the distributable property of the associated Manager is set to true.

param
stream The output stream to write to
exception
IOException if an input/output error occurs


        // Write the scalar instance variables (except Manager)
        stream.writeObject(new Long(creationTime));
        stream.writeObject(new Long(lastAccessedTime));
        stream.writeObject(new Integer(maxInactiveInterval));
        stream.writeObject(new Boolean(isNew));
        stream.writeObject(new Boolean(isValid));
        stream.writeObject(new Long(thisAccessedTime));
        stream.writeObject(id);
        if (manager.getContainer().getLogger().isDebugEnabled())
            manager.getContainer().getLogger().debug
                ("writeObject() storing session " + id);

        // Accumulate the names of serializable and non-serializable attributes
        String keys[] = keys();
        ArrayList saveNames = new ArrayList();
        ArrayList saveValues = new ArrayList();
        for (int i = 0; i < keys.length; i++) {
            Object value = attributes.get(keys[i]);
            if (value == null)
                continue;
            else if ( (value instanceof Serializable) 
                    && (!exclude(keys[i]) )) {
                saveNames.add(keys[i]);
                saveValues.add(value);
            } else {
                removeAttributeInternal(keys[i], true);
            }
        }

        // Serialize the attribute count and the Serializable attributes
        int n = saveNames.size();
        stream.writeObject(new Integer(n));
        for (int i = 0; i < n; i++) {
            stream.writeObject((String) saveNames.get(i));
            try {
                stream.writeObject(saveValues.get(i));
                if (manager.getContainer().getLogger().isDebugEnabled())
                    manager.getContainer().getLogger().debug
                        ("  storing attribute '" + saveNames.get(i) +
                        "' with value '" + saveValues.get(i) + "'");
            } catch (NotSerializableException e) {
                manager.getContainer().getLogger().warn
                    (sm.getString("standardSession.notSerializable",
                     saveNames.get(i), id), e);
                stream.writeObject(NOT_SERIALIZED);
                if (manager.getContainer().getLogger().isDebugEnabled())
                    manager.getContainer().getLogger().debug
                       ("  storing attribute '" + saveNames.get(i) +
                        "' with value NOT_SERIALIZED");
            }
        }

    
public voidwriteObjectData(java.io.ObjectOutputStream stream)
Write a serialized version of the contents of this session object to the specified object output stream, without requiring that the StandardSession itself have been serialized.

param
stream The object output stream to write to
exception
IOException if an input/output error occurs


        writeObject(stream);