/* ======================================================================
The Bodington System Software License, Version 1.0
 
Copyright (c) 2001 The University of Leeds.  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 acknowledgement:  "This product includes
software developed by the University of Leeds
(http://www.bodington.org/)."  Alternately, this acknowledgement may
appear in the software itself, if and wherever such third-party
acknowledgements normally appear.
 
4.  The names "Bodington", "Nathan Bodington", "Bodington System",
"Bodington Open Source Project", and "The University of Leeds" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
d.gardner@leeds.ac.uk.
 
5.  The name "Bodington" may not appear in the name of products derived
from this software without prior written permission of the University of
Leeds.
 
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO,  TITLE,  THE IMPLIED WARRANTIES
OF QUALITY  AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
EVENT SHALL THE UNIVERSITY OF LEEDS 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 was originally created by the University of Leeds and may contain voluntary
contributions from others.  For more information on the Bodington Open Source Project, please
see http://bodington.org/
 
====================================================================== */

package org.bodington.servlet;

import java.util.Hashtable;
import java.util.Map;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;
import org.bodington.server.NavigationSession;

/**
 * Class that can be used to configure a chain of {@link SessionInitializer} 
 * instances. By calling the method {@link #getSessionInitializer(String)} you
 * can obtain a chain of {@link SessionInitializer} instances consisting of
 * default session initializers and (optionally) custom ones, chained in the
 * order that you specify.
 * @see #getSessionInitializer(String)
 * @see SessionInitializer
 * @author Alexis O'Connor
 */
public class SessionInitializerChain
{
    private static Logger log 
        = Logger.getLogger(SessionInitializerChain.class);
    public static final String DELIMITER = "->";
    
    /**
     * Constant representing the <em>Internal</em> session initializer.
     * @see InternalSessionInitializer
     */
    public static final String INTERNAL = "INTERNAL";
    
    /**
     * Constant representing the <em>Basic</em> session initializer.
     * @see BasicSessionInitializer
     */
    public static final String BASIC = "BASIC";
    
    /**
     * Constant representing the <em>WebAuth</em> session initializer.
     * @see WebAuthSessionInitializer
     */
    public static final String WEBAUTH = "WEBAUTH";
    
    /**
     * Constant representing the <em>X509</em> session initializer.
     * @see X509SessionInitializer
     */
    public static final String X509 = "X509";
    
    /**
     * Constant representing the <em>AUTO</em>matic session initializer.
     * @see AutoSessionInitializer
     */
    public static final String AUTO = "AUTO";
    
    // Map <authenticatorName: String, SessionInitializer>
    private static Map INITIALIZER_MAP = new Hashtable();
    static
    {
        INITIALIZER_MAP.put(INTERNAL, new InternalSessionInitializer());
        INITIALIZER_MAP.put(BASIC, new BasicSessionInitializer());
        INITIALIZER_MAP.put(WEBAUTH, new WebAuthSessionInitializer());
        INITIALIZER_MAP.put(X509, new X509SessionInitializer());
        INITIALIZER_MAP.put(AUTO, new AutoSessionInitializer());
    }
    
    private SessionInitializerChain() {}

    /**
     * Get an instance of a session initializer. The intention is that you can
     * use the object returned by this method to initialize sessions by calling
     * its {@link SessionInitializer#handleRequest(Request)} method. The object
     * returned is effectively the base node / root link of a chain of session
     * initializers specified via the the <code>config</code> parameter. The
     * order of the links matches what is specified. The names of the session
     * initializers can be any of the default ones, e.g. {@link #INTERNAL},
     * {@link #BASIC}, {@link #X509}, {@link #WEBAUTH}, {@link #AUTO}
     * or a custom one
     * specified by its fully-qualified class name. The rules for a custom
     * authenticator are the following:
     * <ul>
     * <li>it implements the interface {@link SessionInitializer}.
     * <li>it has a public no-arg constructor.
     * </ul>
     * The names of parameters should be separated by using the value of the
     * {@link #DELIMITER} constant. An example of a <code>config</code>
     * parameter would be <code>X509->INTERNAL->BASIC</code>. If this method
     * returns a non-null result, a further guarantee this method offers, is
     * that the chain will always return a non-null result from the
     * {@link SessionInitializer#handleRequest(Request)} method. If this method
     * is unable to find at least one session initializer, it will return
     * <code>null</code>.
     * @param config a string specifying the session initializers (in order).
     * @return an instance of a session initializer, or <code>null</code> if
     *         no matching session initializers could be found.
     * @see SessionInitializer#handleRequest(Request)
     */
    public static SessionInitializer getSessionInitializer(String config)
    {
        StringTokenizer tokenizer = new StringTokenizer( config, DELIMITER );
        SessionInitializer baseNode = null;
        SessionInitializer previous = null;
        SessionInitializer current = null;
        while(tokenizer.hasMoreTokens())
        {
            String token = tokenizer.nextToken();
            current = (SessionInitializer) INITIALIZER_MAP.get(token);
            
            // If it's not in map, is it a custom one?
            current = (current == null) 
                ? createCustomRequestAuthenticator( token ) : current;
            
            if (current == null) // no matching authenticator.
                continue;
            
            if (baseNode == null)
                baseNode = current;
            else
                previous.setNextSessionInitializer(current);
            
            previous = current;
        }
         
        // At least one authenticator configured?
        if (baseNode == null)
            return null;
        
        // Add a BEGIN link:
        baseNode = new SessionInitializerBookEnd( baseNode );
        // Add an END link:
        current = new SessionInitializerBookEnd( null );
        previous.setNextSessionInitializer( current );
        return baseNode;
    }
    
    /**
     * Create a custom session initializer from the specified string. The
     * class must exist, implement {@link SessionInitializer} and have a
     * public no-arg constructor. If any of these requirements fail, they are
     * logged as warnings to the class logger and the method returns
     * <code>null</code>.
     * @param className the fully qualified class name of the session
     *        initializer   .
     * @return an instance of an session initializer or <code>null</code> if
     *         one could not be instantiated from the argument.
     */
    private static SessionInitializer createCustomRequestAuthenticator(
        final String className )
    {
        Class clazz = null;
        try
        {
            clazz = Class.forName( className );
        }
        catch ( ClassNotFoundException e )
        {
            log.warn( "Request authenticator not found: " + className, e );
            return null;
        }
        if ( !SessionInitializer.class.isAssignableFrom( clazz ) )
        {
            log.warn( "Request authenticator " + className
                + " does not implement the interface "
                + SessionInitializer.class.getName() + "." );
            return null;
        }

        try
        {
            return (SessionInitializer)clazz.newInstance();
        }
        catch ( Exception e )
        {
            log.warn( "Request authenticator " + className
                + " does not appear to have a public no-arg constructor." );
            return null;
        }
    }
    
    /**
     * Simple implementation of a session initializer. Instances of this class
     * are used by the enclosing class to <em>book-end</em> the session
     * initializer chain proper. One instance is placed at the beginning and
     * another at the end. They are in order to provide a uniform interface to
     * the chain and ensure that a {@link NavigationSession} instance is
     * always returned, respectively.
     * @author Alexis O'Connor
     */
    static class SessionInitializerBookEnd implements SessionInitializer
    {
        private SessionInitializer next;
        
        private SessionInitializerBookEnd( SessionInitializer link)
        {
            this.next = link;
        }

        /**
         * Handle the request. If there is a subsequent link, this method
         * calls its {@link #handleRequest(Request)} method 
         * (<code>BEGIN</code> link). If there is not, then this method returns
         * an instance of {@link NavigationSession} by going via the associated
         * {@link org.bodington.servlet.HttpSession} instance (<code>END</code> 
         * link). 
         * @param request the request object.
         */
        public NavigationSession handleRequest( Request request )
        {
            if (next != null)
                return next.handleRequest( request );
            else
            {
                HttpSession session 
                    = (org.bodington.servlet.HttpSession) request.getSession();
                return session.getServerNavigationSession();
            }
        }

        public void setNextSessionInitializer( SessionInitializer initializer ) 
        {
            next = initializer;
        }
    }
}
