/* ======================================================================
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.server.resources;

import org.apache.log4j.Logger;

import java.rmi.*;
import java.util.Vector;
import java.util.Hashtable;
import java.util.Enumeration;
import java.util.Properties;
import java.security.cert.X509Certificate;
import org.bodington.database.PrimaryKey;
import org.bodington.server.*;
import org.bodington.server.realm.*;
import org.bodington.server.resources.ResourceTree;
import org.bodington.server.resources.Resource;
import org.bodington.text.Metadatum;

public class NavigationSessionImpl 
	extends org.bodington.server.MultiResourceSession
	implements NavigationSession, Remote
	{
    
    private static Logger log = Logger.getLogger(NavigationSessionImpl.class);
	Authenticator authenticator = null;
	String authenticator_alias = null;
	    
	Hashtable sessions_by_resource=new Hashtable();    

	    
	public NavigationSessionImpl()
		throws RemoteException
		{
		super();
		try 
			{
			gotoRoot();
			}
		catch ( Exception ex )
			{
			log.error("Unable to set resource to root: " + ex.getMessage(), ex );	       
			try
				{
				setResource( (PrimaryKey)null );
				}
			catch ( Exception ex2 )
				{
				}
			}
		}


        public BuildingSession getResourceSession( PrimaryKey resource_id )
		throws RemoteException, BuildingServerException
        {
            if ( resource_id == null )
                return null;
            
            if ( !isAuthenticated() )
                throw new BuildingServerException( "Can't start a session with a resource before authenticating." );
                
            synchronized( sessions_by_resource )
            {
                BuildingSessionImpl session = (BuildingSessionImpl)sessions_by_resource.get( resource_id );
                if ( session != null )
                    return session;
                
                try
                {
                    Resource resource = Resource.findResource( resource_id );
                    if ( resource == null )
                        return null;
                    Class c = resource.sessionClass();
                    if ( c!=null )
                    {
                       session = (BuildingSessionImpl)c.newInstance();
                       session.init( getAuthenticatedUserId(), resource_id );
                       sessions_by_resource.put( resource_id, session );
                    }
                    return session;
                }
                catch ( java.lang.InstantiationException iex )
                {
                    log.error( iex.getMessage(), iex );
                    throw new BuildingServerException( "Technical error starting session: " + iex );
                }
                catch ( java.lang.IllegalAccessException iaex )
                {
                    log.error( iaex.getMessage(), iaex );
                    throw new BuildingServerException( "Technical error starting session: " + iaex );
                }
            }
        }
        
        
	private Authenticator getAuthenticator( String alias )
	throws BuildingServerException
	{
	    authenticator = null;
	    String property_name = "authenticator.alias." + alias;
	    String class_name = BuildingContext.getProperty( property_name );
	    
	    if ( class_name == null )
		throw new BuildingServerException( "Unknown authenticator alias." );
	    
	    try
	    {
		Class authenticator_class;
		authenticator_class = Class.forName( class_name );
		authenticator = (Authenticator)authenticator_class.newInstance();
		authenticator_alias = alias;
		return authenticator;
		
	    }
	    catch ( ClassNotFoundException cnfe )
	    {
		authenticator = null;
		log.error( cnfe.getMessage(), cnfe );
		throw new BuildingServerException( "Unable to find the authentication code." );
	    }
	    catch ( InstantiationException ie )
	    {
		authenticator = null;
		log.error( ie.getMessage(), ie );
		throw new BuildingServerException( "Unable to create an authentication object." );
	    }
	    catch ( IllegalAccessException iae )
	    {
		authenticator = null;
		log.error( iae.getMessage(), iae );
		throw new BuildingServerException( "Unable to create an authentication object." );
	    }
	}
		
	public void clearAuthenticationCredentials()
		throws RemoteException, BuildingServerException
	{
	    authenticator = null;
	}
	
	public void setAuthenticationCredentials( Properties credentials, String alias )
		throws RemoteException, BuildingServerException
	{
	    try
	    {
		getAuthenticator( alias );
		authenticator.setAuthenticationCredentials( credentials );
	    }
	    catch ( AuthenticationException authe )
	    {
		authenticator = null;
		authenticator_alias = null;
		log.error( authe.getMessage(), authe );
		throw new BuildingServerException( "Technical problem authenticating credentials." );
	    }
	    
	}

        public void setClientX509( X509Certificate cert )
        throws RemoteException, BuildingServerException
        {
	    try
	    {
		InternalX509Authenticator int_authenticator = new InternalX509Authenticator();
		authenticator = int_authenticator;
                authenticator_alias = "_internal_x509_authenticator";
                int_authenticator.setClientX509( cert );
	    }
	    catch ( AuthenticationException authe )
	    {
		authenticator = null;
		authenticator_alias = null;
		log.error( authe.getMessage(), authe );
		throw new BuildingServerException( "Technical problem authenticating credentials." );
	    }
            
        }
	
	public boolean isAuthenticated()
		throws RemoteException, BuildingServerException
	{
	    try
	    {
		if ( authenticator == null )
		    return false;
		return authenticator.isAuthenticated();
	    }
	    catch ( AuthenticationException authe )
	    {
		log.error( authe.getMessage(), authe );
		throw new BuildingServerException( "Technical problem authenticating credentials." );
	    }
	}

	public boolean isAnonymous()
		throws RemoteException, BuildingServerException
	{
	    try
	    {
		if ( authenticator == null )
		    return false;
		return authenticator.isAnonymous();
	    }
	    catch ( AuthenticationException authe )
	    {		
		log.error(authe.getMessage(), authe );
		throw new BuildingServerException( "Technical problem authenticating credentials." );
	    }
	}
	
	public String getAuthenticationError()
		throws RemoteException, BuildingServerException
	{
	    try
	    {
		if ( authenticator == null )
		    return null;
		return authenticator.getAuthenticationError();
	    }
	    catch ( AuthenticationException authe )
	    {
		log.error( authe.getMessage(), authe );
		throw new BuildingServerException( "Technical problem authenticating credentials." );
	    }
	}
	
	public PrimaryKey getAuthenticatedUserId()
		throws RemoteException, BuildingServerException
	{
	    try
	    {
		if ( authenticator == null )
		    return null;
		return authenticator.getAuthenticatedUserId();
	    }
	    catch ( AuthenticationException authe )
	    {
		log.error( authe.getMessage(), authe );
		throw new BuildingServerException( "Technical problem authenticating credentials." );
	    }
	}
	
	public User getAuthenticatedUser()
		throws RemoteException, BuildingServerException
	{
	    PrimaryKey user_id = getAuthenticatedUserId();
	    return User.findUser( user_id );
	}
	
	public String getAuthenticatorAlias()
		throws RemoteException, BuildingServerException
	{
	    return authenticator_alias;
	}
		
	public synchronized void gotoRoot()
		throws RemoteException, BuildingServerException
		{
		ResourceTree tree = ResourceTree.getInstance();
		Resource root =  tree.findRootResource();
		setResource( root );
		}


	public synchronized String currentUserName()
		throws RemoteException, BuildingServerException
		{
		prepareMethodCall();
		try
			{
			if ( user_id == null )
				return "null";
			User user = getUser();
			if ( user == null )
				return "null";
			return user.getName();
			}
		finally
			{
			disposeMethodCall();
			}
			
		}
		
	public synchronized String resourceTitle()
		throws RemoteException, BuildingServerException
		{
		prepareMethodCall();
		try
			{
			if ( getResourceId() == null )
				return "null";
			Resource resource = getResource();
			if ( resource == null )
				return "null";
			return resource.getTitle();
			}
		finally
			{
			disposeMethodCall();
			}
		}
	
	public synchronized Vector childNames()
		throws RemoteException, BuildingServerException
		{
		prepareMethodCall();
		try
			{
			Vector list = new Vector( 10, 10 );

			if ( getResourceId() == null )
				return list;
			Resource resource = getResource();
			if ( resource == null )
				return list;
				
			
			Enumeration enumeration = resource.findChildren();
			Resource r;
			while ( enumeration.hasMoreElements() )
				{
				r = (Resource)enumeration.nextElement();
				list.addElement( r.getName() );
				}
			
			return list;
			}
		finally
			{
			disposeMethodCall();
			}
		}
		
	public synchronized ResourceSummary getSummary()
		throws RemoteException, BuildingServerException
		{
		prepareMethodCall();
		try
			{
			if ( getResourceId() == null )
				return null;
			Resource r = getResource();
			if ( r == null )
				return null;
				
			ResourceSummary summary;
			
			summary = new ResourceSummary();
			summary.setResourceId( r.getResourceId() );
			summary.setHttpFacilityNo( r.getHttpFacilityNo() );
			summary.setName( r.getName() );
			summary.setTitle( r.getTitle() );
			summary.setDescription( r.getDescription() );
			summary.setIntroduction( r.getIntroduction() );
			
			return summary;
			}
		finally
			{
			disposeMethodCall();
			}
		}
		
	public synchronized ResourceSummary getRootSummary()
		throws RemoteException, BuildingServerException
		{
		prepareMethodCall();
		try
			{
			ResourceTree tree = ResourceTree.getInstance();
			Resource r =  tree.findRootResource();
			if ( r == null )
				return null;
				
			ResourceSummary summary;
			
			summary = new ResourceSummary();
			summary.setResourceId( r.getResourceId() );
			summary.setHttpFacilityNo( r.getHttpFacilityNo() );
			summary.setName( r.getName() );
			summary.setTitle( r.getTitle() );
			summary.setDescription( r.getDescription() );
			summary.setIntroduction( r.getIntroduction() );
			
			return summary;
			}
		finally
			{
			disposeMethodCall();
			}
		}
		
	public synchronized Vector childSummaries()
		throws RemoteException, BuildingServerException
		{
		prepareMethodCall();
		try
			{
			if ( getResourceId() == null )
				throw new BuildingServerException( "No resource has been selected - can't supply any information." );
			return childSummaries( getResourceId() );
			}
		finally
			{
			disposeMethodCall();
			}
		}
		
	public synchronized Vector childSummaries( PrimaryKey r_id )
		throws RemoteException, BuildingServerException
		{
		prepareMethodCall();
		try
			{
			
			Vector list = new Vector( 10, 10 );

			if ( r_id == null )
				throw new BuildingServerException( "No resource has been selected - can't supply any information." );
			Resource resource = Resource.findResource( r_id );
			if ( resource == null )
				throw new BuildingServerException( "Specified resource couldn't be found." );
				
			
			Enumeration enumeration = resource.findChildren();
			Resource r;
			ResourceSummary summary;
			while ( enumeration.hasMoreElements() )
				{
				r = (Resource)enumeration.nextElement();
				summary = new ResourceSummary();
				summary.setResourceId( r.getResourceId() );
				summary.setHttpFacilityNo( r.getHttpFacilityNo() );
				summary.setName( r.getName() );
				summary.setTitle( r.getTitle() );
				summary.setDescription( r.getDescription() );
				summary.setIntroduction( r.getIntroduction() );
				list.addElement( summary );
				}
			
			return list;
			}
		finally
			{
			disposeMethodCall();
			}
		}
		
	public synchronized BuildingSession getSession()
		throws RemoteException, BuildingServerException
		{
		prepareMethodCall();
		try
			{
			Resource resource = getResource();
			if ( resource == null )
				throw new BuildingServerException( "Selected resource coudn't be found." );
			return BuildingSessionManagerImpl.getSession( resource );
			}
		finally
			{
			disposeMethodCall();
			}
		}
		
		
	public Resource findResource( PrimaryKey resource_id )
		throws RemoteException, BuildingServerException
	    {
		if ( resource_id == null )
		    return null;
		return Resource.findResource( resource_id );
	    }
	    
	public PrimaryKey findResourceId( String[] names )
		throws RemoteException, BuildingServerException
	    {
		ResourceTree tree = ResourceTree.getInstance();
		Resource r;
		if ( names==null || names.length == 0 )
		    r = tree.findResource( "/" );
		else
		    r = tree.findResource( names );
		if ( r==null )
		    return null;
		return r.getResourceId();
	    }

	    
	public String getUserPreferredStyleSheet()
		throws RemoteException, BuildingServerException
	{
	    User user = (User)BuildingContext.getContext().getUser();
	    String stylefile = "standard.css";
	    Metadatum metadatum = Metadatum.findMetadatumByIdAndName( user.getUserId(), "preference.stylesheet" );
	    if ( metadatum != null )
	    {
		stylefile=metadatum.getValue();
	    }
	    return stylefile;
	}
	    
	
	public String getUserProperty( String name )
		throws RemoteException, BuildingServerException
	{
	    String value=null;
	    User user = (User)BuildingContext.getContext().getUser();
	    Metadatum metadatum = Metadatum.findMetadatumByIdAndName( user.getUserId(), name );
	    if ( metadatum != null )
	    {
		value=metadatum.getValue();
	    }
	    return value;
	}
	
	public void setUserProperty( String name, String value )
		throws RemoteException, BuildingServerException
	{
	    if ( name == null )
		throw new BuildingServerException( "Null property name not allowed." );
	    
	    User user = (User)BuildingContext.getContext().getUser();
	    Metadatum metadatum = Metadatum.findMetadatumByIdAndName( user.getUserId(), name );
	    
	    if ( value == null )
	    {
		if ( metadatum != null )
		    metadatum.delete();
		return;
	    }
	    
	    if ( metadatum == null )
	    {
		metadatum = new Metadatum();
		metadatum.setObjectId( user.getUserId() );
		metadatum.setName( name );
	    }
	    metadatum.setValue( value );
	    metadatum.save();
	}
		    

        private class InternalX509Authenticator implements Authenticator
        {
            PrimaryKey authenticated_user_id = null;
            X509Certificate authenticated_cert = null;
            
            String authentication_error = null;
            
            public void changeCredentials(Properties credentials) throws AuthenticationException
            {
                // ignore
            }
            
            public PrimaryKey getAuthenticatedUserId() throws AuthenticationException
            {
                return authenticated_user_id;
            }
            
            public String getAuthenticationError() throws AuthenticationException
            {
            	//return null;
                return authentication_error;                        	
            }
            
            public boolean isAnonymous() throws AuthenticationException
            {
                return false;
            }
            
            public boolean isAuthenticated() throws AuthenticationException
            {
                return authenticated_user_id != null;
            }
            
            public void setAuthenticationCredentials(Properties credentials) throws AuthenticationException
            {
                // ignore
            }
            
            public void setClientX509( X509Certificate cert )
            throws BuildingServerException, AuthenticationException
            {
                java.security.cert.X509Certificate stored_cert;
                int serial = cert.getSerialNumber().intValue();
                String dn = cert.getSubjectDN().getName();
                UserX509 user_x509;
                
                // look for certificates with same serial number
                // and DN
                Enumeration enumeration = UserX509.findUserX509s( serial, dn );
                while ( enumeration.hasMoreElements() )
                {
                    // for each certificate with same serial and dn see if it
                    // exactly matches the one the user presented.
                    user_x509 = (UserX509)enumeration.nextElement();
                    stored_cert = user_x509.getX509Certificate();
                    if ( cert.equals( stored_cert ) )
                    {
                    	//added by ninging for user expired status check.
                    	User user = User.findUser(user_x509.getUserId());
                    	if (user != null && user.getStatusExpired() != 0)
                    	{
                    		log.warn("User " + user_x509.getUserId() + " has expired!");
                    		authentication_error = "User has expired.";
                    		return; // not to set authenticated_user_id and authenticated_cert
                    	}
                    	//added end.
                    	
                        authenticated_user_id = user_x509.getUserId();                                                
                        authenticated_cert = cert;
                        return;
                    }
                }

            }
        }
        
        
	}


