Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * 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 static org.jboss.web.CatalinaMessages.MESSAGES;
 
 import java.io.File;
 
 
Standard implementation of the Manager 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.

IMPLEMENTATION NOTE: Correct behavior of session storing and reloading depends upon external calls to the start() and stop() methods of this class at the correct times.

Author(s):
Craig R. McClanahan
Jean-Francois Arcand
Version:
$Revision: 1857 $ $Date: 2011-10-27 18:52:51 +0200 (Thu, 27 Oct 2011) $
 
 
 public class StandardManager
     extends ManagerBase
     implements LifecyclePropertyChangeListener {
 
     public static final int MAX_ACTIVE_SESSIONS =
         Integer.valueOf(System.getProperty("org.apache.catalina.session.StandardManager.MAX_ACTIVE_SESSIONS"
                 (.....) ? "1024" : "-1")).intValue();
 
     public static final String PATHNAME =
         System.getProperty("org.apache.catalina.session.StandardManager.PATHNAME");
 
     // ---------------------------------------------------- Security Classes
     private class PrivilegedDoLoad
         implements PrivilegedExceptionAction {
 
         PrivilegedDoLoad() {
         }
 
         public Object run() throws Exception{
            doLoad();
            return null;
         }
     }
 
     private class PrivilegedDoUnload
         implements PrivilegedExceptionAction {
 
         PrivilegedDoUnload() {
         }
 
        public Object run() throws Exception{
            doUnload();
            return null;
        }
    }
    // ----------------------------------------------------- Instance Variables


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


    
The lifecycle event support for this component.
    protected LifecycleSupport lifecycle = new LifecycleSupport(this);


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


    
The descriptive name of this Manager implementation (for logging).
    protected static String name = "StandardManager";


    
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 null value indicates that no persistence is desired. If this pathname is relative, it will be resolved against the temporary working directory provided by our context, available via the javax.servlet.context.tempdir context attribute.
    protected String pathname = ;


    
Has this component been started yet?
    protected boolean started = false;


    
Number of session creations that failed due to maxActiveSessions.
    protected int rejectedSessions = 0;


    
Processing time during session expiration.
    protected long processingTime = 0;
    // ------------------------------------------------------------- Properties


    
Set the Container with which this Manager has been associated. If it is a Context (the usual case), listen for changes to the session timeout property.

Parameters:
container The associated Container
    public void setContainer(Container container) {
        // De-register from the old Container (if any)
        if ((this. != null) && (this. instanceof Context))
            ((Contextthis.).removePropertyChangeListener(this);
        // Default processing provided by our superclass
        super.setContainer(container);
        // Register with the new Container (if any)
        if ((this. != null) && (this. instanceof Context)) {
            ((Contextthis.).addPropertyChangeListener(this);
        }
    }


    
Return descriptive information about this Manager implementation and the corresponding version number, in the format <description>/<version>.
    public String getInfo() {
        return ();
    }


    
Return the maximum number of active Sessions allowed, or -1 for no limit.
    public int getMaxActiveSessions() {
        return (this.);
    }


    
Number of session creations that failed due to maxActiveSessions

Returns:
The count
    public int getRejectedSessions() {
        return ;
    }
    public void setRejectedSessions(int rejectedSessions) {
        this. = rejectedSessions;
    }


    
Set the maximum number of actives Sessions allowed, or -1 for no limit.

Parameters:
max The new maximum number of sessions
    public void setMaxActiveSessions(int max) {
        int oldMaxActiveSessions = this.;
        this. = max;
        .firePropertyChange("maxActiveSessions",
                                   new Integer(oldMaxActiveSessions),
                                   new Integer(this.));
    }


    
Return the descriptive short name of this Manager implementation.
    public String getName() {
        return ();
    }


    
Return the session persistence pathname, if any.
    public String getPathname() {
        return (this.);
    }


    
Set the session persistence pathname to the specified value. If no persistence support is desired, set the pathname to null.

Parameters:
pathname New session persistence pathname
    public void setPathname(String pathname) {
        String oldPathname = this.;
        this. = pathname;
        .firePropertyChange("pathname"oldPathnamethis.);
    }
    // --------------------------------------------------------- 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 null.

Throws:
java.lang.IllegalStateException if a new session cannot be instantiated for any reason
    public Session createSession(String sessionIdRandom random) {
        if (( >= 0) &&
            (.size() >= )) {
            ++;
            throw .managerMaxActiveSessions();
        }
        return (super.createSession(sessionIdrandom));
    }


    
Load any currently active sessions that were previously unloaded to the appropriate persistence mechanism, if any. If persistence is not supported, this method returns without doing anything.

Throws:
java.lang.ClassNotFoundException if a serialized class cannot be found during the reload
java.io.IOException if an input/output error occurs
    public void load() throws ClassNotFoundExceptionIOException {
        if (SecurityUtil.isPackageProtectionEnabled()){
            try{
                AccessController.doPrivilegednew PrivilegedDoLoad() );
            } catch (PrivilegedActionException ex){
                Exception exception = ex.getException();
                if (exception instanceof ClassNotFoundException){
                    throw (ClassNotFoundException)exception;
                } else if (exception instanceof IOException){
                    throw (IOException)exception;
                }
            }
        } else {
            doLoad();
        }
    }


    
Load any currently active sessions that were previously unloaded to the appropriate persistence mechanism, if any. If persistence is not supported, this method returns without doing anything.

Throws:
java.lang.ClassNotFoundException if a serialized class cannot be found during the reload
java.io.IOException if an input/output error occurs
    protected void doLoad() throws ClassNotFoundExceptionIOException {
        // Initialize our internal data structures
        .clear();
        // Open an input stream to the specified pathname, if any
        File file = file();
        if (file == null)
            return;
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        Loader loader = null;
        ClassLoader classLoader = null;
        try {
            fis = new FileInputStream(file.getAbsolutePath());
            BufferedInputStream bis = new BufferedInputStream(fis);
            if ( != null)
                loader = .getLoader();
            if (loader != null)
                classLoader = loader.getClassLoader();
            if (classLoader != null) {
                ois = new CustomObjectInputStream(bisclassLoader);
            } else {
                ois = new ObjectInputStream(bis);
            }
        } catch (FileNotFoundException e) {
            return;
        } catch (IOException e) {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException f) {
                    ;
                }
                ois = null;
            }
            throw e;
        }
        // Load the previously unloaded active sessions
        synchronized () {
            try {
                Integer count = (Integerois.readObject();
                int n = count.intValue();
                for (int i = 0; i < ni++) {
                    StandardSession session = getNewSession();
                    session.readObjectData(ois);
                    session.setManager(this);
                    if (session.isValidInternal()) {
                        .put(session.getIdInternal(), session);
                        session.activate();
                        ++;
                    }
                }
            } catch (ClassNotFoundException e) {
                ..managerLoadFailed(e);
                if (ois != null) {
                    try {
                        ois.close();
                    } catch (IOException f) {
                        ;
                    }
                    ois = null;
                }
                throw e;
            } catch (IOException e) {
                ..managerLoadFailed(e);
                if (ois != null) {
                    try {
                        ois.close();
                    } catch (IOException f) {
                        ;
                    }
                    ois = null;
                }
                throw e;
            } finally {
                // Close the input stream
                try {
                    if (ois != null)
                        ois.close();
                } catch (IOException f) {
                    // ignored
                }
                // Delete the persistent storage file
                if (file != null && file.exists() )
                    file.delete();
            }
        }
    }


    
Save any currently active sessions in the appropriate persistence mechanism, if any. If persistence is not supported, this method returns without doing anything.

Throws:
java.io.IOException if an input/output error occurs
    public void unload() throws IOException {
        if (SecurityUtil.isPackageProtectionEnabled()){
            try{
                AccessController.doPrivilegednew PrivilegedDoUnload() );
            } catch (PrivilegedActionException ex){
                Exception exception = ex.getException();
                if (exception instanceof IOException){
                    throw (IOException)exception;
                }
            }
        } else {
            doUnload();
        }
    }


    
Save any currently active sessions in the appropriate persistence mechanism, if any. If persistence is not supported, this method returns without doing anything.

Throws:
java.io.IOException if an input/output error occurs
    protected void doUnload() throws IOException {
        // Open an output stream to the specified pathname, if any
        File file = file();
        if (file == null)
            return;
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            fos = new FileOutputStream(file.getAbsolutePath());
            oos = new ObjectOutputStream(new BufferedOutputStream(fos));
        } catch (IOException e) {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException f) {
                    ;
                }
                oos = null;
            }
            throw e;
        }
        // Write the number of active sessions, followed by the details
        ArrayList list = new ArrayList();
        synchronized () {
            try {
                oos.writeObject(new Integer(.size()));
                Iterator elements = .values().iterator();
                while (elements.hasNext()) {
                    StandardSession session =
                        (StandardSessionelements.next();
                    list.add(session);
                    ((StandardSessionsession).passivate();
                    session.writeObjectData(oos);
                }
            } catch (IOException e) {
                ..managerUnloadFailed(e);
                if (oos != null) {
                    try {
                        oos.close();
                    } catch (IOException f) {
                        ;
                    }
                    oos = null;
                }
                throw 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 e;
        }
        // Expire all the sessions we just wrote
        Iterator expires = list.iterator();
        while (expires.hasNext()) {
            StandardSession session = (StandardSessionexpires.next();
            try {
                session.expire(false);
            } catch (Throwable t) {
                ;
            } finally {
                session.recycle();
            }
        }
    }
    // ------------------------------------------------------ Lifecycle Methods


    
Add a lifecycle event listener to this component.

Parameters:
listener The listener to add
    public void addLifecycleListener(LifecycleListener listener) {
        .addLifecycleListener(listener);
    }


    
Get the lifecycle listeners associated with this lifecycle. If this Lifecycle has no listeners registered, a zero-length array is returned.
        return .findLifecycleListeners();
    }


    
Remove a lifecycle event listener from this component.

Parameters:
listener The listener to remove
    public void removeLifecycleListener(LifecycleListener listener) {
        .removeLifecycleListener(listener);
    }

    
Prepare for the beginning of active use of the public methods of this component. This method should be called after configure(), and before any of the public methods of the component are utilized.

Throws:
org.apache.catalina.LifecycleException if this component detects a fatal error that prevents this component from being used
    public void start() throws LifecycleException {
        if( !  )
            init();
        // Validate and update our current component state
        if () {
            return;
        }
         = true;
        // Load unloaded sessions, if any
        try {
            load();
        } catch (Throwable t) {
        }
    }


    
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.

Throws:
org.apache.catalina.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 (!) {
            return;
        }
        .fireLifecycleEvent(null);
         = false;
        // Write out sessions
        try {
            unload();
        } catch (Throwable t) {
        }
        // Expire all active sessions
        Session sessions[] = findSessions();
        for (int i = 0; i < sessions.lengthi++) {
            Session session = sessions[i];
            try {
                if (session.isValid()) {
                    session.expire();
                }
            } catch (Throwable t) {
                ;
            } finally {
                // Measure against memory leaking if references to the session
                // object are kept in a shared field somewhere
                session.recycle();
            }
        }
        if ) {
            destroy();
        }
    }
    // ----------------------------------------- PropertyChangeListener Methods


    
Process property change events from our associated Context.

Parameters:
event The property change event that has occurred
    public void propertyChange(PropertyChangeEvent event) {
        // Validate the source of this event
        if (!(event.getSource() instanceof Context))
            return;
        Context context = (Contextevent.getSource();
        // Process a relevant property change
        if (event.getPropertyName().equals("sessionTimeout")) {
            try {
                setMaxInactiveInterval
                    ( ((Integerevent.getNewValue()).intValue()*60 );
            } catch (NumberFormatException e) {
            }
        }
    }
    // ------------------------------------------------------ Protected Methods


    
Return a File object representing the pathname to our persistence file, if any.
    protected File file() {
        if (( == null) || (.length() == 0))
            return (null);
        File file = new File();
        if (!file.isAbsolute()) {
            if ( instanceof Context) {
                ServletContext servletContext =
                    ((Context).getServletContext();
                File tempdir = (File)
                    servletContext.getAttribute(.);
                if (tempdir != null)
                    file = new File(tempdir);
            }
        }
//        if (!file.isAbsolute())
//            return (null);
        return (file);
    }
New to GrepCode? Check out our FAQ X