|
Tomcat example source code file (StandardSession.java)
The Tomcat StandardSession.java source code
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.catalina.session;
import java.beans.PropertyChangeSupport;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.apache.catalina.Context;
import org.apache.catalina.Globals;
import org.apache.catalina.Manager;
import org.apache.catalina.Session;
import org.apache.catalina.SessionEvent;
import org.apache.catalina.SessionListener;
import org.apache.catalina.util.Enumerator;
import org.apache.catalina.util.StringManager;
import org.apache.catalina.security.SecurityUtil;
/**
* Standard implementation of the <b>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.
* <p>
* <b>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 <code>org.apache.catalina.session package cannot cast an
* HttpSession view of this instance back to a Session view.
* <p>
* <b>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 <a href="mailto:jon@latchkey.com">Jon S. Stevens
* @version $Revision: 505593 $ $Date: 2007-02-10 01:54:56 +0100 (sam., 10 févr. 2007) $
*/
public class StandardSession
implements HttpSession, Session, Serializable {
protected static final boolean ACTIVITY_CHECK =
Globals.STRICT_SERVLET_COMPLIANCE
|| Boolean.valueOf(System.getProperty("org.apache.catalina.session.StandardSession.ACTIVITY_CHECK", "false")).booleanValue();
// ----------------------------------------------------------- Constructors
/**
* Construct a new Session associated with the specified Manager.
*
* @param manager The manager with which this Session is associated
*/
public StandardSession(Manager manager) {
super();
this.manager = manager;
// Initialize access count
if (ACTIVITY_CHECK) {
accessCount = new AtomicInteger();
}
}
// ----------------------------------------------------- Instance Variables
/**
* Type array.
*/
protected static final String EMPTY_ARRAY[] = new String[0];
/**
* The dummy attribute value serialized when a NotSerializableException is
* encountered in <code>writeObject().
*/
protected static final String NOT_SERIALIZED =
"___NOT_SERIALIZABLE_EXCEPTION___";
/**
* The collection of user data attributes associated with this Session.
*/
protected Map attributes = new ConcurrentHashMap();
/**
* 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 String authType = null;
/**
* The <code>java.lang.Method for the
* <code>fireContainerEvent() method of the
* <code>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 transient Method containerEventMethod = null;
/**
* The method signature for the <code>fireContainerEvent method.
*/
protected static final Class containerEventTypes[] =
{ String.class, Object.class };
/**
* The time this session was created, in milliseconds since midnight,
* January 1, 1970 GMT.
*/
protected long creationTime = 0L;
/**
* Set of attribute names which are not allowed to be persisted.
*/
protected static final String[] excludedAttributes = {
Globals.SUBJECT_ATTR
};
/**
* 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 boolean expiring = false;
/**
* The facade associated with this session. NOTE: This value is not
* included in the serialized version of this object.
*/
protected transient StandardSessionFacade facade = null;
/**
* The session identifier of this Session.
*/
protected String id = null;
/**
* Descriptive information describing this Session implementation.
*/
protected static final String info = "StandardSession/1.0";
/**
* The last accessed time for this Session.
*/
protected long lastAccessedTime = creationTime;
/**
* The session event listeners for this Session.
*/
protected transient ArrayList listeners = new ArrayList();
/**
* The Manager with which this Session is associated.
*/
protected transient Manager manager = null;
/**
* 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 int maxInactiveInterval = -1;
/**
* Flag indicating whether this session is new or not.
*/
protected boolean isNew = false;
/**
* Flag indicating whether this session is valid or not.
*/
protected boolean isValid = false;
/**
* Internal notes associated with this session by Catalina components
* and event listeners. <b>IMPLEMENTATION NOTE: This object is
* <em>not saved and restored across session serializations!
*/
protected transient Map notes = new Hashtable();
/**
* The authenticated Principal associated with this session, if any.
* <b>IMPLEMENTATION NOTE: This object is not saved and
* restored across session serializations!
*/
protected transient Principal principal = null;
/**
* The string manager for this package.
*/
protected static StringManager sm =
StringManager.getManager(Constants.Package);
/**
* The HTTP session context associated with this session.
*/
protected static HttpSessionContext sessionContext = null;
/**
* The property change support for this component. NOTE: This value
* is not included in the serialized version of this object.
*/
protected transient PropertyChangeSupport support =
new PropertyChangeSupport(this);
/**
* The current accessed time for this session.
*/
protected long thisAccessedTime = creationTime;
/**
* The access count for this session.
*/
protected transient AtomicInteger accessCount = null;
// ----------------------------------------------------- Session Properties
/**
* Return the authentication type used to authenticate our cached
* Principal, if any.
*/
public String getAuthType() {
return (this.authType);
}
/**
* Set the authentication type used to authenticate our cached
* Principal, if any.
*
* @param authType The new cached authentication type
*/
public void setAuthType(String authType) {
String oldAuthType = this.authType;
this.authType = authType;
support.firePropertyChange("authType", oldAuthType, this.authType);
}
/**
* 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
*/
public void setCreationTime(long time) {
this.creationTime = time;
this.lastAccessedTime = time;
this.thisAccessedTime = time;
}
/**
* Return the session identifier for this session.
*/
public String getId() {
return (this.id);
}
/**
* Return the session identifier for this session.
*/
public String getIdInternal() {
return (this.id);
}
/**
* Set the session identifier for this session.
*
* @param id The new session identifier
*/
public void setId(String id) {
if ((this.id != null) && (manager != null))
manager.remove(this);
this.id = id;
if (manager != null)
manager.add(this);
tellNew();
}
/**
* Inform the listeners about the new session.
*
*/
public void tellNew() {
// 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);
}
}
}
}
/**
* Return descriptive information about this Session implementation and
* the corresponding version number, in the format
* <code><description>/<version>.
*/
public String getInfo() {
return (info);
}
/**
* 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.
*/
public long getLastAccessedTime() {
if (!isValidInternal()) {
throw new IllegalStateException
(sm.getString("standardSession.getLastAccessedTime.ise"));
}
return (this.lastAccessedTime);
}
/**
* Return the last client access time without invalidation check
* @see #getLastAccessedTime().
*/
public long getLastAccessedTimeInternal() {
return (this.lastAccessedTime);
}
/**
* Return the Manager within which this Session is valid.
*/
public Manager getManager() {
return (this.manager);
}
/**
* Set the Manager within which this Session is valid.
*
* @param manager The new Manager
*/
public void setManager(Manager manager) {
this.manager = manager;
}
/**
* 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.
*/
public int getMaxInactiveInterval() {
return (this.maxInactiveInterval);
}
/**
* 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
*/
public void setMaxInactiveInterval(int interval) {
this.maxInactiveInterval = interval;
if (isValid && interval == 0) {
expire();
}
}
/**
* Set the <code>isNew flag for this session.
*
* @param isNew The new value for the <code>isNew flag
*/
public void setNew(boolean isNew) {
this.isNew = isNew;
}
/**
* Return the authenticated Principal that is associated with this Session.
* This provides an <code>Authenticator with a means to cache a
* previously authenticated Principal, and avoid potentially expensive
* <code>Realm.authenticate() calls on every request. If there
* is no current associated Principal, return <code>null.
*/
public Principal getPrincipal() {
return (this.principal);
}
/**
* Set the authenticated Principal that is associated with this Session.
* This provides an <code>Authenticator with a means to cache a
* previously authenticated Principal, and avoid potentially expensive
* <code>Realm.authenticate() calls on every request.
*
* @param principal The new Principal, or <code>null if none
*/
public void setPrincipal(Principal principal) {
Principal oldPrincipal = this.principal;
this.principal = principal;
support.firePropertyChange("principal", oldPrincipal, this.principal);
}
/**
* Return the <code>HttpSession for which this object
* is the facade.
*/
public HttpSession getSession() {
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);
}
/**
* Return the <code>isValid flag for this session.
*/
public boolean isValid() {
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);
}
/**
* Set the <code>isValid flag for this session.
*
* @param isValid The new value for the <code>isValid flag
*/
public void setValid(boolean isValid) {
this.isValid = isValid;
}
// ------------------------------------------------- Session Public Methods
/**
* 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.
*/
public void access() {
this.lastAccessedTime = this.thisAccessedTime;
this.thisAccessedTime = System.currentTimeMillis();
if (ACTIVITY_CHECK) {
accessCount.incrementAndGet();
}
}
/**
* End the access.
*/
public void endAccess() {
isNew = false;
if (ACTIVITY_CHECK) {
accessCount.decrementAndGet();
}
}
/**
* Add a session event listener to this component.
*/
public void addSessionListener(SessionListener listener) {
listeners.add(listener);
}
/**
* Perform the internal processing required to invalidate this session,
* without triggering an exception if the session has already expired.
*/
public void expire() {
expire(true);
}
/**
* 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?
*/
public void expire(boolean notify) {
// 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);
}
}
/**
* Perform the internal processing required to passivate
* this session.
*/
public void passivate() {
// 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);
}
}
}
}
/**
* Perform internal processing required to activate this
* session.
*/
public void activate() {
// 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);
}
}
}
}
/**
* Return the object bound with the specified name to the internal notes
* for this session, or <code>null if no such binding exists.
*
* @param name Name of the note to be returned
*/
public Object getNote(String name) {
return (notes.get(name));
}
/**
* Return an Iterator containing the String names of all notes bindings
* that exist for this session.
*/
public Iterator getNoteNames() {
return (notes.keySet().iterator());
}
/**
* Release all object references, and initialize instance variables, in
* preparation for reuse of this object.
*/
public void recycle() {
// 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;
}
/**
* Remove any object bound to the specified name in the internal notes
* for this session.
*
* @param name Name of the note to be removed
*/
public void removeNote(String name) {
notes.remove(name);
}
/**
* Remove a session event listener from this component.
*/
public void removeSessionListener(SessionListener listener) {
listeners.remove(listener);
}
/**
* 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
*/
public void setNote(String name, Object value) {
notes.put(name, value);
}
/**
* Return a string representation of this object.
*/
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("StandardSession[");
sb.append(id);
sb.append("]");
return (sb.toString());
}
// ------------------------------------------------ Session Package Methods
/**
* 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
*/
public void readObjectData(ObjectInputStream stream)
throws ClassNotFoundException, IOException {
readObject(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
*/
public void writeObjectData(ObjectOutputStream stream)
throws IOException {
writeObject(stream);
}
// ------------------------------------------------- HttpSession Properties
/**
* 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
*/
public long getCreationTime() {
if (!isValidInternal())
throw new IllegalStateException
(sm.getString("standardSession.getCreationTime.ise"));
return (this.creationTime);
}
/**
* Return the ServletContext to which this session belongs.
*/
public ServletContext getServletContext() {
if (manager == null)
return (null);
Context context = (Context) manager.getContainer();
if (context == null)
return (null);
else
return (context.getServletContext());
}
/**
* 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.
*/
public HttpSessionContext getSessionContext() {
if (sessionContext == null)
sessionContext = new StandardSessionContext();
return (sessionContext);
}
// ----------------------------------------------HttpSession Public Methods
/**
* Return the object bound with the specified name in this session, or
* <code>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
*/
public Object getAttribute(String name) {
if (!isValidInternal())
throw new IllegalStateException
(sm.getString("standardSession.getAttribute.ise"));
return (attributes.get(name));
}
/**
* Return an <code>Enumeration of
Other Tomcat examples (source code examples)Here is a short list of links related to this Tomcat StandardSession.java source code file: |
... this post is sponsored by my books ... | |
#1 New Release! |
FP Best Seller |
Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.