/**********************************************************************************
*
* $Header: /home/cvspublic/jakarta-jetspeed/src/java/org/apache/jetspeed/services/statemanager/JetspeedHttpStateManagerService.java,v 1.2 2002/08/08 00:05:18 ggolden Exp $
*
* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000-2002 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 acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *     "Apache Jetspeed" 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" or
 *    "Apache Jetspeed", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * 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/>.
 */

// package
package org.apache.jetspeed.services.statemanager;

// imports
import java.util.HashMap;
import java.util.Map;
import java.util.Collections;
import java.util.Vector;
import java.util.Enumeration;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionBindingEvent;

import org.apache.jetspeed.services.statemanager.BaseStateManagerService;

/**
* <p>JetspeedHttpStateManagerService is an implementation of the BaseStateManagerService
* which manages the states stored in the "current" HttpSession.</p>
* <p>Note: This implementation of the StateManagerService takes advantage of the
* Servlet container's management of the HttpSession.
* When the session is invalidated, the states we manage will be automatically cleaned up.
* When this happens, the objects placed into our states will have their
* SessionStateBindingListener mechanism invoked.</p>
* <p>Note: This implementation segments the states by session.  States created in one session will NOT BE AVAILABLE
* from other sessions.</p>
* @version $Revision: 1.2 $
* @see org.apache.jetspeed.services.statemanager.BaseStateManagerService
* @see org.apache.jetspeed.services.statemanager.StateManagerService
* @see org.apache.jetspeed.services.statemanager.SessionState
* @author <a href="mailto:ggolden@apache.org">Glenn R. Golden</a>
*/
public class JetspeedHttpStateManagerService
    extends BaseStateManagerService
{
    /**
    * Initialize the states storage.
    */
    protected void initStates()
    {
    }   // initStates

    /**
    * Cleanup the states storage.
    */
    protected void shutdownStates()
    {
    }   // shutdownStates

    /**
    * Access the current HttpSession.
    */
    private HttpSession getSession()
    {
        // get the current session that was installed for this thread
        HttpSession session = (HttpSession) m_httpSessions.get(Thread.currentThread());
        if (session == null) return null;

        // call isNew just to see if the session has been invalidated already
        try
        {
            session.isNew();
        }
        catch (IllegalStateException e)
        {
            return null;
        }

        return session;

    }   // getSession

    /**
    * Convert the key to a name safe to store directly in the session.
    * @param key The state key.
    * @return a name safe to store directly in the session based on key.
    */
    private String getSessionKey( String key )
    {
        // we want our keys not to conflict with any other session usage...
        return JetspeedHttpStateManagerService.class.getName() + "." + key;

    }   // getSessionKey

    /**
    * Access the Map which is the set of attributes for a state.
    * @param key The state key.
    * @return The Map which is the set of attributes for a state.
    */
    protected Map getState( String key )
    {
        // get the session
        HttpSession session = getSession();
        if (session == null) return null;

        // get this state from our entry in the session
        StateEntry stateEntry = (StateEntry) session.getAttribute(getSessionKey(key));
        if (stateEntry == null) return null;

        return stateEntry.getMap();

    }   // getState

    /**
    * Add a new state to the states we are managing.
    * @param key The state key.
    * @param state The Map which is the set of attributes for the state.
    */
    protected void addState( String key, Map state )
    {
        // get the session
        HttpSession session = getSession();
        if (session == null) return;

        // create a stateEntry to hold our state Map
        StateEntry stateEntry = new StateEntry(key, state);

        // put it in the session
        session.setAttribute(getSessionKey(key), stateEntry);

    }   // addState

    /**
    * Remove a state from the states we are managing.
    * @param key The state key.
    */
    protected void removeState( String key )
    {
        // get the session
        HttpSession session = getSession();
        if (session == null) return;

        // remove the key from the session - the StateEntry will be notified
        session.removeAttribute(getSessionKey(key));

    }   // removeState

    /**
    * Access an array of the keys of all states managed, those that start with the parameter.
    * @param start The starting string used to select the keys.
    * @return an array of the keys of all states managed.
    */
    protected String[] getStateKeys( String start )
    {
        // get the session
        HttpSession session = getSession();
        if (session == null) return null;

        // use this as the test pattern
        String pattern = getSessionKey(start);

        // for those that match, this starts the session key
        int subStart = getSessionKey("").length();

        // collect for return
        Vector rv = new Vector();

        // get the session names
        Enumeration names = session.getAttributeNames();
        while (names.hasMoreElements())
        {
            String sessionName = (String) names.nextElement();
            
            // pick our states, and those whose key starts with the pattern
            if (sessionName.startsWith(pattern))
            {
                rv.add(sessionName.substring(subStart));
            }
        }

        if (rv.size() == 0) return null;

        return (String[]) rv.toArray(new String[rv.size()]);

    }   // getStateKeys

    /**
    * Store the Map for the state, and listen for HttpSessionBinding events
    */
    private class StateEntry
        implements HttpSessionBindingListener
    {
        /** Store the map. */
        private Map m_map = null;
        
        /** The state key. */
        private String m_key = null;

        /**
        * Construct.
        * @param key The state key.
        * @param map The map to hold.
        */
        public StateEntry( String key, Map map )
        {
            m_key = key;
            m_map = map;

        }   // StateEntry
        
        /**
        * Access the map we are holding.
        * @return the Map we are holding.
        */
        public Map getMap()
        {
            return m_map;

        }   // getMap

        /**
        * We don't care about when we are bound...
        */
        public void valueBound( HttpSessionBindingEvent event ) {}

        /**
        * When we are unbound, unbind our state's (map's) attributes
        */
        public void valueUnbound( HttpSessionBindingEvent event )
        {
            // notify all attribute and clear the state
            retireAttributes(m_key, m_map);
            m_map = null;
            m_key = null;
        }

    }   // class StateEntry

}   // JetspeedHttpStateManagerService

/**********************************************************************************
*
* $Header: /home/cvspublic/jakarta-jetspeed/src/java/org/apache/jetspeed/services/statemanager/JetspeedHttpStateManagerService.java,v 1.2 2002/08/08 00:05:18 ggolden Exp $
*
**********************************************************************************/

