cziegeler    2003/04/27 05:52:53

  Modified:    
src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/components
                        DefaultHandlerManager.java Manager.java
                        DefaultAuthenticationManager.java
                        Authenticator.java
               
src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication
                        AuthenticationConstants.java
  Added:       
src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/user
                        UserHandler.java RequestState.java UserState.java
               
src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/configuration
                        ApplicationConfiguration.java
                        HandlerConfiguration.java
               
src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/context
                        AuthenticationContextProvider.java
                        AuthenticationContext.java
  Removed:     
src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/components
                        Status.java UserHandler.java UserStatus.java
                        HandlerConfiguration.java
                        ApplicationConfiguration.java
  Log:
  Refactoring of authentication framework - continued
  
  Revision  Changes    Path
  1.1                  
cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/user/UserHandler.java
  
  Index: UserHandler.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, 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 Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", 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 (INCLU-
   DING, 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 and was  originally created by
   Stefano Mazzocchi  <[EMAIL PROTECTED]>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.webapps.authentication.user;
  
  import org.apache.cocoon.ProcessingException;
  import 
org.apache.cocoon.webapps.authentication.configuration.HandlerConfiguration;
  import org.apache.cocoon.webapps.session.context.SessionContext;
  
  /**
   * The authentication Handler.
   *
   * @author <a href="mailto:[EMAIL PROTECTED]">Carsten Ziegeler</a>
   * @version CVS $Id: UserHandler.java,v 1.1 2003/04/27 12:52:53 cziegeler Exp 
$
  */
  public final class UserHandler
  implements java.io.Serializable {
  
      /** The corresponding handler */
      private HandlerConfiguration handler;
      
      /** Are all apps loaded? */
      private boolean appsLoaded = false;
  
     /**
       * Create a new handler object.
       */
      public UserHandler(HandlerConfiguration handler) {
          this.handler = handler;
      }
  
      public void setApplicationsLoaded(boolean value)
      throws ProcessingException {
          this.appsLoaded = value;
      }
  
      public boolean getApplicationsLoaded()
      throws ProcessingException {
          if ( this.handler.getApplications().isEmpty() ) {
              return true;
          } else {
              return this.appsLoaded;
          }
      }
      
      /**
       * Add a handler context
       */
      public SessionContext getContext() {
          // TODO
          return null;
      }
  
      /**
       * Get the handler name
       */
      public String getHandlerName() {
          return this.handler.getName();
      }
      
      /**
       * Get the handler configuration
       */
      public HandlerConfiguration getHandlerConfiguration() {
          return this.handler;
      }
  }
  
  
  
  1.1                  
cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/user/RequestState.java
  
  Index: RequestState.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, 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 Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", 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 (INCLU-
   DING, 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 and was  originally created by
   Stefano Mazzocchi  <[EMAIL PROTECTED]>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.webapps.authentication.user;
  
  import java.util.Map;
  
  import org.apache.cocoon.components.CocoonComponentManager;
  import 
org.apache.cocoon.webapps.authentication.configuration.ApplicationConfiguration;
  
  
  /**
   * The state of the user for the current request.
   * This object holds the information which handler and application
   * is currently used for this request.
   *
   * @author <a href="mailto:[EMAIL PROTECTED]">Carsten Ziegeler</a>
   * @version CVS $Id: RequestState.java,v 1.1 2003/04/27 12:52:53 cziegeler 
Exp $
  */
  public final class RequestState
  implements java.io.Serializable {
  
      private static final String KEY = RequestState.class.getName();
      
      /** The handlers */
      private UserHandler handler;
          
      /** The application */
      private String application;
      
      public static RequestState getState() {
          final Map objectModel = 
CocoonComponentManager.getCurrentEnvironment().getObjectModel();
          return (RequestState)objectModel.get(KEY);
      }
      
      public static void setState(RequestState status) {
          final Map objectModel = 
CocoonComponentManager.getCurrentEnvironment().getObjectModel();
          if ( status != null ) {
              objectModel.put( KEY, status);
          } else {
              objectModel.remove( KEY );
          }
      }
      
      /**
       * Create a new handler object.
       */
      public RequestState(UserHandler handler, String app) {
          this.handler = handler;
          this.application = app;
      }
  
      public String getApplicationName() {
          return this.application;
      }
      
      public UserHandler getHandler() {
          return this.handler;
      }
      
      public String getHandlerName() {
          return this.handler.getHandlerName();
      }
      
      public ApplicationConfiguration getApplicationConfiguration() {
          if ( this.application != null ) {
              return 
(ApplicationConfiguration)this.handler.getHandlerConfiguration().getApplications().get(this.application);
          }
          return null;
      }
  }
  
  
  
  1.1                  
cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/user/UserState.java
  
  Index: UserState.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, 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 Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", 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 (INCLU-
   DING, 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 and was  originally created by
   Stefano Mazzocchi  <[EMAIL PROTECTED]>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.webapps.authentication.user;
  
  import java.util.HashMap;
  import java.util.Map;
  
  /**
   * The state of the user.
   * This object holds all authentication handlers ([EMAIL PROTECTED] 
UserHandler}
   * the user is currently logged-in to.
   *
   * @author <a href="mailto:[EMAIL PROTECTED]">Carsten Ziegeler</a>
   * @version CVS $Id: UserState.java,v 1.1 2003/04/27 12:52:53 cziegeler Exp $
  */
  public final class UserState
  implements java.io.Serializable {
  
      /** The handlers */
      private Map handlers = new HashMap(7);
  
     /**
       * Create a new handler object.
       */
      public UserState() {
      }
  
      public void addHandler(UserHandler value) {
          this.handlers.put(value.getHandlerName(), value);
      }
  
      public void removeHandler(String name) {
          this.handlers.remove( name );
      }
      
      public UserHandler getHandler(String name) {
          return (UserHandler) this.handlers.get( name );
      }
      
      public boolean hasHandler() {
          return (this.handlers.size() > 0);
      }
  }
  
  
  
  1.3       +2 -1      
cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/components/DefaultHandlerManager.java
  
  Index: DefaultHandlerManager.java
  ===================================================================
  RCS file: 
/home/cvs/cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/components/DefaultHandlerManager.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- DefaultHandlerManager.java        21 Apr 2003 19:26:14 -0000      1.2
  +++ DefaultHandlerManager.java        27 Apr 2003 12:52:53 -0000      1.3
  @@ -60,6 +60,7 @@
   import org.apache.cocoon.components.ChainedConfiguration;
   import org.apache.cocoon.components.SitemapConfigurationHolder;
   import org.apache.cocoon.environment.ObjectModelHelper;
  +import org.apache.cocoon.webapps.authentication.configuration.*;
   import org.apache.excalibur.source.SourceResolver;
   
   
  
  
  
  1.4       +17 -10    
cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/components/Manager.java
  
  Index: Manager.java
  ===================================================================
  RCS file: 
/home/cvs/cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/components/Manager.java,v
  retrieving revision 1.3
  retrieving revision 1.4
  diff -u -r1.3 -r1.4
  --- Manager.java      21 Apr 2003 19:26:14 -0000      1.3
  +++ Manager.java      27 Apr 2003 12:52:53 -0000      1.4
  @@ -55,12 +55,14 @@
   import org.apache.cocoon.ProcessingException;
   import org.apache.cocoon.environment.Redirector;
   import org.apache.excalibur.source.SourceParameters;
  -import org.w3c.dom.DocumentFragment;
   
   
   
   /**
  - * This is the basis authentication component.
  + * This is the authentication manager.
  + * It is used to authenticate (login, logout) a user. Usually, this
  + * component should not be used from custom code. The provided
  + * actions perform all required tasks.
    *
    * @author <a href="mailto:[EMAIL PROTECTED]">Carsten Ziegeler</a>
    * @version CVS $Id$
  @@ -72,12 +74,15 @@
   
       /**
        * Is the current user authenticated for the given handler?
  +     * @return Returns true of the user is authenticated.
        */
       boolean isAuthenticated(String handlerName)
       throws ProcessingException;
   
       /**
        * Is the current user authenticated for the given handler?
  +     * If the user is already authenticated, the [EMAIL PROTECTED] 
RequestState}
  +     * is updated to the provided information (handler and application).
        */
       boolean checkAuthentication(Redirector redirector,
                                    String     handlerName,
  @@ -85,16 +90,18 @@
       throws ProcessingException, IOException;
   
       /**
  -     * Authenticate
  -     * If the authentication is successful, <code>null</code> is returned.
  -     * If not an element "failed" is return. If handler specific error
  -     * information is available this is also returned.
  +     * Try to login the user.
  +     * If the authentication is successful, <code>true</code> is returned.
  +     * If not, <code>false</code> is returned.
        */
  -    DocumentFragment authenticate(String              handlerName,
  -                                  String              applicationName,
  -                                  SourceParameters    parameters)
  +    boolean login(String              handlerName,
  +                   String              applicationName,
  +                   SourceParameters    parameters)
       throws ProcessingException;
   
  +    /**
  +     * Perform a logout of the user.
  +     */
       void logout(String handlerName,
                    int mode)
       throws ProcessingException;
  
  
  
  1.5       +102 -37   
cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/components/DefaultAuthenticationManager.java
  
  Index: DefaultAuthenticationManager.java
  ===================================================================
  RCS file: 
/home/cvs/cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/components/DefaultAuthenticationManager.java,v
  retrieving revision 1.4
  retrieving revision 1.5
  diff -u -r1.4 -r1.5
  --- DefaultAuthenticationManager.java 21 Apr 2003 19:26:14 -0000      1.4
  +++ DefaultAuthenticationManager.java 27 Apr 2003 12:52:53 -0000      1.5
  @@ -53,6 +53,8 @@
   import java.io.IOException;
   import java.util.Map;
   
  +import org.apache.avalon.framework.activity.Disposable;
  +import org.apache.avalon.framework.component.Component;
   import org.apache.avalon.framework.configuration.ConfigurationException;
   import org.apache.avalon.framework.logger.AbstractLogEnabled;
   import org.apache.avalon.framework.service.ServiceException;
  @@ -68,9 +70,15 @@
   import org.apache.cocoon.environment.Request;
   import org.apache.cocoon.environment.Session;
   import org.apache.cocoon.environment.SourceResolver;
  +import org.apache.cocoon.webapps.authentication.AuthenticationConstants;
  +import 
org.apache.cocoon.webapps.authentication.configuration.HandlerConfiguration;
  +import 
org.apache.cocoon.webapps.authentication.context.AuthenticationContextProvider;
  +import org.apache.cocoon.webapps.authentication.user.RequestState;
  +import org.apache.cocoon.webapps.authentication.user.UserHandler;
  +import org.apache.cocoon.webapps.authentication.user.UserState;
  +import org.apache.cocoon.webapps.session.components.SessionManager;
   import org.apache.excalibur.source.SourceParameters;
   import org.apache.excalibur.source.SourceUtil;
  -import org.w3c.dom.DocumentFragment;
   
   /**
    * This is the basis authentication component.
  @@ -80,7 +88,7 @@
   */
   public final class DefaultAuthenticationManager
   extends AbstractLogEnabled
  -implements Manager, SitemapConfigurable, Serviceable, ThreadSafe {
  +implements Manager, SitemapConfigurable, Serviceable, Disposable, 
ThreadSafe, Component {
   
       /** The name of the session attribute storing the user status */
       public final static String SESSION_ATTRIBUTE_USER_STATUS = 
DefaultAuthenticationManager.class.getName() + "/UserStatus";
  @@ -91,6 +99,24 @@
       /** The Service Manager */
       private ServiceManager manager;
       
  +    /** The authenticator used to authenticate a user */
  +    private Authenticator authenticator;
  +    
  +    /** Init the class,
  +     *  add the provider for the authentication context
  +     */
  +    static {
  +        // add the provider for the authentication context
  +        AuthenticationContextProvider contextProvider = new 
AuthenticationContextProvider();
  +        // TODO
  +/*        try {
  +            // FIXME - this is static!!!
  +            SessionManager.addSessionContextProvider(contextProvider, 
AuthenticationConstants.SESSION_CONTEXT_NAME);
  +        } catch (ProcessingException local) {
  +            throw new CascadingRuntimeException("Unable to register provider 
for authentication context.", local);
  +        }*/
  +    }
  +
       /**
        * Set the sitemap configuration containing the handlers
        */
  @@ -126,8 +152,8 @@
   
       /**
        * Get the handler configuration
  -     * @param name
  -     * @return
  +     * @param name The handler name
  +     * @return The configuration or null.
        */
       private HandlerConfiguration getHandlerConfiguration(String name) 
       throws ProcessingException {   
  @@ -148,34 +174,34 @@
           return this.getRequest().getSession(create);
       }
       
  -    private UserStatus getUserStatus() {
  +    private UserState getUserState() {
           final Session session = this.getSession( false );
  -        UserStatus status = null;
  +        UserState status = null;
           if ( session != null) {
  -            status = (UserStatus) 
session.getAttribute(SESSION_ATTRIBUTE_USER_STATUS);
  +            status = (UserState) 
session.getAttribute(SESSION_ATTRIBUTE_USER_STATUS);
           }
           return status;
       }
   
  -    private UserStatus createUserStatus() {
  -        UserStatus status = this.getUserStatus();
  +    private UserState createUserState() {
  +        UserState status = this.getUserState();
           if ( status == null ) {
               final Session session = this.getSession(true);
  -            status = new UserStatus();
  +            status = new UserState();
               session.setAttribute(SESSION_ATTRIBUTE_USER_STATUS, status);
           }
           return status;
       }
       
       private UserHandler getUserHandler(String name) {
  -        final UserStatus status = this.getUserStatus();
  +        final UserState status = this.getUserState();
           if ( status != null ) {
  -            return status.getUserHandler( name );
  +            return status.getHandler( name );
           }
           return null;
       }
       
  -    private void updateUserStatus() {
  +    private void updateUserState() {
           final Session session = this.getSession(true);
           Object status = session.getAttribute(SESSION_ATTRIBUTE_USER_STATUS);
           session.setAttribute(SESSION_ATTRIBUTE_USER_STATUS, status);
  @@ -184,9 +210,9 @@
        /* (non-Javadoc)
         * @see 
org.apache.cocoon.webapps.authentication.components.Manager#authenticate(java.lang.String,
 java.lang.String, org.apache.excalibur.source.SourceParameters)
         */
  -     public DocumentFragment authenticate(String handlerName,
  -                                          String applicationName,
  -                                          SourceParameters parameters)
  +     public boolean login(String handlerName,
  +                           String applicationName,
  +                           SourceParameters parameters)
       throws ProcessingException {
           HandlerConfiguration config = this.getHandlerConfiguration( 
handlerName );
           if ( config == null ) {
  @@ -198,16 +224,22 @@
               throw new ProcessingException("User is already authenticated 
using handler: " + handlerName);
           }
           
  -        // TODO Authentication
  +        // This could be made pluggable, if required
  +        handler = this.authenticator.authenticate( config, parameters );
           
  -        // create UserStatus
  -        final UserStatus status = this.createUserStatus();
  -        handler = new UserHandler( config );
  +        if ( handler != null ) {
  +            // create UserStatus
  +            final UserState status = this.createUserState();
           
  -        status.addHandler( handler );        
  -        this.updateUserStatus();
  +            status.addHandler( handler );        
  +            this.updateUserState();
           
  -             return null;
  +            // update RequestState
  +            RequestState state = new RequestState( handler, applicationName 
);
  +            RequestState.setState( state );
  +        }
  +        
  +             return (handler != null);
        }
   
        /* (non-Javadoc)
  @@ -237,6 +269,10 @@
               parameters.setSingleParameterValue("resource", resource);
               final String redirectURI = config.getRedirectURI();
               redirector.globalRedirect(false, 
SourceUtil.appendParameters(redirectURI, parameters));
  +        } else {
  +            // update state
  +            RequestState state = new RequestState( handler, applicationName 
);
  +            RequestState.setState( state );
           }
           
                return authenticated;
  @@ -263,22 +299,37 @@
           UserHandler handler = this.getUserHandler( handlerName );
           // we don't throw an exception if we are already logged out!
           if ( handler != null ) {
  -            UserStatus status = this.getUserStatus();
  +            UserState status = this.getUserState();
               status.removeHandler( handlerName );
  -            this.updateUserStatus();
  -        }
  -        
  -        /*
  -        if ( mode == AuthenticationConstants.LOGOUT_MODE_IMMEDIATELY ) {
  -            this.getSessionManager().terminateSession(true);
  -        } else if (!this.handlerManager.hasUserHandler( this.request )) {
  -            if (mode == AuthenticationConstants.LOGOUT_MODE_IF_UNUSED) {
  -                this.getSessionManager().terminateSession(false);
  -            } else {
  -                this.getSessionManager().terminateSession(true);
  +            this.updateUserState();
  +
  +            // handling of session termination
  +            SessionManager sessionManager = null;
  +            try {
  +                sessionManager = (SessionManager)this.manager.lookup( 
SessionManager.ROLE );
  +            
  +                if ( mode == AuthenticationConstants.LOGOUT_MODE_IMMEDIATELY 
) {
  +                    sessionManager.terminateSession(true);
  +                } else if ( mode == 
AuthenticationConstants.LOGOUT_MODE_IF_UNUSED ) {
  +                    if ( !status.hasHandler()) {
  +                        sessionManager.terminateSession( false ); 
  +                    }
  +                 
  +                } else if ( mode == 
AuthenticationConstants.LOGOUT_MODE_IF_NOT_AUTHENTICATED) {
  +                    if ( !status.hasHandler()) {
  +                        sessionManager.terminateSession( true ); 
  +                    }
  +                } else {
  +                    throw new ProcessingException("Unknown logout mode: " + 
mode);
  +                }
  +            
  +            } catch (ServiceException se) {
  +                throw new ProcessingException("Unable to lookup session 
manager.", se);
  +            } finally {
  +                this.manager.release( sessionManager );
               }
           }
  -        */
  +        
        }
   
        /**
  @@ -287,6 +338,20 @@
        public void service(ServiceManager manager) 
       throws ServiceException {
           this.manager = manager;
  +        this.authenticator = new Authenticator();
  +        this.authenticator.enableLogging( this.getLogger() );
  +        this.authenticator.service( this.manager );
  +     }
  +
  +     /* (non-Javadoc)
  +      * @see org.apache.avalon.framework.activity.Disposable#dispose()
  +      */
  +     public void dispose() {
  +             if ( this.authenticator != null ) {
  +            this.authenticator.dispose();
  +            this.authenticator = null;
  +             }
  +        this.manager = null;
        }
   
   }
  
  
  
  1.2       +222 -4    
cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/components/Authenticator.java
  
  Index: Authenticator.java
  ===================================================================
  RCS file: 
/home/cvs/cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/components/Authenticator.java,v
  retrieving revision 1.1
  retrieving revision 1.2
  diff -u -r1.1 -r1.2
  --- Authenticator.java        27 Apr 2003 09:42:42 -0000      1.1
  +++ Authenticator.java        27 Apr 2003 12:52:53 -0000      1.2
  @@ -50,26 +50,54 @@
   */
   package org.apache.cocoon.webapps.authentication.components;
   
  +import java.io.IOException;
  +import java.util.Iterator;
  +
  +import org.apache.avalon.framework.activity.Disposable;
   import org.apache.avalon.framework.logger.AbstractLogEnabled;
  +import org.apache.avalon.framework.service.ServiceException;
  +import org.apache.avalon.framework.service.ServiceManager;
  +import org.apache.avalon.framework.service.Serviceable;
  +import org.apache.avalon.framework.thread.ThreadSafe;
   import org.apache.cocoon.ProcessingException;
  +import org.apache.cocoon.webapps.authentication.MediaManager;
  +import 
org.apache.cocoon.webapps.authentication.configuration.ApplicationConfiguration;
  +import 
org.apache.cocoon.webapps.authentication.configuration.HandlerConfiguration;
  +import org.apache.cocoon.webapps.authentication.user.UserHandler;
  +import org.apache.cocoon.webapps.session.SessionConstants;
  +import org.apache.cocoon.webapps.session.components.SessionManager;
  +import org.apache.cocoon.webapps.session.context.SessionContext;
   import org.apache.cocoon.xml.XMLUtils;
   import org.apache.cocoon.xml.dom.DOMUtil;
  +import org.apache.excalibur.source.Source;
  +import org.apache.excalibur.source.SourceException;
  +import org.apache.excalibur.source.SourceParameters;
  +import org.apache.excalibur.source.SourceResolver;
   import org.w3c.dom.Document;
   import org.w3c.dom.DocumentFragment;
   import org.w3c.dom.Element;
   import org.w3c.dom.Node;
   import org.w3c.dom.NodeList;
   import org.w3c.dom.Text;
  +import org.xml.sax.SAXException;
   
   /**
  - * Verify if the a user could be authenticated
  + * Verify if the a user could be authenticated.
  + * This is a helper class that could be made pluggable if required.
    *
    * @author <a href="mailto:[EMAIL PROTECTED]">Carsten Ziegeler</a>
    * @version CVS $Id$
   */
  -public class Authenticator 
  -    extends AbstractLogEnabled {
  +public final class Authenticator 
  +    extends AbstractLogEnabled
  +    implements Serviceable, ThreadSafe, Disposable {
           
  +    /** The service manager */
  +    private ServiceManager manager;
  +    
  +    /** The source resolver */
  +    private SourceResolver resolver;
  +    
       /**
        * Check the fragment if it is valid
        */
  @@ -126,5 +154,195 @@
           }
           return isValid;
       }
  +
  +    /**
  +     * Try to authenticate the user.
  +     * @return A new [EMAIL PROTECTED] UserHandler} if authentication was 
successful
  +     * @throws ProcessingException
  +     */
  +    public UserHandler authenticate( HandlerConfiguration configuration,
  +                                      SourceParameters      parameters)
  +    throws ProcessingException {
  +        if (this.getLogger().isDebugEnabled() ) {
  +            this.getLogger().debug("start authenticator using handler " + 
configuration.getName());
  +        }
  +
  +        final String   authenticationResourceName = 
configuration.getAuthenticationResource();
  +        final SourceParameters authenticationParameters = 
configuration.getAuthenticationResourceParameters();
  +        if (parameters != null) {
  +            parameters.add(authenticationParameters);
  +        } else {
  +            parameters = authenticationParameters;
  +        }
  +
  +        Document doc = null;
  +        String exceptionMsg = null;
  +        
  +        // invoke the source
  +        try {
  +            Source source = null;
  +            try {
  +                source = 
org.apache.cocoon.components.source.SourceUtil.getSource(authenticationResourceName,
 
  +                                                                             
     null, 
  +                                                                             
     parameters, 
  +                                                                             
     this.resolver);
  +                
  +                doc = 
org.apache.cocoon.components.source.SourceUtil.toDOM(source);
  +            } catch (SAXException se) {
  +                throw new ProcessingException(se);
  +            } catch (SourceException se) {
  +                throw 
org.apache.cocoon.components.source.SourceUtil.handle(se);
  +            } catch (IOException e) {
  +                throw new ProcessingException(e);
  +                     } finally {
  +                this.resolver.release(source);
  +            }
  +
  +        } catch (ProcessingException local) {
  +            this.getLogger().error("authenticator: " + local.getMessage(), 
local);
  +            exceptionMsg = local.getMessage();
  +        }
  +
  +        // test if authentication was successful
  +        boolean isValid = false;
  +        UserHandler handler = null;
  +        if (doc != null) {
  +            isValid = this.isValidAuthenticationFragment( doc );
  +
  +            if ( isValid ) {
  +                if (this.getLogger().isInfoEnabled() ) {
  +                    this.getLogger().info("Authenticator: User authenticated 
using handler '" + configuration.getName()+"'");
  +                }
  +                
  +                handler = new UserHandler(configuration);
  +                
  +                SessionContext context = handler.getContext();
  +
  +                MediaManager mediaManager = null;
  +                String mediaType;
  +                try {
  +                    mediaManager = (MediaManager)this.manager.lookup( 
MediaManager.ROLE );
  +                    mediaType = mediaManager.getMediaType();
  +                } catch (ServiceException se) {
  +                    throw new ProcessingException("Unable to lookup media 
manager.", se);
  +                } finally {
  +                    this.manager.release( mediaManager );
  +                }
  +                synchronized(context) {
  +                    // add special nodes to the authentication block:
  +                    // useragent, type and media
  +                    Element specialElement;
  +                    Text    specialValue;
  +                    Element authNode;
  +
  +                    authNode = (Element)doc.getFirstChild();
  +
  +                    specialElement = doc.createElementNS(null, "type");
  +                    specialValue = 
doc.createTextNode("cocoon.authentication");
  +                    specialElement.appendChild(specialValue);
  +                    authNode.appendChild(specialElement);
  +
  +                    specialElement = doc.createElementNS(null, "media");
  +                    specialValue = doc.createTextNode(mediaType);
  +                    specialElement.appendChild(specialValue);
  +                    authNode.appendChild(specialElement);
  +
  +                    // store the authentication data in the context
  +                    context.setNode("/" + configuration.getName(), doc);
  +
  +                    // And now load applications
  +                    boolean loaded = true;
  +                    Iterator applications = 
configuration.getApplications().values().iterator();
  +
  +                    while ( applications.hasNext() ) {
  +                        ApplicationConfiguration appHandler = 
(ApplicationConfiguration)applications.next();
  +                        if ( !appHandler.getLoadOnDemand() ) {
  +                            // FIXME - loadApplication
  +                            
//this.loadApplicationXML((SessionContextImpl)this.getSessionManager().getContext(AuthenticationConstants.SESSION_CONTEXT_NAME),
  +                            //                        appHandler, "/");
  +                        } else {
  +                            loaded = false;
  +                        }
  +                    }
  +                    handler.setApplicationsLoaded( loaded );
  +
  +                } // end sync
  +            }
  +        }
  +        
  +        if ( !isValid ) {
  +            if (this.getLogger().isInfoEnabled() ) {
  +                this.getLogger().info("Authenticator: Failed authentication 
using handler '" +  configuration.getName()+"'");
  +            }
  +            // get the /authentication/data Node if available
  +            Node data = null;
  +
  +            if (doc != null) {
  +                data = DOMUtil.getFirstNodeFromPath(doc, new String[] 
{"authentication","data"}, false);
  +            }
  +
  +            // now create the following xml:
  +            // <failed/>
  +            // if data is available data is included, otherwise:
  +            // <data>No information</data>
  +            // If exception message contains info, it is included into failed
  +            DocumentFragment authenticationFragment = 
doc.createDocumentFragment();
  +
  +            Element element = doc.createElementNS(null, "failed");
  +            authenticationFragment.appendChild(element);
  +
  +            if (exceptionMsg != null) {
  +                Text text = doc.createTextNode(exceptionMsg);
  +                element.appendChild(text);
  +            }
  +
  +            if (data == null) {
  +                element = doc.createElementNS(null, "data");
  +                authenticationFragment.appendChild(element);
  +                Text text = doc.createTextNode("No information");
  +                element.appendChild(text);
  +            } else {
  +                authenticationFragment.appendChild(doc.importNode(data, 
true));
  +            }
  +            
  +            // now set this information in the temporary context
  +            SessionManager sessionManager = null;
  +            try {
  +                sessionManager = (SessionManager) this.manager.lookup( 
SessionManager.ROLE );
  +                SessionContext temp = sessionManager.getContext( 
SessionConstants.TEMPORARY_CONTEXT );
  +                temp.appendXML("/", authenticationFragment);
  +            } catch ( ServiceException se ) {
  +                throw new ProcessingException("Unable to lookup session 
manager.", se);
  +            } finally {
  +                this.manager.release( sessionManager );
  +            }
  +        }
  +            
  +        if (this.getLogger().isDebugEnabled() ) {
  +            this.getLogger().debug("end authenticator");
  +        }
  +
  +        return handler;
  +    }
  +    
  +    
  +     /* (non-Javadoc)
  +      * @see 
org.apache.avalon.framework.service.Serviceable#service(org.apache.avalon.framework.service.ServiceManager)
  +      */
  +     public void service(ServiceManager manager) throws ServiceException {
  +             this.manager = manager;
  +        this.resolver = (SourceResolver) 
this.manager.lookup(SourceResolver.ROLE);
  +     }
  +
  +     /* (non-Javadoc)
  +      * @see org.apache.avalon.framework.activity.Disposable#dispose()
  +      */
  +     public void dispose() {
  +             if ( this.manager != null ){
  +            this.manager.release( this.resolver );
  +            this.manager = null;
  +            this.resolver = null;
  +             }
  +     }
   
   }
  
  
  
  1.2       +4 -3      
cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/AuthenticationConstants.java
  
  Index: AuthenticationConstants.java
  ===================================================================
  RCS file: 
/home/cvs/cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/AuthenticationConstants.java,v
  retrieving revision 1.1
  retrieving revision 1.2
  diff -u -r1.1 -r1.2
  --- AuthenticationConstants.java      9 Mar 2003 00:02:15 -0000       1.1
  +++ AuthenticationConstants.java      27 Apr 2003 12:52:53 -0000      1.2
  @@ -70,9 +70,10 @@
       
       /** Logout mode: session is terminated if not used anymore (by the 
        * session or the authentication framework */
  -    int LOGOUT_MODE_IF_UNUSED= 1;
  +    int LOGOUT_MODE_IF_UNUSED = 1;
   
  -    /** Logout mode: session is terminated immediately */
  +    /** Logout mode: session is terminated if the user is not authenticated
  +     * to any handler anymore. */
       int LOGOUT_MODE_IF_NOT_AUTHENTICATED = 2;
   }
   
  
  
  
  1.1                  
cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/configuration/ApplicationConfiguration.java
  
  Index: ApplicationConfiguration.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, 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 Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", 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 (INCLU-
   DING, 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 and was  originally created by
   Stefano Mazzocchi  <[EMAIL PROTECTED]>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.webapps.authentication.configuration;
  
  import java.io.IOException;
  import java.util.HashMap;
  import java.util.Map;
  
  import org.apache.avalon.framework.configuration.Configuration;
  import org.apache.avalon.framework.configuration.ConfigurationException;
  import org.apache.cocoon.ProcessingException;
  import org.apache.excalibur.source.SourceParameters;
  import org.apache.excalibur.source.SourceResolver;
  import org.xml.sax.SAXException;
  
  /**
   * This object stores information about an application configuration
   * inside a handler configuration.
   *
   * @author <a href="mailto:[EMAIL PROTECTED]">Carsten Ziegeler</a>
   * @version CVS $Id: ApplicationConfiguration.java,v 1.1 2003/04/27 12:52:53 
cziegeler Exp $
  */
  public final class ApplicationConfiguration
  implements java.io.Serializable {
  
      /** The unique name of the handler */
      private String name;
  
      /** The load resource (optional) */
      private String loadResource;
  
      /** The save resource (optional) */
      private String saveResource;
  
      /** The load resource parameters (optional) */
      private SourceParameters loadResourceParameters;
  
      /** The save resource parameters (optional) */
      private SourceParameters saveResourceParameters;
  
      /** Is the application loaded on demand */
      private boolean loadOnDemand = false;
  
      /** The corresponding handler */
      private HandlerConfiguration handler;
  
      /** The configuration fragments */
      private Map configurations;
  
      /**
       * Construct a new application handler
       */
      public ApplicationConfiguration(HandlerConfiguration handler, String name)
      throws ProcessingException {
          this.handler = handler;
          this.name = name;
          if (name.indexOf('_') != -1
              || name.indexOf(':') != -1
              || name.indexOf('/') != -1) {
             throw new ProcessingException("application name must not contain 
one of the characters ':','_' or '/'.");
          }
          this.configurations = new HashMap(3, 2);
      }
  
      /**
       * Configure an application
       */
      public void configure(SourceResolver resolver, Configuration appconf)
      throws ProcessingException, SAXException, IOException, 
ConfigurationException {
          Configuration child = null;
  
          // test for loadondemand attribute
          this.loadOnDemand = appconf.getAttributeAsBoolean("loadondemand", 
false);
  
          // get load resource (optinal)
          child = appconf.getChild("load", false);
          if (child != null) {
              this.loadResource = child.getAttribute("uri");
              this.loadResourceParameters = SourceParameters.create(child);
          }
  
          // get save resource (optional)
          child =  appconf.getChild("save", false);
          if (child != null) {
              this.saveResource = child.getAttribute("uri");
              this.saveResourceParameters = SourceParameters.create(child);
          }
  
          // get configurations (optional)
          Configuration[] configurations = appconf.getChildren("configuration");
          if (configurations != null) {
              for(int i = 0; i < configurations.length; i++) {
                  child = configurations[i];
                  String value = child.getAttribute("name");
                  if (this.getConfiguration(value) != null) {
                      throw new ConfigurationException("Configuration names 
must be unique for application " + this.name + ": " + value);
                  }
                  this.configurations.put(value, child);
              }
          }
      }
  
      /**
       * Get the application name.
       */
      public String getName() { return name; }
  
      /**
       * Get the handler
       */
      public HandlerConfiguration getHandler() { return handler; }
  
      /**
       * Get the load resource
       */
      public String getLoadResource() {
          return this.loadResource;
      }
  
      /**
       * Get the save resource
       */
      public String getSaveResource() {
          return this.saveResource;
      }
  
      /**
       * Get the load resource parameters
       */
      public SourceParameters getLoadResourceParameters() {
          return this.loadResourceParameters;
      }
  
      /**
       * Get the save resource parameters
       */
      public SourceParameters getSaveResourceParameters() {
          return this.saveResourceParameters;
      }
  
      public boolean getLoadOnDemand() { return loadOnDemand; }
  
      /**
       * Get the configuration
       */
      public Configuration getConfiguration(String name) {
          return (Configuration)this.configurations.get(name);
      }
  
  }
  
  
  
  1.1                  
cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/configuration/HandlerConfiguration.java
  
  Index: HandlerConfiguration.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, 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 Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", 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 (INCLU-
   DING, 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 and was  originally created by
   Stefano Mazzocchi  <[EMAIL PROTECTED]>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.webapps.authentication.configuration;
  
  import java.io.IOException;
  import java.util.HashMap;
  import java.util.Hashtable;
  import java.util.Map;
  
  import org.apache.avalon.framework.configuration.Configuration;
  import org.apache.avalon.framework.configuration.ConfigurationException;
  import org.apache.cocoon.ProcessingException;
  import org.apache.cocoon.environment.Request;
  import org.apache.excalibur.source.SourceParameters;
  import org.apache.excalibur.source.SourceResolver;
  import org.xml.sax.SAXException;
  
  /**
   * The authentication Handler.
   *
   * @author <a href="mailto:[EMAIL PROTECTED]">Carsten Ziegeler</a>
   * @version CVS $Id: HandlerConfiguration.java,v 1.1 2003/04/27 12:52:53 
cziegeler Exp $
  */
  public final class HandlerConfiguration
  implements java.io.Serializable {
  
      /** The unique name of the handler */
      private final String name;
  
      /** The redirect-to URI */
      private String redirectURI;
  
      /** The redirect parameters */
      private SourceParameters redirectParameters;
  
      /** The authentication resource */
      private String authenticationResource;
  
      /** The authentication resource parameters */
      private SourceParameters authenticationResourceParameters;
  
      /** The load resource (optional) */
      private String loadResource;
  
      /** The load resource (optional) parameters */
      private SourceParameters loadResourceParameters;
  
      /** The save resource (optional) */
      private String saveResource;
  
      /** The save resource (optional) parameters */
      private SourceParameters saveResourceParameters;
  
      /** The Application Configurations */
      private Map applications = new Hashtable(3, 2);
  
      /** The configuration fragments */
      private Map configurations;
  
      /**
       * Create a new handler object.
       */
      public HandlerConfiguration(String name) {
          this.name = name;
          this.configurations = new HashMap(3, 2);
      }
  
      /**
       * Configure
       */
      public void configure(SourceResolver resolver,
                            Request        request,
                            Configuration  conf)
      throws ProcessingException, SAXException, IOException, 
ConfigurationException {
          // get login (required)
          Configuration child = conf.getChild("redirect-to", false);
          if (child == null)
              throw new ConfigurationException("Handler '"+this.name+"' needs a 
redirect-to URI.");
          this.redirectURI = child.getAttribute("uri");
          if ( this.redirectURI.startsWith("cocoon:") ) {
              final int pos = this.redirectURI.indexOf('/');
              if ( pos != -1 && this.redirectURI.length() > pos) {
                  if (this.redirectURI.charAt(pos+1) == '/') {
                      this.redirectURI = 
this.redirectURI.substring(pos+2).trim();
                      this.redirectURI = 
request.getContextPath()+"/"+this.redirectURI;
                  } else {
                      this.redirectURI = 
this.redirectURI.substring(pos+1).trim();
                  }
              }
          }
  
          this.redirectParameters = SourceParameters.create(child);
  
          // get load resource (required)
          child = conf.getChild("authentication", false);
          if (child == null)
              throw new ConfigurationException("Handler '"+this.name+"' needs 
authentication configuration");
          this.authenticationResource = child.getAttribute("uri");
          this.authenticationResourceParameters = 
SourceParameters.create(child);
  
          // get load resource (optional)
          child = conf.getChild("load", false);
          if (child != null) {
              this.loadResource = child.getAttribute("uri");
              this.loadResourceParameters = SourceParameters.create(child);
          }
  
          // get save resource (optional)
          child = conf.getChild("save", false);
          if (child != null) {
              this.saveResource = child.getAttribute("uri");
              this.saveResourceParameters = SourceParameters.create(child);
          }
  
          // And now: Applications
          child = conf.getChild("applications", false);
          if (child != null) {
              Configuration[] appConfs = child.getChildren("application");
              Configuration appconf;
  
              if (appConfs != null) {
                  for(int i = 0; i < appConfs.length; i++) {
                      appconf = appConfs[i];
  
                      // get name
                      String appName = appconf.getAttribute("name");
  
                      // test if handler is unique
                      if (this.applications.get(appName) != null) {
                          throw new ConfigurationException("Application names 
must be unique: " + appName);
                      }
  
                      // create handler
                      ApplicationConfiguration apphandler = new 
ApplicationConfiguration(this, appName);
  
                      // store handler
                      this.applications.put(appName, apphandler);
  
                      // configure
                      apphandler.configure(resolver, appconf);
                  }
              }
          }
  
          // get configurations (optional)
          Configuration[] configurations = conf.getChildren("configuration");
          if (configurations != null) {
              for(int i = 0; i < configurations.length; i++) {
                  child = configurations[i];
                  String value = child.getAttribute("name");
                  if (this.getConfiguration(value) != null) {
                      throw new ConfigurationException("Configuration names 
must be unique for application " + this.name + ": " + value);
                  }
                  this.configurations.put(value, child);
              }
          }
  
      }
  
  
      /**
       * Get the handler name.
       */
      public String getName() { return name; }
  
      /**
       * Get the redirect URI
       */
      public String getRedirectURI() {
          return this.redirectURI;
      }
  
      /**
       * Get the redirect parameters
       */
      public SourceParameters getRedirectParameters() {
          return this.redirectParameters;
      }
  
      /**
       * Get the authentication resource
       */
      public String getAuthenticationResource() {
          return this.authenticationResource;
      }
  
      /**
       * Get the authentication resource
       */
      public SourceParameters getAuthenticationResourceParameters() {
          return this.authenticationResourceParameters;
      }
  
      /** Get the save resource */
      public String getSaveResource() { return this.saveResource; }
  
      /** Get the load resource */
      public String getLoadResource() { return this.loadResource; }
  
      /** Get the save resource */
      public SourceParameters getSaveResourceParameters() { return 
this.saveResourceParameters; }
  
      /** Get the load resource parameters */
      public SourceParameters getLoadResourceParameters() { return 
this.loadResourceParameters; }
  
      /**
       * Get the applications map
       */
      public Map getApplications() { return applications; }
  
      /**
       * Get the configuration
       */
      public Configuration getConfiguration(String name) {
          return (Configuration)this.configurations.get(name);
      }
  
      /**
       * toString()
       */
      public String toString() {
          return "authentication-Handler " + this.name;
      }
  }
  
  
  
  1.1                  
cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/context/AuthenticationContextProvider.java
  
  Index: AuthenticationContextProvider.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, 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 Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", 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 (INCLU-
   DING, 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 and was  originally created by
   Stefano Mazzocchi  <[EMAIL PROTECTED]>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.webapps.authentication.context;
  
  import java.util.Map;
  
  import org.apache.avalon.framework.component.ComponentManager;
  import org.apache.cocoon.ProcessingException;
  import org.apache.cocoon.webapps.authentication.user.RequestState;
  import org.apache.cocoon.webapps.authentication.user.UserHandler;
  import org.apache.cocoon.webapps.session.context.SessionContext;
  import org.apache.cocoon.webapps.session.context.SessionContextProvider;
  import org.apache.excalibur.source.SourceResolver;
  
  
  /**
   *  Context provider for the authentication context
   *
   * @author <a href="mailto:[EMAIL PROTECTED]">Carsten Ziegeler</a>
   * @version CVS $Id: AuthenticationContextProvider.java,v 1.1 2003/04/27 
12:52:53 cziegeler Exp $
  */
  public final class AuthenticationContextProvider
  implements SessionContextProvider {
  
      /**
       * Get the context
       * @param name The name of the context
       * @param objectModel The objectModel of the current request.
       * @param resolver    The source resolver
       * @param componentManager manager
       * @return The context
       * @throws ProcessingException If the context is not available.
       */
      public SessionContext getSessionContext(String           name,
                                              Map              objectModel,
                                              SourceResolver   resolver,
                                              ComponentManager manager)
      throws ProcessingException {
          SessionContext context = null;
          if 
(name.equals(org.apache.cocoon.webapps.authentication.AuthenticationConstants.SESSION_CONTEXT_NAME)
 ) {
              RequestState state = RequestState.getState();
              if ( null != state ) {
                  UserHandler handler = state.getHandler();
                  if ( handler != null ) {
                      context = handler.getContext();
                  }
              }
          }
          return context;
      }
  
  }
  
  
  
  1.1                  
cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/context/AuthenticationContext.java
  
  Index: AuthenticationContext.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, 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 Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", 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 (INCLU-
   DING, 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 and was  originally created by
   Stefano Mazzocchi  <[EMAIL PROTECTED]>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.webapps.authentication.context;
  
  import org.apache.avalon.framework.component.ComponentException;
  import org.apache.avalon.framework.component.ComponentManager;
  import org.apache.cocoon.ProcessingException;
  import org.apache.cocoon.components.source.SourceUtil;
  import org.apache.cocoon.webapps.authentication.components.ApplicationHandler;
  import 
org.apache.cocoon.webapps.authentication.components.AuthenticationManager;
  import org.apache.cocoon.webapps.authentication.components.Handler;
  import org.apache.cocoon.webapps.session.context.SessionContext;
  import org.apache.cocoon.xml.dom.DOMUtil;
  import org.apache.excalibur.source.SourceParameters;
  import org.apache.excalibur.source.SourceResolver;
  import org.w3c.dom.DocumentFragment;
  import org.w3c.dom.Node;
  import org.w3c.dom.NodeList;
  import org.xml.sax.ContentHandler;
  import org.xml.sax.SAXException;
  import org.xml.sax.ext.LexicalHandler;
  import org.xml.sax.helpers.AttributesImpl;
  
  import java.io.IOException;
  import java.util.Map;
  
  /**
   * This is the implementation for the authentication context
   * @author <a href="mailto:[EMAIL PROTECTED]">Carsten Ziegeler</a>
   * @version CVS $Id: AuthenticationContext.java,v 1.1 2003/04/27 12:52:53 
cziegeler Exp $
  */
  public final class AuthenticationContext
  implements SessionContext {
  
      private String          name;
      private SessionContext  authContext;
      private String          loadResource;
      private String          saveResource;
      private String          authLoadResource;
      private String          authSaveResource;
      private SourceParameters loadResourceParameters;
      private SourceParameters saveResourceParameters;
      private SourceParameters authLoadResourceParameters;
      private SourceParameters authSaveResourceParameters;
      private String          handlerName;
      private String          applicationName;
  
      public AuthenticationContext(SessionContext context,
                                String         contextName,
                                String          handlerName,
                                String          applicationName,
                                SourceResolver  resolver,
                                ComponentManager manager)
      throws ProcessingException {
          AuthenticationManager authManager = null;
          try {
              authManager = 
(AuthenticationManager)manager.lookup(AuthenticationManager.ROLE);
              Handler handler = authManager.getHandler();
              this.name = contextName;
              this.authContext = context;
              this.handlerName = handlerName;
              this.applicationName = applicationName;
              this.authLoadResource = handler.getLoadResource();
              this.authSaveResource = handler.getSaveResource();
              this.authLoadResourceParameters = 
handler.getLoadResourceParameters();
              this.authSaveResourceParameters = 
handler.getSaveResourceParameters();
              if (this.applicationName != null) {
                  ApplicationHandler appHandler = 
(ApplicationHandler)handler.getApplications().get(this.applicationName);
                  this.loadResource = appHandler.getLoadResource();
                  this.saveResource = appHandler.getSaveResource();
                  this.loadResourceParameters = 
appHandler.getLoadResourceParameters();
                  this.saveResourceParameters = 
appHandler.getSaveResourceParameters();
              }
  
          } catch (ComponentException ce) {
              throw new ProcessingException("Unable to lookup the resource 
connector.", ce);
          } finally {
              manager.release(authManager);
          }
      }
  
      /** Set the name of the context.
       *  This method must be invoked in the init phase.
       *  In addition a load and a save resource can be provided.
       */
      public void setup(String value, String load, String save) {
      }
  
      /**
       * Get the name of the context
       */
      public String getName() {
          return this.name;
      }
  
      /**
       *  Get a document fragment.
       *  If the node specified by the path exist, its content is returned
       *  as a DocumentFragment.
       *  If the node does not exists, <CODE>null</CODE> is returned.
       */
      public DocumentFragment getXML(String path)
      throws ProcessingException {
          if (path == null) {
              throw new ProcessingException("getXML: Path is required");
          }
          if (path.startsWith("/") == false) path = '/' + path;
  
          DocumentFragment frag = null;
  
          if (path.equals("/") == true) {
              // get all: first authentication then application
              frag = this.authContext.getXML("/" + this.handlerName + 
"/authentication");
  
              if (frag != null) {
                  // now add root node authentication
                  Node root = frag.getOwnerDocument().createElementNS(null, 
"authentication");
                  Node child;
                  while (frag.hasChildNodes() == true) {
                      child = frag.getFirstChild();
                      frag.removeChild(child);
                      root.appendChild(child);
                  }
                  frag.appendChild(root);
              }
  
              if (this.applicationName != null) {
                  // join
                  DocumentFragment appFrag = this.authContext.getXML("/" + 
this.handlerName + "/applications/" + this.applicationName);
                  if (appFrag != null) {
                      // now add root node application
                      Node root = 
appFrag.getOwnerDocument().createElementNS(null, "application");
                      Node child;
                      while (appFrag.hasChildNodes() == true) {
                          child = appFrag.getFirstChild();
                          appFrag.removeChild(child);
                          root.appendChild(child);
                      }
                      appFrag.appendChild(root);
  
                      if (frag == null) {
                          frag = appFrag;
                      } else {
                          while (appFrag.hasChildNodes() == true) {
                              child = appFrag.getFirstChild();
                              appFrag.removeChild(child);
                              child = frag.getOwnerDocument().importNode(child, 
true);
                              frag.appendChild(child);
                          }
                      }
                  }
              }
  
          } else if (path.startsWith("/authentication") == true) {
              frag = this.authContext.getXML("/" + this.handlerName + path);
  
          } else if (path.equals("/application") == true || 
path.startsWith("/application/") == true) {
              if (this.applicationName != null) {
                  String appPath;
                  if (path.equals("/application") == true) {
                      appPath ="/";
                  } else {
                      appPath = path.substring("/application".length());
                  }
                  frag = this.authContext.getXML("/" + this.handlerName + 
"/applications/" + this.applicationName + appPath);
              }
          } else {
              frag = this.authContext.getXML("/" + this.handlerName + path);
          }
  
          return frag;
      }
  
      /**
       * Convert the authentication XML of a handler to parameters.
       * The XML is flat and consists of elements which all have exactly one 
text node:
       * <parone>value_one<parone>
       * <partwo>value_two<partwo>
       * A parameter can occur more than once with different values.
       */
      public void addParametersFromAuthenticationXML(String handlerName,
                                                     String path,
                                                     SourceParameters 
parameters)
      throws ProcessingException {
          final DocumentFragment fragment = this.authContext.getXML("/" + 
handlerName + "/authentication" + path);
          if (fragment != null) {
              NodeList   childs = fragment.getChildNodes();
              if (childs != null) {
                  Node current;
                  for(int i = 0; i < childs.getLength(); i++) {
                      current = childs.item(i);
  
                      // only element nodes
                      if (current.getNodeType() == Node.ELEMENT_NODE) {
                          current.normalize();
                          NodeList valueChilds = current.getChildNodes();
                          String   key;
                          StringBuffer   valueBuffer;
                          String         value;
  
                          key = current.getNodeName();
                          valueBuffer = new StringBuffer();
                          for(int m = 0; m < valueChilds.getLength(); m++) {
                              current = valueChilds.item(m); // attention: 
current is reused here!
                              if (current.getNodeType() == Node.TEXT_NODE) { // 
only text nodes
                                  if (valueBuffer.length() > 0) 
valueBuffer.append(' ');
                                  valueBuffer.append(current.getNodeValue());
                              }
                          }
                          value = valueBuffer.toString().trim();
                          if (key != null && value != null && value.length() > 
0) {
                              parameters.setParameter(key, value);
                          }
                      }
                  }
              }
          }
      }
  
      /**
       *  Set a document fragment at the given path.
       *  The implementation of this method is context specific.
       *  Usually all children of the node specified by the path are removed
       *  and the children of the fragment are inserted as new children.
       *  If the path is not existent it is created.
       */
      public void setXML(String path, DocumentFragment fragment)
      throws ProcessingException {
          if (path == null) {
              throw new ProcessingException("setXML: Path is required");
          }
          if (path.startsWith("/") == false) path = '/' + path;
  
          if ( path.equals("/") ) {
              // set all is not allowed with "/"
              throw new ProcessingException("Path '/' is not allowed");
  
          } else if ( path.startsWith("/authentication") ) {
  
              this.cleanParametersCache();
              this.authContext.setXML('/' + this.handlerName + path, fragment);
  
          } else if (path.equals("/application") == true
                     || path.startsWith("/application/") == true) {
  
              if (this.applicationName == null) {
                  throw new ProcessingException("Application is required");
              }
              String appPath;
              if (path.equals("/application") == true) {
                  appPath = "/";
              } else {
                  appPath = path.substring("/application".length());
              }
              this.authContext.setXML("/" + this.handlerName + "/applications/" 
+ this.applicationName + appPath, fragment);
  
          } else {
              this.authContext.setXML("/" + this.handlerName + path, fragment);
          }
      }
  
      /**
       * Set the XML for an application
       */
      public void setApplicationXML(String setHandlerName,
                                    String setApplicationName,
                                    String path,
                                    DocumentFragment fragment)
      throws ProcessingException {
          path = "/" + setHandlerName + "/applications/" + setApplicationName + 
path;
          this.authContext.setXML(path, fragment);
      }
  
      /**
       * Append a document fragment at the given path.
       * The implementation of this method is context specific.
       * Usually the children of the fragment are appended as new children of 
the
       * node specified by the path.
       * If the path is not existent it is created and this method should work
       * in the same way as setXML.
       */
      public void appendXML(String path, DocumentFragment fragment)
      throws ProcessingException {
          if (path == null) {
              throw new ProcessingException("appendXML: Path is required");
          }
          if (path.startsWith("/") == false) path = '/' + path;
  
          if ( path.equals("/") ) {
              // set all is not allowed with "/"
              throw new ProcessingException("Path '/' is not allowed");
  
          } else if ( path.startsWith("/authentication") ) {
  
              this.cleanParametersCache();
              this.authContext.appendXML('/' + this.handlerName + path, 
fragment);
  
          } else if (path.equals("/application") == true
                     || path.startsWith("/application/") == true) {
  
              if (this.applicationName == null) {
                  throw new ProcessingException("Application is required");
              }
              String appPath;
              if (path.equals("/application") == true) {
                  appPath = "/";
              } else {
                  appPath = path.substring("/application".length());
              }
              this.authContext.appendXML("/" + this.handlerName + 
"/applications/" + this.applicationName + appPath, fragment);
  
          } else {
              this.authContext.appendXML("/" + this.handlerName + path, 
fragment);
          }
      }
  
      /**
       * Remove some content from the context.
       * The implementation of this method is context specific.
       * Usually this method should remove all children of the node specified
       * by the path.
       */
      public void removeXML(String path)
      throws ProcessingException {
          if (path == null) {
              throw new ProcessingException("removeXML: Path is required");
          }
          if (path.startsWith("/") == false) path = '/' + path;
  
          if (path.equals("/") == true) {
              this.cleanParametersCache();
              this.authContext.removeXML("/" + this.handlerName);
  
          } else if (path.startsWith("/authentication") == true) {
  
              this.cleanParametersCache();
              this.authContext.removeXML("/" + this.handlerName + path);
  
          } else if (path.equals("/application") == true
                     || path.startsWith("/application/") == true) {
              if (this.applicationName == null) {
                  throw new ProcessingException("removeXML: Application is 
required for path " + path);
              }
              String appPath;
              if (path.equals("/application") == true) {
                  appPath = "/";
              } else {
                  appPath = path.substring("/application".length());
              }
              this.authContext.removeXML("/" + this.handlerName + 
"/applications/" + this.applicationName + appPath);
          } else {
              this.authContext.removeXML("/" + this.handlerName + path);
          }
      }
  
      /**
       * Set a context attribute.
       * Attributes over a means to store any data (object) in a session
       * context. If <CODE>value</CODE> is <CODE>null</CODE> the attribute is
       * removed. If already an attribute exists with the same key, the value
       * is overwritten with the new one.
       */
      public void setAttribute(String key, Object value)
      throws ProcessingException {
          this.authContext.setAttribute(key, value);
      }
  
      /**
       * Get the value of a context attribute.
       * If the attribute is not available return <CODE>null</CODE>.
       */
      public Object getAttribute(String key)
      throws ProcessingException {
          return this.authContext.getAttribute(key);
      }
  
      /**
       * Get the value of a context attribute.
       * If the attribute is not available the return the
       * <CODE>defaultObject</CODE>.
       */
      public Object getAttribute(String key, Object defaultObject)
      throws ProcessingException {
          return this.authContext.getAttribute(key, defaultObject);
      }
  
      /**
       * Get a copy of the first node specified by the path.
       * If the node does not exist, <CODE>null</CODE> is returned.
       */
      public Node getSingleNode(String path)
      throws ProcessingException {
          throw new ProcessingException("This method is not supported by the 
authenticaton session context.");
      }
  
      /**
       * Get a copy of all nodes specified by the path.
       */
      public NodeList getNodeList(String path)
      throws ProcessingException {
          throw new ProcessingException("This method is not supported by the 
authenticaton session context.");
      }
  
      /**
       * Set the value of a node. The node is copied before insertion.
       */
      public void setNode(String path, Node node)
      throws ProcessingException {
          throw new ProcessingException("This method is not supported by the 
authenticaton session context.");
      }
  
      /**
       * Get the value of this node.
       * This is similiar to the xsl:value-of function.
       * If the node does not exist, <code>null</code> is returned.
       */
      public String getValueOfNode(String path)
      throws ProcessingException {
          throw new ProcessingException("This method is not supported by the 
authenticaton session context.");
      }
  
      /**
       * Set the value of a node.
       * All children of the node are removed beforehand and one single text
       * node with the given value is appended to the node.
       */
      public void setValueOfNode(String path, String value)
      throws ProcessingException {
          throw new ProcessingException("This method is not supported by the 
authenticaton session context.");
      }
  
      /**
       * Stream the XML directly to the handler.
       * This streams the contents of getXML() to the given handler without
       * creating a DocumentFragment containing a copy of the data.
       * If no data is available (if the path does not exist) 
<code>false</code> is
       * returned, otherwise <code>true</code>.
       */
      public boolean streamXML(String path, ContentHandler contentHandler,
                               LexicalHandler lexicalHandler)
      throws SAXException, ProcessingException {
          if (path == null) {
              throw new ProcessingException("streamXML: Path is required");
          }
          if (path.startsWith("/") == false) path = '/' + path;
  
          if (path.equals("/") == true) {
              // get all: first authentication then application
              contentHandler.startElement(null, "authentication", 
"authentication", new AttributesImpl());
              this.authContext.streamXML('/' + this.handlerName + 
"/authentication", contentHandler, lexicalHandler);
              contentHandler.endElement(null, "authentication", 
"authentication");
  
              if (this.applicationName != null) {
                  contentHandler.startElement(null, "application", 
"application", new AttributesImpl());
                  this.authContext.streamXML('/' + this.handlerName + 
"/applications/" + this.applicationName, contentHandler, lexicalHandler);
                  contentHandler.endElement(null, "application", "application");
              }
              return true;
  
          } else if (path.startsWith("/authentication") == true) {
              return this.authContext.streamXML('/' + this.handlerName + path, 
contentHandler, lexicalHandler);
  
          } else if (path.equals("/application") == true || 
path.startsWith("/application/") == true) {
              if (this.applicationName != null) {
                  String appPath;
                  if (path.equals("/application") == true) {
                      appPath ="/";
                  } else {
                      appPath = path.substring("/application".length());
                  }
                  return this.authContext.streamXML('/' + this.handlerName + 
"/applications/" + this.applicationName + appPath, contentHandler, 
lexicalHandler);
              }
          } else {
              return this.authContext.streamXML('/' + this.handlerName + path, 
contentHandler, lexicalHandler);
          }
          return false;
      }
  
      /**
       * Try to load XML into the context.
       * If the context does not provide the ability of loading,
       * an exception is thrown.
       */
      public void loadXML(String path,
                          SourceParameters parameters,
                          Map                objectModel,
                          SourceResolver     resolver,
                          ComponentManager   manager)
      throws SAXException, ProcessingException, IOException {
          if (path.startsWith("/") == false) path = '/' + path;
  
          if (path.equals("/") == true) {
              // load all: first authentication then application
              this.loadAuthenticationXML("/authentication",
                                         parameters,
                                         objectModel,
                                         resolver,
                                         manager);
              if (this.applicationName != null) {
                  this.loadApplicationXML("/",
                                          parameters,
                                          objectModel,
                                          resolver,
                                          manager);
              }
  
          } else if (path.startsWith("/authentication") == true) {
              this.loadAuthenticationXML(path,
                                         parameters,
                                         objectModel,
                                         resolver,
                                         manager);
  
          } else if (path.equals("/application") == true && 
this.applicationName != null) {
              this.loadApplicationXML("/",
                                      parameters,
                                      objectModel,
                                      resolver,
                                      manager);
          } else if (path.startsWith("/application/") == true && 
this.applicationName != null) {
              this.loadApplicationXML(path.substring(12), // start path with '/'
                                      parameters,
                                      objectModel,
                                      resolver,
                                      manager);
          } else {
              throw new ProcessingException("loadXML: Path is not valid: " + 
path);
          }
      }
  
      /**
       * Try to save XML from the context.
       * If the context does not provide the ability of saving,
       * an exception is thrown.
       */
      public void saveXML(String             path,
                          SourceParameters parameters,
                          Map                objectModel,
                          SourceResolver     resolver,
                          ComponentManager   manager)
      throws SAXException, ProcessingException, IOException {
          if (path.startsWith("/") == false) path = '/' + path;
  
          if (path.equals("/") == true) {
              // save all: first authentication then application
              this.saveAuthenticationXML("/authentication",
                                         parameters,
                                         objectModel,
                                         resolver,
                                         manager);
              if (this.applicationName != null) {
                  this.saveApplicationXML("/",
                                          parameters,
                                          objectModel,
                                          resolver,
                                          manager);
              }
  
          } else if (path.startsWith("/authentication") == true) {
              this.saveAuthenticationXML(path,
                                         parameters,
                                         objectModel,
                                         resolver,
                                         manager);
  
          } else if (path.equals("/application") == true && 
this.applicationName != null) {
              this.saveApplicationXML("/",
                                      parameters,
                                      objectModel,
                                      resolver,
                                      manager);
          } else if (path.startsWith("/application/") == true && 
this.applicationName != null) {
              this.saveApplicationXML(path.substring(12), // start path with '/'
                                      parameters,
                                      objectModel,
                                      resolver,
                                      manager);
          } else {
              throw new ProcessingException("saveXML: Path is not valid: " + 
path);
          }
      }
  
      /**
       * Clean the parameters cache
       */
      private void cleanParametersCache()
      throws ProcessingException {
          this.authContext.setAttribute("cachedparameters_" + this.handlerName, 
null);
          this.authContext.setAttribute("cachedmap_" + this.handlerName, null);
      }
  
      /**
       * Clean the parameters cache
       */
      public void cleanParametersCache(String handlerName)
      throws ProcessingException {
          this.authContext.setAttribute("cachedparameters_" + handlerName, 
null);
          this.authContext.setAttribute("cachedmap_" + handlerName, null);
      }
  
      /**
       * Save Authentication
       */
      private void saveAuthenticationXML(String             path,
                                         SourceParameters parameters,
                                         Map                objectModel,
                                         SourceResolver     resolver,
                                         ComponentManager   manager)
      throws ProcessingException {
          if (this.authSaveResource == null) {
              throw new ProcessingException("The context " + this.name + " does 
not support saving.");
          }
  
          synchronized(this.authContext) {
              DocumentFragment fragment = this.getXML(path);
              if (fragment == null) {
                  // create empty fake fragment
                  fragment = DOMUtil.createDocument().createDocumentFragment();
              }
              if (parameters != null) {
                  parameters = (SourceParameters)parameters.clone();
                  parameters.add(this.authSaveResourceParameters);
              } else if (this.authSaveResourceParameters != null) {
                  parameters = 
(SourceParameters)this.authSaveResourceParameters.clone();
              }
              parameters = this.createParameters(parameters,
                                                 this.handlerName,
                                                 path,
                                                 null);
              SourceUtil.writeDOM(this.authSaveResource,
                                  null,
                                  parameters,
                                  fragment,
                                  resolver,
                                  "xml");
          } // end synchronized
      }
  
      /**
       * Save Authentication
       */
      private void loadAuthenticationXML(String             path,
                                         SourceParameters parameters,
                                         Map                objectModel,
                                         SourceResolver     resolver,
                                         ComponentManager   manager)
      throws ProcessingException {
          if (this.authLoadResource == null) {
              throw new ProcessingException("The context " + this.name + " does 
not support loading.");
          }
  
          synchronized(this.authContext) {
  
              if (parameters != null) {
                  parameters = (SourceParameters)parameters.clone();
                  parameters.add(this.authLoadResourceParameters);
              } else if (this.authLoadResourceParameters != null) {
                  parameters = 
(SourceParameters)this.authLoadResourceParameters.clone();
              }
              parameters = this.createParameters(parameters,
                                                 this.handlerName,
                                                 path,
                                                 null);
              DocumentFragment frag;
              
              frag = SourceUtil.readDOM(this.authLoadResource, 
                                        null, 
                                        parameters, 
                                        resolver);
              
              this.setXML(path, frag);
  
          } // end synchronized
      }
  
      /**
       * Load XML of an application
       */
      private void loadApplicationXML(String             path,
                                      SourceParameters parameters,
                                      Map                objectModel,
                                      SourceResolver     resolver,
                                      ComponentManager   manager)
      throws ProcessingException {
          if (this.loadResource == null) {
              throw new ProcessingException("The context " + this.name + " does 
not support loading.");
          }
          // synchronized
          synchronized (this.authContext) {
  
              if (parameters != null) {
                  parameters = (SourceParameters)parameters.clone();
                  parameters.add(this.loadResourceParameters);
              } else if (this.loadResourceParameters != null) {
                  parameters = 
(SourceParameters)this.loadResourceParameters.clone();
              }
              parameters = this.createParameters(parameters,
                                                 this.handlerName,
                                                 path,
                                                 this.applicationName);
              DocumentFragment fragment;
              fragment = SourceUtil.readDOM(this.loadResource, 
                                            null, 
                                            parameters, 
                                            resolver);
              this.setXML(path, fragment);
  
          } // end synchronized
  
      }
  
      /**
       * Save XML of an application
       */
      private void saveApplicationXML(String path,
                                      SourceParameters parameters,
                                      Map                objectModel,
                                      SourceResolver     resolver,
                                      ComponentManager   manager)
      throws ProcessingException {
          if (this.saveResource == null) {
              throw new ProcessingException("The context " + this.name + " does 
not support saving.");
          }
          // synchronized
          synchronized (this.authContext) {
  
              if (parameters != null) {
                  parameters = (SourceParameters)parameters.clone();
                  parameters.add(this.saveResourceParameters);
              } else if (this.saveResourceParameters != null) {
                  parameters = 
(SourceParameters)this.saveResourceParameters.clone();
              }
              parameters = this.createParameters(parameters,
                                                 this.handlerName,
                                                 path,
                                                 this.applicationName);
              DocumentFragment fragment = this.getXML("/application" + path);
              if (fragment == null) {
                  // create empty fake fragment
                  fragment = DOMUtil.createDocument().createDocumentFragment();
              }
  
              SourceUtil.writeDOM(this.saveResource,
                                  null,
                                  parameters,
                                  fragment,
                                  resolver,
                                  "xml");
  
          } // end synchronized
  
      }
  
      /**
       * Build parameters for loading and saving of application data
       */
      public SourceParameters createParameters(SourceParameters parameters,
                                                 String             myHandler,
                                                 String             path,
                                                 String             appName)
      throws ProcessingException {
          if (parameters == null) parameters = new SourceParameters();
  
          // add all elements from inside the handler data
          this.addParametersFromAuthenticationXML(myHandler,
                                                  "/data",
                                                  parameters);
  
          // add all top level elements from authentication
          this.addParametersFromAuthenticationXML(myHandler,
                                                  "",
                                                  parameters);
  
          // add application and path
          parameters.setSingleParameterValue("handler", myHandler);
          if (appName != null) 
parameters.setSingleParameterValue("application", appName);
          if (path != null) parameters.setSingleParameterValue("path", path);
  
          return parameters;
      }
  
  }
  
  
  

Reply via email to