/**********************************************************************************
*
* $Header: /home/cvspublic/jakarta-jetspeed/src/java/org/apache/jetspeed/services/rundata/JetspeedRunDataService.java,v 1.3 2003/03/04 00:05:10 sgala 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.rundata;

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

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.turbine.services.rundata.TurbineRunDataService;
import org.apache.turbine.services.InitializationException;
import org.apache.turbine.util.RunData;
import org.apache.turbine.util.TurbineException;
import org.apache.turbine.util.Log;
import org.apache.turbine.services.TurbineServices;

import org.apache.jetspeed.services.rundata.JetspeedRunData;
import org.apache.jetspeed.services.statemanager.StateManagerService;


/**
* The JetspeedRunDataService extends TurbineRunDataService,
* adding the ability to get the current runData object for the thread
* at any time.  This is accomplished by storing the active runData objects
* in a map, keyed by thread.
* Also done here, because this is so nicely bracketed around each http request
* by Turbine, is the association of the http session for this request / thread
* with the state manager.
*
* @author <a href="mailto:ggolden@umich.edu">Glenn R. Golden</a>
* @version $Revision: 1.3 $
*/
public class JetspeedRunDataService
    extends TurbineRunDataService 
{
    /** The collection of active JetspeedRunData objects, keyed by Thread. */
    private Map m_runDataStore = null;

    /*******************************************************************************
    * Service implementation
    *******************************************************************************/

    /**
    * Initializes the service
    *
    * @throws InitializationException if initialization fails.
    */
    public void init()
        throws InitializationException
    {
        super.init();

        // allocate a thread-safe map
        m_runDataStore = Collections.synchronizedMap(new HashMap());

    }   // init

    /*******************************************************************************
    * TurbineRunDataService implementation
    *******************************************************************************/

    /**
    * Gets a RunData instance from a specific configuration.
    *
    * @param key a configuration key.
    * @param req a servlet request.
    * @param res a servlet response.
    * @param config a servlet config.
    * @return a new or recycled RunData object.
    * @throws TurbineException if the operation fails.
    * @throws IllegalArgumentException if any of the parameters are null.
    */
    public RunData getRunData(String key,
                                HttpServletRequest req,
                                HttpServletResponse res,
                                ServletConfig config)
        throws TurbineException, IllegalArgumentException
    {
        // let the super do the work
        JetspeedRunData r = (JetspeedRunData)super.getRunData(key, req, res, config);

        // store the rundata associated with this thread
        m_runDataStore.put(Thread.currentThread(), r);

        // associate this http session with this thread in the state manager
        StateManagerService stateManager = (StateManagerService)TurbineServices
                .getInstance().getService(StateManagerService.SERVICE_NAME);
        if (stateManager != null)
        {
            stateManager.setCurrentContext(req.getSession(true));
        }

        if (Log.getLogger().isDebugEnabled())
            Log.debug("JetspeedRunDataService: storing rundata " + r
                        + " for thread: " + Thread.currentThread());

        return r;

    }   // getRunData

    /**
    * Puts the used RunData object back to the factory for recycling.
    *
    * @param data the used RunData object.
    * @return true, if pooling is supported and the object was accepted.
    */
    public boolean putRunData(RunData data)
    {
        // un-associate this http session with this thread in the state manager
        StateManagerService stateManager = (StateManagerService)TurbineServices
                .getInstance().getService(StateManagerService.SERVICE_NAME);
        if (stateManager != null)
        {
            stateManager.clearCurrentContext();
        }

        // remove this thread's rundata
        m_runDataStore.remove(Thread.currentThread());

        if (Log.getLogger().isDebugEnabled())
            Log.debug("JetspeedRunDataService: releasing rundata for thread: "
                + Thread.currentThread());

        // let super do the work
        return super.putRunData(data);

    }   // putRunData

    /**
    * Access the current rundata object - the one associated with the current thread.
    * @return The current JetspeedRunData object associatd with the current thread.
    */
    public JetspeedRunData getCurrentRunData()
    {
        if (Log.getLogger().isDebugEnabled())
            Log.debug("JetspeedRunDataService: accessing rundata "
                        + m_runDataStore.get(Thread.currentThread())
                        + " for thread: " + Thread.currentThread());

        return (JetspeedRunData) m_runDataStore.get(Thread.currentThread());

    }   // getCurrentRunData

}   // JetspeedRunDataService

/**********************************************************************************
*
* $Header: /home/cvspublic/jakarta-jetspeed/src/java/org/apache/jetspeed/services/rundata/JetspeedRunDataService.java,v 1.3 2003/03/04 00:05:10 sgala Exp $
*
**********************************************************************************/

