Package org.apache.tomcat.session

Source Code of org.apache.tomcat.session.StandardManager

/*
* $Header: /home/cvs/jakarta-tomcat/proposals/catalina/src/share/org/apache/tomcat/session/StandardManager.java,v 1.4 2000/01/31 05:29:04 craigmcc Exp $
* $Revision: 1.4 $
* $Date: 2000/01/31 05:29:04 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation.  All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in
*    the documentation and/or other materials provided with the
*    distribution.
*
* 3. The end-user documentation included with the redistribution, if
*    any, must include the following acknowlegement: 
*       "This product includes software developed by the
*        Apache Software Foundation (http://www.apache.org/)."
*    Alternately, this acknowlegement may appear in the software itself,
*    if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
*    Foundation" must not be used to endorse or promote products derived
*    from this software without prior written permission. For written
*    permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
*    nor may "Apache" appear in their names without prior written
*    permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation.  For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/


package org.apache.tomcat.session;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import org.apache.tomcat.Lifecycle;
import org.apache.tomcat.LifecycleException;
import org.apache.tomcat.Manager;
import org.apache.tomcat.Request;
import org.apache.tomcat.Session;
import org.apache.tomcat.util.StringManager;


/**
* Standard implementation of the <b>Manager</b> interface that provides
* simple session persistence across restarts of this component (such as
* when the entire server is shut down and restarted, or when a particular
* web application is reloaded.
* <p>
* <b>IMPLEMENTATION NOTE</b>:  Correct behavior of session storing and
* reloading depends upon external calls to the <code>start()</code> and
* <code>stop()</code> methods of this class at the correct times.
*
* @author Craig R. McClanahan
* @version $Revision: 1.4 $ $Date: 2000/01/31 05:29:04 $
*/

public final class StandardManager
    extends ManagerBase
    implements Lifecycle, Runnable {


    // ----------------------------------------------------- Instance Variables


    /**
     * The interval (in seconds) between checks for expired sessions.
     */
    private int checkInterval = 60;


    /**
     * The descriptive information about this implementation.
     */
    private static final String info = "StandardManager/1.0";


    /**
     * The maximum number of active Sessions allowed, or -1 for no limit.
     */
    private int maxActiveSessions = -1;


    /**
     * Path name of the disk file in which active sessions are saved
     * when we stop, and from which these sessions are loaded when we start.
     * A <code>null</code> value indicates that no persistence is desired.
     */
    private String pathname = null;


    /**
     * The string manager for this package.
     */
    private StringManager sm =
        StringManager.getManager(Constants.Package);


    /**
     * Has this component been started yet?
     */
    private boolean started = false;


    /**
     * The background thread.
     */
    private Thread thread = null;


    /**
     * The background thread completion semaphore.
     */
    private boolean threadDone = false;


    /**
     * Name to register for the background thread.
     */
    private String threadName = "StandardManager";


    // ------------------------------------------------------------- Properties


    /**
     * Return the check interval (in seconds) for this Manager.
     */
    public int getCheckInterval() {

  return (this.checkInterval);

    }


    /**
     * Set the check interval (in seconds) for this Manager.
     *
     * @param checkInterval The new check interval
     */
    public void setCheckInterval(int checkInterval) {

  int oldCheckInterval = this.checkInterval;
  this.checkInterval = checkInterval;
  support.firePropertyChange("checkInterval",
           new Integer(oldCheckInterval),
           new Integer(this.checkInterval));

    }


    /**
     * Return descriptive information about this Manager implementation and
     * the corresponding version number, in the format
     * <code>&lt;description&gt;/&lt;version&gt;</code>.
     */
    public String getInfo() {

  return (this.info);

    }


    /**
     * Return the maximum number of active Sessions allowed, or -1 for
     * no limit.
     */
    public int getMaxActiveSessions() {

  return (this.maxActiveSessions);

    }


    /**
     * Set the maximum number of actives Sessions allowed, or -1 for
     * no limit.
     *
     * @param max The new maximum number of sessions
     */
    public void setMaxActiveSessions(int max) {

  int oldMaxActiveSessions = this.maxActiveSessions;
  this.maxActiveSessions = max;
  support.firePropertyChange("maxActiveSessions",
           new Integer(oldMaxActiveSessions),
           new Integer(this.maxActiveSessions));

    }


    /**
     * Return the session persistence pathname, if any.
     */
    public String getPathname() {

  return (this.pathname);

    }


    /**
     * Set the session persistence pathname to the specified value.  If no
     * persistence support is desired, set the pathname to <code>null</code>.
     *
     * @param pathname New session persistence pathname
     */
    public void setPathname(String pathname) {

  String oldPathname = this.pathname;
  this.pathname = pathname;
  support.firePropertyChange("pathname", oldPathname, this.pathname);

    }


    // --------------------------------------------------------- Public Methods


    /**
     * Construct and return a new session object, based on the default
     * settings specified by this Manager's properties.  The session
     * id will be assigned by this method, and available via the getId()
     * method of the returned session.  If a new session cannot be created
     * for any reason, return <code>null</code>.
     *
     * @exception IllegalStateException if a new session cannot be
     *  instantiated for any reason
     */
    public Session createSession() {

  if ((maxActiveSessions >= 0) &&
    (sessions.size() >= maxActiveSessions))
      throw new IllegalStateException
    (sm.getString("standardManager.createSession.ise"));

  return (super.createSession());

    }


    // ------------------------------------------------------ Lifecycle Methods


    /**
     * Prepare for the beginning of active use of the public methods of this
     * component.  This method should be called after <code>configure()</code>,
     * and before any of the public methods of the component are utilized.
     *
     * @exception IllegalStateException if this component has already been
     *  started
     * @exception LifecycleException if this component detects a fatal error
     *  that prevents this component from being used
     */
    public void start() throws LifecycleException {

  // Validate and update our current component state
  if (started)
      throw new LifecycleException
    (sm.getString("standardManager.alreadyStarted"));
  started = true;

  // Load any previously persisted sessions
  load();

  // Start the background reaper thread
  threadStart();

    }


    /**
     * Gracefully terminate the active use of the public methods of this
     * component.  This method should be the last one called on a given
     * instance of this component.
     *
     * @exception IllegalStateException if this component has not been started
     * @exception LifecycleException if this component detects a fatal error
     *  that needs to be reported
     */
    public void stop() throws LifecycleException {

  // Validate and update our current component state
  if (!started)
      throw new LifecycleException
    (sm.getString("standardManager.notStarted"));
  started = false;

  // Stop the background reaper thread
  threadStop();

  // Save any currently active sessions
  unload();

  // Expire all active sessions
  Session sessions[] = findSessions();
  for (int i = 0; i < sessions.length; i++) {
      StandardSession session = (StandardSession) sessions[i];
      if (!session.isValid())
    continue;
      session.expire();
  }

    }


    // -------------------------------------------------------- Private Methods


    /**
     * Load any currently active sessions that were previously unloaded
     * to the specified persistence file, if any.
     *
     * @exception LifecycleException if a fatal error is encountered
     */
    private void load() throws LifecycleException {

  // Initialize our internal data structures
  recycled.removeAllElements();
  sessions.clear();

  // Open an input stream to the specified pathname, if any
  if (pathname == null)
      return;
  FileInputStream fis = null;
  ObjectInputStream ois = null;
  try {
      fis = new FileInputStream(pathname);
      ois = new ObjectInputStream(new BufferedInputStream(fis));
  } catch (FileNotFoundException e) {
      return;
  } catch (IOException e) {
      if (ois != null) {
    try {
        ois.close();
    } catch (IOException f) {
        ;
    }
    ois = null;
      }
      throw new LifecycleException("load/open: IOException", e);
  }

  // Load the previously unloaded active sessions
  synchronized (sessions) {
      try {
    Integer count = (Integer) ois.readObject();
    int n = count.intValue();
    for (int i = 0; i < n; i++) {
        Session session = (Session) ois.readObject();
        sessions.put(session.getId(), session);
    }
      } catch (ClassNotFoundException e) {
    if (ois != null) {
        try {
      ois.close();
        } catch (IOException f) {
      ;
        }
        ois = null;
    }
    throw new LifecycleException
        ("load/read: ClassNotFoundException", e);
      } catch (IOException e) {
    if (ois != null) {
        try {
      ois.close();
        } catch (IOException f) {
      ;
        }
        ois = null;
    }
    throw new LifecycleException("load/read: IOException", e);
      }
  }

  // Close the input stream
  try {
      ois.close();
  } catch (IOException f) {
      ;
  }

    }


    /**
     * Invalidate all sessions that have expired.
     */
    private void processExpires() {

  long timeNow = System.currentTimeMillis();
  Session sessions[] = findSessions();

  for (int i = 0; i < sessions.length; i++) {
      StandardSession session = (StandardSession) sessions[i];
      if (!session.isValid())
    continue;
      int maxInactiveInterval = session.getMaxInactiveInterval();
      if (maxInactiveInterval < 0)
    continue;
      int timeIdle = // Truncate, do not round up
    (int) ((timeNow - session.getLastAccessedTime()) / 1000L);
      if (timeIdle >= maxInactiveInterval)
    session.expire();
  }
    }


    /**
     * Save any currently active sessions in the specified persistence file,
     * if any.
     *
     * @exception LifecycleException if a fatal error is encountered
     */
    private void unload() throws LifecycleException {

  // Open an output stream to the specified pathname, if any
  if (pathname == null)
      return;
  FileOutputStream fos = null;
  ObjectOutputStream oos = null;
  try {
      fos = new FileOutputStream(pathname);
      oos = new ObjectOutputStream(new BufferedOutputStream(fos));
  } catch (IOException e) {
      if (oos != null) {
    try {
        oos.close();
    } catch (IOException f) {
        ;
    }
    oos = null;
      }
      throw new LifecycleException("unload/open: IOException", e);
  }

  // Write the number of active sessions, followed by the details
  synchronized (sessions) {
      try {
    oos.writeObject(new Integer(sessions.size()));
    Enumeration elements = sessions.elements();
    while (elements.hasMoreElements()) {
        Session session = (Session) elements.nextElement();
        oos.writeObject(session);
    }
      } catch (IOException e) {
    if (oos != null) {
        try {
      oos.close();
        } catch (IOException f) {
      ;
        }
        oos = null;
    }
    throw new LifecycleException("unload/write: IOException", e);
      }
  }

  // Flush and close the output stream
  try {
      oos.flush();
      oos.close();
      oos = null;
  } catch (IOException e) {
      if (oos != null) {
    try {
        oos.close();
    } catch (IOException f) {
        ;
    }
    oos = null;
      }
      throw new LifecycleException("unload/close: IOException", e);
  }

    }


    /**
     * Sleep for the duration specified by the <code>checkInterval</code>
     * property.
     */
    private void threadSleep() {

  try {
      Thread.sleep(checkInterval * 1000L);
  } catch (InterruptedException e) {
      ;
  }

    }


    /**
     * Start the background thread that will periodically check for
     * session timeouts.
     */
    private void threadStart() {

  if (thread != null)
      return;

  threadDone = false;
  thread = new Thread(this, threadName);
  thread.setDaemon(true);
  thread.start();

    }


    /**
     * Stop the background thread that is periodically checking for
     * session timeouts.
     */
    private void threadStop() {

  if (thread == null)
      return;

  threadDone = true;
  thread.interrupt();
  try {
      thread.join();
  } catch (InterruptedException e) {
      ;
  }

  thread = null;

    }


    // ------------------------------------------------------ Background Thread


    /**
     * The background thread that checks for session timeouts and shutdown.
     */
    public void run() {

  // Loop until the termination semaphore is set
  while (!threadDone) {
      threadSleep();
      processExpires();
  }

    }


}
TOP

Related Classes of org.apache.tomcat.session.StandardManager

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.