cziegeler 02/04/17 03:04:53
Modified: src/java/org/apache/cocoon/webapps/session/context
SessionContextProvider.java
Added: src/java/org/apache/cocoon/webapps/authentication
AuthenticationConstants.java
src/java/org/apache/cocoon/webapps/authentication/acting
AuthAction.java LoggedInAction.java
LoginAction.java LogoutAction.java
src/java/org/apache/cocoon/webapps/authentication/components
ApplicationHandler.java AuthenticationManager.java
Handler.java
src/java/org/apache/cocoon/webapps/authentication/context
SessionContextImpl.java
SessionContextProviderImpl.java
src/java/org/apache/cocoon/webapps/authentication/generation
ConfigurationGenerator.java
src/java/org/apache/cocoon/webapps/authentication/selection
MediaSelector.java
Log:
Next step: adding authentication (aka sunRise)
Revision Changes Path
1.1
xml-cocoon2/src/java/org/apache/cocoon/webapps/authentication/AuthenticationConstants.java
Index: AuthenticationConstants.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2002 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;
/**
* The <code>Constants</code> used throughout the core of the authentication
* framework.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Carsten Ziegeler</a>
* @version CVS $Id: AuthenticationConstants.java,v 1.1 2002/04/17 10:04:52
cziegeler Exp $
*/
public interface AuthenticationConstants {
String REQUEST_ATTRIBUTE_HANDLER_NAME =
"org.apache.cocoon.webapps.authentication.HandlerName";
String REQUEST_ATTRIBUTE_APPLICATION_NAME =
"org.apache.cocoon.webapps.authentication.ApplicationName";
String REQUEST_ATTRIBUTE_MEDIA_TYPE =
"org.apache.cocoon.webapps.authentication.MediaType";
/** The name of the session attribute storing the context */
String SESSION_ATTRIBUTE_CONTEXT_NAME =
"org.apache.cocoon.webapps.authentication.SessionContext";
/** The name of the session attribute storing the handler configuration */
String SESSION_ATTRIBUTE_HANDLERS =
"org.apache.cocoon.webapps.authentication.Handlers";
/** The name of the authentication context. */
String SESSION_CONTEXT_NAME = "authentication";
/**
* The name of the request attribute containing error information for
* a failed login to a handler. The real name of the attribute is
* obtained by adding the handler name.
* The value of the attribute is a document fragment.
*/
String REQUEST_ATTRIBUTE_FAILED_LOGIN =
"org.apache.cocoon.webapps.authentication.LoginFailedFor";
}
1.1
xml-cocoon2/src/java/org/apache/cocoon/webapps/authentication/acting/AuthAction.java
Index: AuthAction.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2002 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.acting;
import java.util.Map;
import java.util.HashMap;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.avalon.framework.thread.ThreadSafe;
import org.apache.cocoon.acting.ComposerAction;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.webapps.session.components.SessionManager;
import org.apache.cocoon.webapps.authentication.AuthenticationConstants;
import
org.apache.cocoon.webapps.authentication.components.AuthenticationManager;
/**
* This is the authentication action
* This action contains the complete configuration for the authentication
* Manager. During configuration the AuthenticationManager class gets this
* configuration to configure the instances properly.
* The main task of this action is to check if the user is authenticated
* using a handler. If not a redirect takes place.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Carsten Ziegeler</a>
* @version CVS $Id: AuthAction.java,v 1.1 2002/04/17 10:04:52 cziegeler Exp $
*/
public final class AuthAction
extends ComposerAction
implements ThreadSafe, Configurable {
public Map act(Redirector redirector,
SourceResolver resolver,
Map objectModel,
String source,
Parameters par)
throws Exception {
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("BEGIN act resolver="+resolver+
", objectModel="+objectModel+
", source="+source+
", par="+par);
}
String handlerName = null;
String applicationName = null;
AuthenticationManager authManager = null;
Map map = null;
boolean initialized;
try {
final Request request = ObjectModelHelper.getRequest( objectModel
);
// Are we called as an internal resource?
if ( objectModel.get("Internal-Request") != null ) {
handlerName =
(String)request.getAttribute(AuthenticationConstants.REQUEST_ATTRIBUTE_HANDLER_NAME);
applicationName =
(String)request.getAttribute(AuthenticationConstants.REQUEST_ATTRIBUTE_APPLICATION_NAME);
initialized = true;
} else {
handlerName = par.getParameter("handler", null);
applicationName = par.getParameter("application", null);
if (handlerName != null)
request.setAttribute(AuthenticationConstants.REQUEST_ATTRIBUTE_HANDLER_NAME,
handlerName);
if (applicationName != null)
request.setAttribute(AuthenticationConstants.REQUEST_ATTRIBUTE_APPLICATION_NAME,
applicationName);
initialized = false;
}
authManager = (AuthenticationManager) this.manager.lookup(
AuthenticationManager.ROLE );
// do authentication
if (authManager.checkAuthentication(redirector, !initialized) ==
false) {
// All events are ignored
// the sitemap.xsl ensures that only the redirect is processed
} else {
if (initialized == false) {
map = authManager.createMap();
} else {
map = new HashMap();
}
}
} finally {
this.manager.release( authManager );
}
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("END act map="+map);
}
return map;
}
public void configure(Configuration configuration)
throws ConfigurationException {
// pass the configuration on to the authManager component
AuthenticationManager.setConfiguration(configuration);
}
}
1.1
xml-cocoon2/src/java/org/apache/cocoon/webapps/authentication/acting/LoggedInAction.java
Index: LoggedInAction.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2002 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.acting;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.avalon.framework.activity.Disposable;
import org.apache.avalon.framework.component.Component;
import org.apache.avalon.framework.component.ComponentManager;
import org.apache.avalon.framework.component.ComponentException;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.avalon.framework.thread.ThreadSafe;
import org.apache.cocoon.acting.ComposerAction;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.SourceResolver;
import
org.apache.cocoon.webapps.authentication.components.AuthenticationManager;
/**
* This action tests if the user is logged in for a given handler.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Carsten Ziegeler</a>
* @version CVS $Id: LoggedInAction.java,v 1.1 2002/04/17 10:04:52 cziegeler
Exp $
*/
public final class LoggedInAction
extends ComposerAction
implements ThreadSafe {
public Map act(Redirector redirector,
SourceResolver resolver,
Map objectModel,
String source,
Parameters par)
throws Exception {
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("BEGIN act resolver="+resolver+
", objectModel="+objectModel+
", source="+source+
", par="+par);
}
Map map = null;
String handlerName = par.getParameter("handler", null);
AuthenticationManager authManager = null;
try {
authManager = (AuthenticationManager)
this.manager.lookup(AuthenticationManager.ROLE);
if (authManager.isAuthenticated(handlerName) == true) {
map = authManager.createMap();
}
} finally {
this.manager.release(authManager);
}
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("END act map="+map);
}
return map;
}
}
1.1
xml-cocoon2/src/java/org/apache/cocoon/webapps/authentication/acting/LoginAction.java
Index: LoginAction.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2002 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.acting;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.avalon.excalibur.source.SourceParameters;
import org.apache.avalon.framework.activity.Disposable;
import org.apache.avalon.framework.component.Component;
import org.apache.avalon.framework.component.ComponentManager;
import org.apache.avalon.framework.component.ComponentException;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.avalon.framework.thread.ThreadSafe;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.acting.ComposerAction;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.webapps.authentication.AuthenticationConstants;
import
org.apache.cocoon.webapps.authentication.components.AuthenticationManager;
/**
* This action logs the current user into a given handler
*
* @author <a href="mailto:[EMAIL PROTECTED]">Carsten Ziegeler</a>
* @version CVS $Id: LoginAction.java,v 1.1 2002/04/17 10:04:52 cziegeler Exp
$
*/
public final class LoginAction
extends ComposerAction
implements ThreadSafe {
public Map act(Redirector redirector,
SourceResolver resolver,
Map objectModel,
String source,
Parameters par)
throws Exception {
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("BEGIN act resolver="+resolver+
", objectModel="+objectModel+
", source="+source+
", par="+par);
}
final String handlerName = par.getParameter("handler", null);
if ( handlerName == null )
throw new ProcessingException("LoginAction requires at least the
handler parameter.");
final Request request = ObjectModelHelper.getRequest( objectModel );
// build authentication parameters
SourceParameters authenticationParameters = new SourceParameters();
String[] enum = par.getNames();
if (enum != null) {
for(int i = 0; i < enum.length; i++) {
final String key = enum[i];
if ( key.startsWith("parameter_") ) {
String value = par.getParameter(key);
if ( value.startsWith("request:") ) {
value = request.getParameter(
value.substring("request:".length()) );
if (value == null) value = "";
}
authenticationParameters.setParameter(
key.substring("parameter_".length()),
value);
}
}
}
Map map = null;
// authenticate
AuthenticationManager authManager = null;
try {
authManager = (AuthenticationManager)
this.manager.lookup(AuthenticationManager.ROLE);
Object o;
o = authManager.authenticate( handlerName,
authenticationParameters);
if ( null == o) {
// success
map = authManager.createMap();
} else {
request.setAttribute(AuthenticationConstants.REQUEST_ATTRIBUTE_FAILED_LOGIN +
handlerName, o);
}
} finally {
this.manager.release(authManager);
}
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("END act map="+map);
}
return map;
}
}
1.1
xml-cocoon2/src/java/org/apache/cocoon/webapps/authentication/acting/LogoutAction.java
Index: LogoutAction.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2002 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.acting;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.avalon.framework.activity.Disposable;
import org.apache.avalon.framework.component.Component;
import org.apache.avalon.framework.component.ComponentManager;
import org.apache.avalon.framework.component.ComponentException;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.avalon.framework.thread.ThreadSafe;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.acting.ComposerAction;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.webapps.authentication.AuthenticationConstants;
import
org.apache.cocoon.webapps.authentication.components.AuthenticationManager;
/**
* This action logs the current user out of a given handler
*
* @author <a href="mailto:[EMAIL PROTECTED]">Carsten Ziegeler</a>
* @version CVS $Id: LogoutAction.java,v 1.1 2002/04/17 10:04:52 cziegeler
Exp $
*/
public final class LogoutAction
extends ComposerAction
implements ThreadSafe {
public Map act(Redirector redirector,
SourceResolver resolver,
Map objectModel,
String source,
Parameters par)
throws Exception {
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("BEGIN act resolver="+resolver+
", objectModel="+objectModel+
", source="+source+
", par="+par);
}
final Request request = ObjectModelHelper.getRequest( objectModel );
final String handlerName = par.getParameter("handler",
(String)request.getAttribute(AuthenticationConstants.REQUEST_ATTRIBUTE_HANDLER_NAME));
if ( null == handlerName )
throw new ProcessingException("LogoutAction requires at least the
handler parameter.");
final String mode = par.getParameter("mode", "normal");
// authenticate
AuthenticationManager manager = null;
try {
manager = (AuthenticationManager)
this.manager.lookup(AuthenticationManager.ROLE);
manager.logout( handlerName , mode );
} finally {
this.manager.release( manager );
}
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("END act map={}");
}
return EMPTY_MAP;
}
}
1.1
xml-cocoon2/src/java/org/apache/cocoon/webapps/authentication/components/ApplicationHandler.java
Index: ApplicationHandler.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2002 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.components;
import java.io.IOException;
import java.util.*;
import org.apache.avalon.excalibur.source.SourceParameters;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.webapps.session.context.SessionContext;
import org.apache.cocoon.webapps.session.connector.*;
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: ApplicationHandler.java,v 1.1 2002/04/17 10:04:52
cziegeler Exp $
*/
public final class ApplicationHandler
implements java.io.Serializable {
/** The unique name of the handler */
private String name;
/** The load resource (optional) */
private Resource loadResource;
/** The save resource (optional) */
private Resource saveResource;
/** Is the application loaded on demand */
private boolean loadOnDemand = false;
/** The corresponding handler */
private Handler handler;
/** The configuration fragments */
private Map configurations;
/** The name of the context attribute, where isLoaded is stored */
private String attributeName;
/**
* Construct a new application handler
*/
public ApplicationHandler(Handler 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);
this.attributeName = "authentication_AH_" + handler.getName() + "_" +
this.name;
}
/**
* Configure an application
*/
public void configure(SourceResolver resolver, Configuration appconf)
throws ProcessingException, SAXException, IOException,
ConfigurationException {
Configuration child = null;
String uri = null;
String classname = 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 = new Resource(resolver,
child.getAttribute("uri"));
this.loadResource.setResourceParameters(SourceParameters.create(child));
}
// get save resource (optional)
child = appconf.getChild("save", false);
if (child != null) {
this.saveResource = new Resource(resolver,
child.getAttribute("uri"));
this.saveResource.setResourceParameters(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 Handler getHandler() { return handler; }
/**
* Get the load resource
*/
public Resource getLoadResource() {
return this.loadResource;
}
/**
* Get the save resource
*/
public Resource getSaveResource() {
return this.saveResource;
}
public boolean getIsLoaded(SessionContext context)
throws ProcessingException {
if (this.loadResource == null) {
return true;
} else {
boolean result = false;
Boolean bool = (Boolean)context.getAttribute(this.attributeName);
if (bool != null) result = bool.booleanValue();
return result;
}
}
public void setIsLoaded(SessionContext context, boolean value)
throws ProcessingException {
Boolean bool = new Boolean(value);
context.setAttribute(this.attributeName, bool);
}
public boolean getLoadOnDemand() { return loadOnDemand; }
/**
* Get the configuration
*/
public Configuration getConfiguration(String name) {
return (Configuration)this.configurations.get(name);
}
}
1.1
xml-cocoon2/src/java/org/apache/cocoon/webapps/authentication/components/AuthenticationManager.java
Index: AuthenticationManager.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2002 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.components;
import java.io.IOException;
import java.util.*;
import org.apache.avalon.excalibur.source.SourceParameters;
import org.apache.avalon.excalibur.source.SourceUtil;
import org.apache.avalon.framework.component.ComponentException;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.Response;
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.context.SessionContextImpl;
import
org.apache.cocoon.webapps.authentication.context.SessionContextProviderImpl;
import org.apache.cocoon.webapps.session.components.AbstractSessionComponent;
import org.apache.cocoon.webapps.session.components.SessionManager;
import org.apache.cocoon.webapps.session.context.SessionContext;
import org.apache.cocoon.webapps.session.context.SessionContextProvider;
import org.apache.cocoon.webapps.session.context.SimpleSessionContext;
import org.apache.cocoon.webapps.session.connector.ResourceConnector;
import org.apache.cocoon.webapps.session.connector.Resource;
import org.apache.cocoon.webapps.session.xml.XMLUtil;
import org.apache.cocoon.xml.IncludeXMLConsumer;
import org.apache.cocoon.xml.XMLConsumer;
import org.apache.cocoon.xml.XMLUtils;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import org.w3c.dom.Attr;
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;
/**
* This is the basis authentication component.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Carsten Ziegeler</a>
* @version CVS $Id: AuthenticationManager.java,v 1.1 2002/04/17 10:04:52
cziegeler Exp $
*/
public final class AuthenticationManager
extends AbstractSessionComponent
implements Configurable {
/** The Avalon Role */
public static final String ROLE = AuthenticationManager.class.getName();
/** Request parameter */
public static final String REQ_PARAMETER_STATE = "authstate";
public static final String REQ_PARAMETER_ROLE = "authrole";
public static final String REQ_PARAMETER_ID = "authid";
public static final String REQ_PARAMETER_USER = "authuser";
private static final String SESSION_CONTEXT_ATTRIBUTE_ADMIN_ROLE =
"org.apache.cocoon.webapps.authentication.adminrole";
/** All Handlers hashed by their name */
private Map configuredHandlers;
/** All handlers of the current user */
private Map userHandlers;
/** The handler configuration */
private Configuration configuration;
/** The application name of the current resource */
private String applicationName;
/** The application */
private ApplicationHandler application;
/** The handler name of the current resource */
private String handlerName;
/** The handler of the current resource */
private Handler handler;
/** The media Types */
private MediaType[] allMediaTypes;
private String defaultMediaType;
private String[] mediaTypeNames;
/** media type */
private String mediaType;
/** The context provider */
private static SessionContextProviderImpl contextProvider;
/** Init the class,
* add the provider for the sunSpot context
*/
static {
// add the provider for the sunSpot context
contextProvider = new SessionContextProviderImpl();
try {
SessionManager.addSessionContextProvider(contextProvider,
AuthenticationConstants.SESSION_CONTEXT_NAME);
} catch (ProcessingException local) {
throw new RuntimeException("Unable to register provider for
authentication context.");
}
}
/**
* Set the configuration
* The configuration is set global once when the AuthAction is
* configured, allowing other components to use the AuthenticationManager
* instance
*/
private static Configuration authenticationConfiguration;
public static void setConfiguration(Configuration configuration) {
authenticationConfiguration = configuration;
}
/**
* Recyclable
*/
public void recycle() {
super.recycle();
this.applicationName = null;
this.application = null;
this.handler = null;
this.handlerName = null;
this.userHandlers = null;
}
/**
* Set the <code>SourceResolver</code>, objectModel <code>Map</code>,
* used to process the request.
* This method is automatically called for each request. Do not invoke
* this method by hand.
*/
public void setup(SourceResolver resolver, Map objectModel)
throws ProcessingException, SAXException, IOException {
super.setup(resolver, objectModel);
// synchronized
this.configureHandlers(AuthenticationManager.authenticationConfiguration);
// get the media of the current request
String useragent = request.getHeader("User-Agent");
MediaType media = null;
if (useragent != null) {
int i, l;
i = 0;
l = this.allMediaTypes.length;
while (i < l && media == null) {
if (useragent.indexOf(this.allMediaTypes[i].useragent) == -1)
{
i++;
} else {
media = this.allMediaTypes[i];
}
}
}
this.mediaType = (media == null ? this.defaultMediaType : media.name);
this.request.setAttribute(AuthenticationConstants.REQUEST_ATTRIBUTE_MEDIA_TYPE,
this.mediaType);
}
/**
* Configurable interface.
*/
public void configure(Configuration myConfiguration)
throws ConfigurationException {
// no sync required
Configuration mediaConf = myConfiguration.getChild("mediatypes",
false);
if (mediaConf == null) throw new
ConfigurationException("AuthenticationManager needs mediatypes configuration");
this.defaultMediaType = mediaConf.getAttribute("default");
this.mediaTypeNames = new String[1];
this.mediaTypeNames[0] = this.defaultMediaType;
boolean found;
int i;
String name;
Configuration[] childs = mediaConf.getChildren("media");
MediaType[] array = new MediaType[0];
MediaType[] copy;
Configuration current;
if (childs != null) {
for(int x = 0; x < childs.length; x++) {
current = childs[x];
copy = new MediaType[array.length + 1];
System.arraycopy(array, 0, copy, 0, array.length);
array = copy;
name = current.getAttribute("name");
array[array.length-1] = new MediaType(name,
current.getAttribute("useragent"));
found = false;
i = 0;
while ( i < this.mediaTypeNames.length && found == false) {
found = this.mediaTypeNames[i].equals(name);
i++;
}
if (found == false) {
String[] newStrings = new
String[this.mediaTypeNames.length + 1];
System.arraycopy(this.mediaTypeNames, 0, newStrings, 0,
this.mediaTypeNames.length);
newStrings[newStrings.length-1] = name;
this.mediaTypeNames = newStrings;
}
}
}
this.allMediaTypes = array;
this.configuredHandlers = null;
}
/**
* Configure the handler
*/
private void configureHandlers(Configuration configuration)
throws ProcessingException {
if (this.configuredHandlers == null
|| configuration.equals(this.configuration) == false) {
this.configuration = configuration; // store the configuration
try {
this.configuredHandlers = new Hashtable(3, 2);
Configuration handlersConfiguration =
configuration.getChild("handlers", false);
Configuration currentHandlerConf;
if (handlersConfiguration != null) {
Configuration[] handlerConfs =
handlersConfiguration.getChildren("handler");
if (handlerConfs != null) {
for(int i = 0; i < handlerConfs.length; i++) {
currentHandlerConf = handlerConfs[i];
String value;
// get name
String name =
currentHandlerConf.getAttribute("name");
// test if handler is unique
if (this.configuredHandlers.get(name) != null) {
throw new ConfigurationException("Handler
names must be unique: " + name);
}
// create handler
Handler currentHandler = new Handler(name);
// store handler
this.configuredHandlers.put(name, currentHandler);
currentHandler.configure(this.resolver,
this.request, currentHandlerConf);
}
}
}
} catch (IOException local) {
throw new ProcessingException("IOException: " + local, local);
} catch (SAXException local) {
throw new ProcessingException("SAXException: " + local,
local);
} catch (ConfigurationException local) {
throw new ProcessingException("ConfigurationException: " +
local, local);
}
}
}
/**
* Store the handlers in the session of the user
*/
private void storeHandlers()
throws ProcessingException {
final Request req = ObjectModelHelper.getRequest( this.objectModel );
final Session session = req.getSession();
Map myHandlers =
(Map)session.getAttribute(AuthenticationConstants.SESSION_ATTRIBUTE_HANDLERS);
if (myHandlers == null) {
this.userHandlers = this.configuredHandlers;
session.setAttribute(AuthenticationConstants.SESSION_ATTRIBUTE_HANDLERS,
this.userHandlers);
this.configuredHandlers = null;
this.configureHandlers(this.configuration);
}
}
/**
* Test if the media of the current request is the given value
*/
public boolean testMedia(Map objectModel, String value) {
// synchronized
Request req = ObjectModelHelper.getRequest( objectModel );
boolean result = false;
if (req != null) {
String useragent = request.getHeader("User-Agent");
MediaType theMedia = null;
int i, l;
i = 0;
l = this.allMediaTypes.length;
while (i < l && theMedia == null) {
if (useragent.indexOf(this.allMediaTypes[i].useragent) == -1)
{
i++;
} else {
theMedia = this.allMediaTypes[i];
}
}
if (theMedia != null) {
result = theMedia.name.equals(value);
} else {
result = this.defaultMediaType.equals(value);
}
}
return result;
}
public String[] getMediaTypes() {
// synchronized
return this.mediaTypeNames;
}
/**
* Create a new context
*/
public Handler getHandler() {
return this.handler;
}
/**
* Show the configuration for the admin.
* If <code>src</code> is "admin" or null the admin configuration is
shown.
* If <code>src</code> is "user" the configuration of the current user
* is shown.
*/
public void showConfiguration(XMLConsumer consumer,
String src)
throws ProcessingException, SAXException {
// synchronized
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("BEGIN showConfiguration consumer=" +
consumer + ", src="+src);
}
boolean isAdmin = (src == null || src.equals("admin"));
// now start producing xml:
AttributesImpl attr = new AttributesImpl();
consumer.startElement("", "configuration", "configuration", attr);
// set the conf uri:
// This is a bug in the servlet 2.2 API!!!
// It does not contain the context: String uri =
HttpUtils.getRequestURL(this.request).toString();
// So: ABSOLUTELY USELESS
String uri = this.response.encodeURL(this.request.getRequestURI());
consumer.startElement("", "uri", "uri", attr);
consumer.characters(uri.toCharArray(), 0, uri.length());
consumer.endElement("", "uri", "uri");
if (isAdmin == true) {
// build the menue
consumer.startElement("", "menue", "menue", attr);
if (this.handler != null) {
if (this.handler.getNewRoleResource() != null) {
consumer.startElement("", "addrole", "addrole", attr);
consumer.endElement("", "addrole", "addrole");
}
if (this.handler.getDeleteRoleResource() != null) {
consumer.startElement("", "delrole", "delrole", attr);
consumer.endElement("", "delrole", "delrole");
}
}
consumer.endElement("", "menue", "menue");
}
SessionContext context = this.getAuthenticationSessionContext(true);
synchronized (context) {
String state =
this.request.getParameter(AuthenticationManager.REQ_PARAMETER_STATE);
if (state == null) {
state = (isAdmin == true ? "main" : "seluser");
}
if (state.equals("addrole") == true) {
String role =
this.request.getParameter(AuthenticationManager.REQ_PARAMETER_ROLE);
if (role != null && role.trim().length() > 0) {
SourceParameters pars = new SourceParameters();
// first include all request parameters
Enumeration requestParameters =
this.request.getParameterNames();
String current;
while (requestParameters.hasMoreElements() == true) {
current = (String)requestParameters.nextElement();
pars.setParameter(current,
this.request.getParameter(current));
}
this.addRole(role, pars);
} else {
role = null;
}
context.setAttribute(AuthenticationManager.SESSION_CONTEXT_ATTRIBUTE_ADMIN_ROLE,
null);
}
if (state.equals("delrole") == true) {
try {
String role =
this.request.getParameter(AuthenticationManager.REQ_PARAMETER_ROLE);
if (role != null) {
// first delete user
DocumentFragment userDF = this.getUsers(role, null);
NodeList users = null;
if (userDF != null) users =
XMLUtil.selectNodeList(userDF, "users/user");
if (users != null) {
for(int i = 0; i < users.getLength(); i++) {
this.deleteUser(role,
XMLUtil.getValueOf(users.item(i), "ID"), null);
}
}
this.deleteRole(role, null);
}
context.setAttribute(AuthenticationManager.SESSION_CONTEXT_ATTRIBUTE_ADMIN_ROLE,
null);
} catch (javax.xml.transform.TransformerException local) {
throw new ProcessingException("TransformerException: " +
local, local);
}
}
if (state.equals("chguser") == true) {
String role;
String id;
String user;
if (isAdmin == false) {
SourceParameters pars = this.createParameters(null);
id = pars.getParameter("ID", null);
role = pars.getParameter("role", null);
user = "old";
} else {
role =
this.request.getParameter(AuthenticationManager.REQ_PARAMETER_ROLE);
id =
this.request.getParameter(AuthenticationManager.REQ_PARAMETER_ID);
user =
this.request.getParameter(AuthenticationManager.REQ_PARAMETER_USER);
}
boolean addingNewUserFailed = false;
if (role != null && id != null && user != null) {
if (user.equals("new") == true) {
SourceParameters pars = new SourceParameters();
// first include all request parameters
Enumeration requestParameters =
this.request.getParameterNames();
String current;
while (requestParameters.hasMoreElements() == true) {
current = (String)requestParameters.nextElement();
pars.setParameter(current,
this.request.getParameter(current));
}
addingNewUserFailed = !this.addUser(role, id, pars);
if (addingNewUserFailed == false) {
consumer.startElement("", "addeduser",
"addeduser", attr);
consumer.characters(id.toCharArray(), 0,
id.length());
consumer.endElement("", "addeduser", "addeduser");
}
} else {
String delete =
this.request.getParameter("authdeluser");
if (delete != null && delete.equals("true") == true) {
this.deleteUser(role, id, null);
} else {
SourceParameters pars = new SourceParameters();
// first include all request parameters
Enumeration requestParameters =
this.request.getParameterNames();
String current;
while (requestParameters.hasMoreElements() ==
true) {
current =
(String)requestParameters.nextElement();
pars.setParameter(current,
this.request.getParameter(current));
}
this.changeUser(role, id, pars);
}
}
context.setAttribute(AuthenticationManager.SESSION_CONTEXT_ATTRIBUTE_ADMIN_ROLE,
null);
}
if (addingNewUserFailed == false) {
state = (isAdmin == true ? "adduser" : "seluser");
} else {
state = "erruser";
}
}
if (state.equals("seluser") == true) {
String role;
String id;
if (isAdmin == false) {
SourceParameters pars = this.createParameters(null);
id = pars.getParameter("ID", null);
role = pars.getParameter("role", null);
} else {
role =
this.request.getParameter(AuthenticationManager.REQ_PARAMETER_ROLE);
id =
this.request.getParameter(AuthenticationManager.REQ_PARAMETER_ID);
}
if (role != null && id != null) {
context.setAttribute(AuthenticationManager.SESSION_CONTEXT_ATTRIBUTE_ADMIN_ROLE,
role);
// include users
DocumentFragment userDF = this.getUsers(role, id);
Element users = null;
try {
if (userDF != null) users =
(Element)XMLUtil.getSingleNode(userDF, "users/user");
} catch (javax.xml.transform.TransformerException local) {
throw new ProcessingException("TransformerException:
" + local, local);
}
consumer.startElement("", "uservalues", "uservalues",
attr);
if (users != null && users.hasChildNodes() == true) {
NodeList childs = users.getChildNodes();
for(int i = 0; i < childs.getLength(); i++) {
if (childs.item(i).getNodeType() ==
Node.ELEMENT_NODE)
IncludeXMLConsumer.includeNode(childs.item(i), consumer, consumer);
}
}
consumer.endElement("", "uservalues", "uservalues");
}
consumer.startElement("", "user", "user", attr);
consumer.characters("old".toCharArray(), 0, 3);
consumer.endElement("", "user", "user");
if (isAdmin == false) {
consumer.startElement("", "role", "role", attr);
consumer.characters(role.toCharArray(), 0, role.length());
consumer.endElement("", "role", "role");
}
}
if (state.equals("erruser") == true) {
String role;
String id;
if (isAdmin == false) {
SourceParameters pars = this.createParameters(null);
id = pars.getParameter("ID", null);
role = pars.getParameter("role", null);
} else {
role =
this.request.getParameter(AuthenticationManager.REQ_PARAMETER_ROLE);
id =
this.request.getParameter(AuthenticationManager.REQ_PARAMETER_ID);
}
if (role != null && id != null) {
context.setAttribute(AuthenticationManager.SESSION_CONTEXT_ATTRIBUTE_ADMIN_ROLE,
role);
// include users
DocumentFragment userDF = this.getUsers(role, id);
Element users = null;
try {
if (userDF != null) users =
(Element)XMLUtil.getSingleNode(userDF, "users/user");
} catch (javax.xml.transform.TransformerException local) {
throw new ProcessingException("TransformerException:
" + local, local);
}
consumer.startElement("", "uservalues", "uservalues",
attr);
if (users != null && users.hasChildNodes() == true) {
NodeList childs = users.getChildNodes();
for(int i = 0; i < childs.getLength(); i++) {
if (childs.item(i).getNodeType() ==
Node.ELEMENT_NODE)
IncludeXMLConsumer.includeNode(childs.item(i), consumer, consumer);
}
}
consumer.endElement("", "uservalues", "uservalues");
}
consumer.startElement("", "user", "user", attr);
consumer.characters("error".toCharArray(), 0, 5);
consumer.endElement("", "user", "user");
if (isAdmin == false) {
consumer.startElement("", "role", "role", attr);
consumer.characters(role.toCharArray(), 0, role.length());
consumer.endElement("", "role", "role");
}
}
if (state.equals("adduser") == true) {
consumer.startElement("", "user", "user", attr);
consumer.characters("new".toCharArray(), 0, 3);
consumer.endElement("", "user", "user");
}
if (state.equals("selrole") == true) {
String role =
this.request.getParameter(AuthenticationManager.REQ_PARAMETER_ROLE);
context.setAttribute(AuthenticationManager.SESSION_CONTEXT_ATTRIBUTE_ADMIN_ROLE,
role);
// include users
DocumentFragment userDF = this.getUsers(role, null);
Node users = null;
try {
if (userDF != null) users = XMLUtil.getSingleNode(userDF,
"users");
} catch (javax.xml.transform.TransformerException local) {
throw new ProcessingException("TransformerException: " +
local, local);
}
IncludeXMLConsumer.includeNode(users, consumer, consumer);
}
if (isAdmin == true) {
// include roles
DocumentFragment rolesDF = this.getRoles();
Node roles = null;
try {
if (rolesDF != null) roles =
XMLUtil.getSingleNode(rolesDF, "roles");
} catch (javax.xml.transform.TransformerException local) {
throw new ProcessingException("TransformerException: " +
local, local);
}
IncludeXMLConsumer.includeNode(roles, consumer, consumer);
// include selected role
String role =
(String)context.getAttribute(AuthenticationManager.SESSION_CONTEXT_ATTRIBUTE_ADMIN_ROLE);
if (role != null) {
consumer.startElement("", "role", "role", attr);
consumer.characters(role.toCharArray(), 0, role.length());
consumer.endElement("", "role", "role");
}
}
} // end synchronized(context)
consumer.endElement("", "configuration", "configuration");
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("END showConfiguration");
}
}
/**
* Is the current user authenticated for the given handler?
*/
public boolean isAuthenticated()
throws IOException, ProcessingException {
return this.isAuthenticated(this.handlerName);
}
/**
* Is the current user authenticated for the given handler?
*/
public boolean isAuthenticated(String name)
throws IOException, ProcessingException {
// synchronized
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("BEGIN isAuthenticated handler=" + name);
}
boolean isAuthenticated = true;
// if no handler: authenticated
if (name != null) {
isAuthenticated = false;
// get the session context
// if no session context: not authenticated
SessionContext context =
this.getAuthenticationSessionContext(false);
if (context != null) {
synchronized(context) {
try {
// is result in cache (= context attribute)
if (context.getAttribute("COCOON_ISAUTHENTICATED:" +
name) != null) {
isAuthenticated = true;
} else {
DocumentFragment id = context.getXML("/" + name +
"/authentication/ID");
isAuthenticated = (id != null);
if (isAuthenticated == true) {
// cache result
context.setAttribute("COCOON_ISAUTHENTICATED:" + name, "YES");
}
}
} catch (ProcessingException local) {
// ignore this for now
this.getLogger().error("isAuthenticated");
isAuthenticated = false;
}
}
}
}
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("END isAuthenticated authenticated=" +
isAuthenticated);
}
return isAuthenticated;
}
/**
* Checks authentication and generates a redirect, if not authenticated
*/
public boolean checkAuthentication(Redirector redirector, boolean
loadingResource)
throws IOException, ProcessingException {
// synchronized not needed
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("BEGIN checkAuthentication");
}
boolean isAuthenticated = true;
// get user handlers (if available)
final Request req = ObjectModelHelper.getRequest( this.objectModel );
final Session session = req.getSession(false);
if ( null != session ) {
this.userHandlers =
(Map)session.getAttribute(AuthenticationConstants.SESSION_ATTRIBUTE_HANDLERS);
}
// set the configuration for the handler
final String newHandlerName =
(String)this.request.getAttribute(AuthenticationConstants.REQUEST_ATTRIBUTE_HANDLER_NAME);
final String newAppName =
(String)this.request.getAttribute(AuthenticationConstants.REQUEST_ATTRIBUTE_APPLICATION_NAME);
if (this.handlerName == null) this.handlerName = "";
if (this.applicationName == null) this.applicationName = "";
if (this.handlerName.equals(newHandlerName) == false
|| this.applicationName.equals(newAppName) == false) {
this.handlerName = newHandlerName;
this.applicationName = newAppName;
this.handler = null;
this.application = null;
if (this.handlerName != null) {
if ( null != this.userHandlers) {
this.handler =
(Handler)this.userHandlers.get(this.handlerName);
} else {
this.handler =
(Handler)this.configuredHandlers.get(this.handlerName);
}
if (this.handler == null) {
throw new ProcessingException("Handler not found: " +
this.handlerName);
}
if (this.applicationName != null) {
this.application =
(ApplicationHandler)this.handler.getApplications().get(this.applicationName);
if (this.application == null) {
throw new ProcessingException("Application not found:
" + this.applicationName);
}
}
}
} else {
if (this.handlerName.equals("")) this.handlerName = null;
if (this.applicationName.equals("")) this.applicationName = null;
}
if (this.handler != null) {
isAuthenticated = this.isAuthenticated(this.handlerName);
if (isAuthenticated == false) {
// create parameters
SourceParameters parameters = handler.getRedirectParameters();
if (parameters == null) parameters = new SourceParameters();
String resource = this.request.getRequestURI();
if (this.request.getQueryString() != null) {
resource += '?' + this.request.getQueryString();
}
parameters.setSingleParameterValue("resource", resource);
final String redirectURI = handler.getRedirectURI();
redirector.redirect(false,
SourceUtil.appendParameters(redirectURI, parameters));
} else {
if (loadingResource == true) {
// load application data if we are not inside a resource
loading of authentication
this.checkLoaded((SessionContextImpl)this.getSessionManager().getContext(AuthenticationConstants.SESSION_CONTEXT_NAME),
"/");
}
}
}
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("END checkAuthentication authenticated=" +
isAuthenticated);
}
return isAuthenticated;
}
/**
* Get the handler
*/
private Handler getHandler(String name) {
// synchronized
if ( null == name ) return null;
if ( null != this.userHandlers ) {
return (Handler)this.userHandlers.get( name );
} else {
return (Handler)this.configuredHandlers.get( name );
}
}
/**
* 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.
*/
public DocumentFragment authenticate(String loginHandlerName,
SourceParameters parameters)
throws ProcessingException, IOException {
// synchronized
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("BEGIN authenticate handler=" +
loginHandlerName +
", parameters="+parameters);
}
DocumentFragment authenticationFragment = null;
boolean isValid = false;
final Handler myHandler = this.getHandler(loginHandlerName);
if (this.getLogger().isInfoEnabled() == true) {
this.getLogger().info("AuthenticationManager: Trying to
authenticate using handler '" + loginHandlerName +"'");
}
if (myHandler != null) {
String exceptionMsg = null;
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("start authentication");
}
final Resource authenticationResource =
myHandler.getAuthenticationResource();
final String authenticationResourceName =
authenticationResource.getResourceIdentifier();
final int authenticationResourceType =
authenticationResource.getResourceType();
final SourceParameters authenticationParameters =
authenticationResource.getResourceParameters();
if (parameters != null) {
parameters.add(authenticationParameters);
} else {
parameters = authenticationParameters;
}
try {
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("start invoking auth resource");
}
authenticationFragment =
this.getResourceConnector().loadXML(authenticationResourceType, null,
authenticationResourceName, parameters);
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("end invoking auth resource");
}
} catch (ProcessingException local) {
this.getLogger().error("authenticate", local);
exceptionMsg = local.getMessage();
}
// test if authentication was successful
if (authenticationFragment != null) {
isValid =
this.isValidAuthenticationFragment(authenticationFragment);
if (isValid == true) {
this.storeHandlers();
if (this.getLogger().isInfoEnabled() == true) {
this.getLogger().info("AuthenticationManager: Success
authenticated using handler '" + myHandler.getName()+"'");
}
// create session object if necessary, context etc and
get it
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("creating session");
}
SessionContext context =
this.getAuthenticationSessionContext(true);
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("session created");
}
synchronized(context) {
// add special nodes to the authentication block:
// useragent, type and media
Element specialElement;
Text specialValue;
Element authNode;
authNode =
(Element)authenticationFragment.getFirstChild();
specialElement =
authenticationFragment.getOwnerDocument().createElementNS(null, "useragent");
specialValue =
authenticationFragment.getOwnerDocument().createTextNode(request.getHeader("User-Agent"));
specialElement.appendChild(specialValue);
authNode.appendChild(specialElement);
specialElement =
authenticationFragment.getOwnerDocument().createElementNS(null, "type");
specialValue =
authenticationFragment.getOwnerDocument().createTextNode("cocoon.authentication");
specialElement.appendChild(specialValue);
authNode.appendChild(specialElement);
specialElement =
authenticationFragment.getOwnerDocument().createElementNS(null, "media");
specialValue =
authenticationFragment.getOwnerDocument().createTextNode(this.mediaType);
specialElement.appendChild(specialValue);
authNode.appendChild(specialElement);
// store the authentication data in the context
context.setXML("/" + myHandler.getName(),
authenticationFragment);
// Now create the return value for this method:
// <code>null</code>
authenticationFragment = null;
// And now load applications
boolean loaded = true;
Iterator applications =
myHandler.getApplications().values().iterator();
ApplicationHandler appHandler;
while (applications.hasNext() == true) {
appHandler =
(ApplicationHandler)applications.next();
if (appHandler.getLoadOnDemand() == false) {
this.loadApplicationXML((SessionContextImpl)this.getSessionManager().getContext(AuthenticationConstants.SESSION_CONTEXT_NAME),
appHandler, "/");
} else {
loaded = appHandler.getIsLoaded(context);
}
}
myHandler.setApplicationsLoaded(context, loaded);
} // end sync
}
}
if (isValid == false) {
if (this.getLogger().isInfoEnabled() == true) {
this.getLogger().info("AuthenticationManager: Failed
authentication using handler '" + myHandler.getName()+"'");
}
// get the /authentication/data Node if available
Node data = null;
if (authenticationFragment != null) {
data =
XMLUtil.getFirstNodeFromPath(authenticationFragment, 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
Document doc = XMLUtil.createDocument();
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));
}
}
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("end authentication");
}
}
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("END authenticate
fragment="+authenticationFragment);
}
return authenticationFragment;
}
/**
* Check the fragment if it is valid
*/
private boolean isValidAuthenticationFragment(DocumentFragment
authenticationFragment) {
// calling method is synced
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("BEGIN isValidAuthenticationFragment
fragment=" + authenticationFragment);
}
boolean isValid = false;
// authenticationFragment must only have exactly one child with
// the name authentication
if (authenticationFragment.hasChildNodes() == true
&& authenticationFragment.getChildNodes().getLength() == 1) {
Node child = authenticationFragment.getFirstChild();
if (child.getNodeType() == Node.ELEMENT_NODE
&& child.getNodeName().equals("authentication") == true) {
// now authentication must have one child ID
if (child.hasChildNodes() == true) {
NodeList children = child.getChildNodes();
boolean found = false;
int i = 0;
int l = children.getLength();
while (found == false && i < l) {
child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE
&& child.getNodeName().equals("ID") == true) {
found = true;
} else {
i++;
}
}
// now the last check: ID must have a TEXT child
if (found == true) {
child.normalize(); // join text nodes
if (child.hasChildNodes() == true &&
child.getChildNodes().getLength() == 1 &&
child.getChildNodes().item(0).getNodeType() ==
Node.TEXT_NODE) {
String value =
child.getChildNodes().item(0).getNodeValue().trim();
if (value.length() > 0) isValid = true;
}
}
}
}
}
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("END isValidAuthenticationFragment
valid="+isValid);
}
return isValid;
}
/**
* Get the private SessionContext
*/
private SessionContext getAuthenticationSessionContext(boolean create)
throws ProcessingException {
// synchronized
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("BEGIN getAuthenticationSessionContext
create=" + create);
}
SessionContext context = null;
Session session = this.getSessionManager().getSession(create);
if (session != null) {
synchronized(session) {
context =
(SessionContext)session.getAttribute(AuthenticationConstants.SESSION_ATTRIBUTE_CONTEXT_NAME);
if (context == null && create == true) {
context = new SimpleSessionContext();
context.setup(AuthenticationConstants.SESSION_CONTEXT_NAME, null, null);
session.setAttribute(AuthenticationConstants.SESSION_ATTRIBUTE_CONTEXT_NAME,
context);
}
}
}
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("END getAuthenticationSessionContext
context=" + context);
}
return context;
}
/**
* Logout from the given handler
* Terminate session if required
*/
public void logout(String logoutHandlerName,
String mode)
throws ProcessingException {
// synchronized via context
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("BEGIN logout handler=" +
logoutHandlerName +
", mode="+mode);
}
SessionContext context = this.getAuthenticationSessionContext(false);
if (context != null && logoutHandlerName != null) {
// cached?
if (context.getAttribute("COCOON_ISAUTHENTICATED:" +
logoutHandlerName) != null) {
context.setAttribute("COCOON_ISAUTHENTICATED:" +
logoutHandlerName, null);
}
// remove context
context.removeXML(logoutHandlerName);
((SessionContextImpl)this.getSessionManager().getContext(AuthenticationConstants.SESSION_CONTEXT_NAME)).cleanParametersCache(logoutHandlerName);
Handler logoutHandler =
(Handler)this.getHandler(logoutHandlerName);
// reset application load status
logoutHandler.setApplicationsLoaded(context, false);
Iterator apps =
logoutHandler.getApplications().values().iterator();
ApplicationHandler current;
while (apps.hasNext() == true) {
current = (ApplicationHandler)apps.next();
current.setIsLoaded(context, false);
}
final List handlerContexts = logoutHandler.getHandlerContexts();
final Iterator iter = handlerContexts.iterator();
while ( iter.hasNext() ) {
final SessionContext deleteContext = (SessionContext)
iter.next();
this.getSessionManager().deleteContext(
deleteContext.getName() );
}
logoutHandler.clearHandlerContexts();
}
if ( mode != null && mode.equalsIgnoreCase("terminateSession") ) {
this.getSessionManager().terminateSession(true);
}
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("END logout");
}
}
/**
* Get the configuration if available
*/
public Configuration getModuleConfiguration(String name)
throws ProcessingException {
// synchronized not needed
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("BEGIN getModuleConfiguration
module="+name);
}
Configuration conf = null;
if (this.handler != null && this.application != null) {
conf = this.application.getConfiguration(name);
}
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("END getModuleConfiguration conf="+conf);
}
return conf;
}
/**
* Create Application Context.
* This context is destroyed when the user logs out of the handler
*/
public SessionContext createHandlerContext(String name,
String loadURI,
String saveURI)
throws ProcessingException {
// synchronized
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("BEGIN createHandlerContext name="+name);
}
SessionContext context = null;
if (this.handler != null) {
final Session session =
this.getSessionManager().getSession(false);
synchronized(session) {
try {
// create new context
context = this.getSessionManager().createContext(name,
loadURI, saveURI);
this.handler.addHandlerContext( context );
} catch (IOException ioe) {
throw new ProcessingException("Unable to create session
context.", ioe);
} catch (SAXException saxe) {
throw new ProcessingException("Unable to create session
context.", saxe);
}
} // end synchronized
}
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("END createHandlerContext
context="+context);
}
return context;
}
/**
* Get all users in a document fragment with the following children:
* <users>
* <user>
* <ID>...</ID>
* <role>...</role> <!-- optional -->
* <data>
* ...
* </data>
* </user>
* ....
* </users>
* The document fragment might contain further nodes at the root!
* If <code>role</code> is <code>null</code> all users are fetched,
* otherwise only the users for this role.
* If also ID is not null only the single user is fetched.
*/
public DocumentFragment getUsers(String role, String ID)
throws ProcessingException {
// calling method is syned
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("BEGIN getUsers role="+role+", ID="+ID);
}
DocumentFragment frag = null;
if (this.handler != null && this.handler.getLoadUsersResource() !=
null) {
final Resource loadUsersResource =
this.handler.getLoadUsersResource();
final SourceParameters loadParameters =
loadUsersResource.getResourceParameters();
SourceParameters parameters = (loadParameters == null) ? new
SourceParameters()
:
(SourceParameters)loadParameters.clone();
if (this.applicationName != null)
parameters.setSingleParameterValue("application",
this.applicationName);
if (ID != null) {
parameters.setSingleParameterValue("type", "user");
parameters.setSingleParameterValue("ID", ID);
} else {
parameters.setSingleParameterValue("type", "users");
}
if (role != null) parameters.setSingleParameterValue("role",
role);
frag =
this.getResourceConnector().loadXML(loadUsersResource.getResourceType(), null,
loadUsersResource.getResourceIdentifier(), parameters);
}
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("END getUsers fragment="+(frag == null ?
"null" : XMLUtils.serializeNodeToXML(frag)));
}
return frag;
}
/**
* Get all roles in a document fragment with the following children:
* <roles>
* <role>...</role>
* ....
* </roles>
* The document fragment might contain further nodes at the root!
*/
public DocumentFragment getRoles()
throws ProcessingException {
// calling method is syned
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("BEGIN getRoles");
}
DocumentFragment frag = null;
if (this.handler != null && this.handler.getLoadRolesResource() !=
null) {
final Resource loadRolesResource =
this.handler.getLoadRolesResource();
final SourceParameters loadParameters =
loadRolesResource.getResourceParameters();
SourceParameters parameters = (loadParameters == null) ? new
SourceParameters()
:
(SourceParameters)loadParameters.clone();
if (this.applicationName != null)
parameters.setSingleParameterValue("application",
this.applicationName);
parameters.setSingleParameterValue("type", "roles");
frag =
this.getResourceConnector().loadXML(loadRolesResource.getResourceType(), null,
loadRolesResource.getResourceIdentifier(), parameters);
}
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("END getRoles fragment="+frag);
}
return frag;
}
/**
* Add a role
*/
private void addRole(String name, SourceParameters parameters)
throws ProcessingException {
// calling method is syned
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("BEGIN addRole role="+name+",
parameters="+parameters);
}
if (this.handler != null && this.handler.getNewRoleResource() !=
null) {
final Resource newRoleResource =
this.handler.getNewRoleResource();
final SourceParameters handlerPars =
newRoleResource.getResourceParameters();
if (parameters == null) parameters = new SourceParameters();
parameters.add(handlerPars);
if (this.applicationName != null)
parameters.setSingleParameterValue("application",
this.applicationName);
parameters.setSingleParameterValue("type", "role");
parameters.setSingleParameterValue("role", name);
this.getResourceConnector().loadXML(newRoleResource.getResourceType(), null,
newRoleResource.getResourceIdentifier(), parameters);
}
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("END addRole");
}
}
/**
* Add a user.
* @return If a user with ID already exists <code>false</code> is
returned.
*/
public boolean addUser(String role, String ID, SourceParameters
parameters)
throws ProcessingException {
// calling method is syned
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("BEGIN addUser role="+role+", ID="+ID+",
parameters="+parameters);
}
boolean result = false;
if (this.handler != null
&& this.handler.getNewUserResource() != null
&& ID != null
&& ID.trim().length() > 0) {
// first test if a user with this ID already exists
DocumentFragment user = this.getUsers(null, null);
Node node = null;
if (user != null) {
try {
node = XMLUtil.getSingleNode(user,
"users/user/ID[text()='"+ID+"']");
} catch (javax.xml.transform.TransformerException local) {
throw new ProcessingException("Transformer exception: " +
local, local);
}
}
if (user == null || node == null) {
final Resource newUserResource =
this.handler.getNewUserResource();
final SourceParameters newUsersPars =
newUserResource.getResourceParameters();
if (parameters == null) parameters = new SourceParameters();
parameters.add(newUsersPars);
if (this.applicationName != null)
parameters.setSingleParameterValue("application",
this.applicationName);
parameters.setSingleParameterValue("type", "user");
parameters.setSingleParameterValue("role", role);
parameters.setSingleParameterValue("ID", ID);
this.getResourceConnector().loadXML(newUserResource.getResourceType(), null,
newUserResource.getResourceIdentifier(), parameters);
result = true;
}
}
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("END addUser success="+result);
}
return result;
}
/**
* Delete a role
*/
private void deleteRole(String name, SourceParameters parameters)
throws ProcessingException {
// calling method is syned
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("BEGIN deleteRole role="+name+",
parameters="+parameters);
}
if (this.handler != null && this.handler.getDeleteRoleResource() !=
null) {
final Resource deleteRoleResource =
this.handler.getDeleteRoleResource();
final SourceParameters handlerPars =
deleteRoleResource.getResourceParameters();
if (parameters == null) parameters = new SourceParameters();
parameters.add(handlerPars);
if (this.applicationName != null)
parameters.setSingleParameterValue("application",
this.applicationName);
parameters.setSingleParameterValue("type", "role");
parameters.setSingleParameterValue("role", name);
this.getResourceConnector().loadXML(deleteRoleResource.getResourceType(), null,
deleteRoleResource.getResourceIdentifier(), parameters);
}
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("END deleteRole");
}
}
/**
* Delete a user
*/
private void deleteUser(String role, String name, SourceParameters
parameters)
throws ProcessingException {
// calling method is syned
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("BEGIN deleteUser role="+role+",
ID="+name+", parameters="+parameters);
}
if (this.handler != null && this.handler.getDeleteUserResource() !=
null) {
final Resource deleteUserResource =
this.handler.getDeleteUserResource();
final SourceParameters handlerPars =
deleteUserResource.getResourceParameters();
if (parameters == null) parameters = new SourceParameters();
parameters.add(handlerPars);
if (this.applicationName != null)
parameters.setSingleParameterValue("application",
this.applicationName);
parameters.setSingleParameterValue("type", "user");
parameters.setSingleParameterValue("role", role);
parameters.setSingleParameterValue("ID", name);
this.getResourceConnector().loadXML(deleteUserResource.getResourceType(), null,
deleteUserResource.getResourceIdentifier(), parameters);
}
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("END deleteUser");
}
}
/**
* Change a user
*/
private void changeUser(String role, String name, SourceParameters
parameters)
throws ProcessingException {
// calling method is syned
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("BEGIN changeUser role="+role+",
ID="+name+", parameters="+parameters);
}
if (this.handler != null && this.handler.getChangeUserResource() !=
null) {
final Resource changeUserResource =
this.handler.getChangeUserResource();
final SourceParameters handlerPars =
changeUserResource.getResourceParameters();
if (parameters == null) parameters = new SourceParameters();
parameters.add(handlerPars);
if (this.applicationName != null)
parameters.setSingleParameterValue("application",
this.applicationName);
parameters.setSingleParameterValue("type", "user");
parameters.setSingleParameterValue("role", role);
parameters.setSingleParameterValue("ID", name);
this.getResourceConnector().loadXML(changeUserResource.getResourceType(), null,
changeUserResource.getResourceIdentifier(), parameters);
}
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("END changeUser");
}
}
/**
* Load XML of an application
*/
private void loadApplicationXML(SessionContextImpl context,
ApplicationHandler appHandler,
String path)
throws ProcessingException {
// synchronized
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("BEGIN loadApplicationXML application=" +
appHandler.getName() + ", path="+path);
}
Object o = this.getSessionManager().getSession(true);
synchronized(o) {
if (appHandler.getIsLoaded(context) == false) {
final Resource loadResource =
appHandler.getLoadResource();
final String loadResourceName =
loadResource.getResourceIdentifier();
final int loadResourceType =
loadResource.getResourceType();
SourceParameters parameters =
loadResource.getResourceParameters();
if (parameters != null) parameters =
(SourceParameters)parameters.clone();
parameters = this.createParameters(parameters,
appHandler.getHandler().getName(),
path,
appHandler.getName());
DocumentFragment fragment;
fragment =
this.getResourceConnector().loadXML(loadResourceType, null,
loadResourceName, parameters);
appHandler.setIsLoaded(context, true);
context.setApplicationXML(appHandler.getHandler().getName(),
appHandler.getName(),
path,
fragment);
// now test handler if all applications are loaded
Iterator applications =
appHandler.getHandler().getApplications().values().iterator();
boolean allLoaded = true;
while (allLoaded == true && applications.hasNext() == true) {
allLoaded =
((ApplicationHandler)applications.next()).getIsLoaded(context);
}
appHandler.getHandler().setApplicationsLoaded(context,
allLoaded);
}
} // end synchronized
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("END loadApplicationXML");
}
}
/**
* Check if application for path is loaded
*/
private void checkLoaded(SessionContextImpl context,
String path)
throws ProcessingException {
// synchronized as loadApplicationXML is synced
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("BEGIN checkLoaded path="+path);
}
if (path.equals("/") == true || path.startsWith("/application") ==
true) {
if (this.application != null) {
this.loadApplicationXML(context, this.application, "/");
}
}
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("END checkLoaded");
}
}
/**
* Build parameters for loading and saving of application data
*/
public SourceParameters createParameters(String path)
throws ProcessingException {
// synchronized
if (this.handler == null) {
return new SourceParameters();
}
if (path == null) {
SessionContext context =
this.getAuthenticationSessionContext(false);
SourceParameters pars =
(SourceParameters)context.getAttribute("cachedparameters_" +
this.handler.getName());
if (pars == null) {
pars = this.createParameters(null, this.handlerName, path,
this.applicationName);
context.setAttribute("cachedparameters_" +
this.handler.getName(), pars);
}
return pars;
}
return this.createParameters(null, this.handlerName, path,
this.applicationName);
}
/**
* Create a map for the actions
* The result is cached!
*/
public Map createMap()
throws ProcessingException {
if (this.handler == null) {
// this is only a fallback
return new HashMap();
}
SessionContext context = this.getAuthenticationSessionContext(false);
Map map = (Map)context.getAttribute("cachedmap_" +
this.handler.getName());
if (map == null) {
map = new HashMap();
Parameters pars =
this.createParameters(null).getFirstParameters();
String[] names = pars.getNames();
if (names != null) {
String key;
String value;
for(int i=0;i<names.length;i++) {
key = names[i];
value = pars.getParameter(key, null);
if (value != null) map.put(key, value);
}
}
context.setAttribute("cachedmap_" + this.handler.getName(), map);
}
return map;
}
/**
* Build parameters for loading and saving of application data
*/
private SourceParameters createParameters(SourceParameters parameters,
String myHandler,
String path,
String appName)
throws ProcessingException {
// synchronized
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("BEGIN createParameters handler=" +
myHandler +
", path="+path+ ", application=" + appName);
}
SessionContextImpl context;
context =
(SessionContextImpl)contextProvider.getSessionContext(AuthenticationConstants.SESSION_CONTEXT_NAME,
this.objectModel,
this.resolver,
this.manager);
parameters = context.createParameters(parameters, myHandler, path,
appName);
if (this.getLogger().isDebugEnabled() == true) {
this.getLogger().debug("END createParameters
parameters="+parameters);
}
return parameters;
}
}
/**
* This class stores the media type configuration
*/
final class MediaType {
String name;
String useragent;
MediaType(String name, String useragent) {
this.name = name;
this.useragent = useragent;
}
}
1.1
xml-cocoon2/src/java/org/apache/cocoon/webapps/authentication/components/Handler.java
Index: Handler.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2002 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.components;
import java.io.IOException;
import java.util.*;
import org.apache.avalon.excalibur.source.SourceParameters;
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.cocoon.environment.SourceResolver;
import org.apache.cocoon.webapps.session.context.SessionContext;
import org.apache.cocoon.webapps.session.connector.*;
import org.xml.sax.SAXException;
/**
* The authentication Handler.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Carsten Ziegeler</a>
* @version CVS $Id: Handler.java,v 1.1 2002/04/17 10:04:52 cziegeler Exp $
*/
public final class Handler
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 Resource authenticationResource;
/** The load resource (optional) */
private Resource loadResource;
/** The save resource (optional) */
private Resource saveResource;
/** The ApplicationHandler */
private Map applications = new Hashtable(3, 2);
/** The load-users resource */
private Resource loadUsersResource;
/** The load-roles resource */
private Resource loadRolesResource;
/** The new-user resource */
private Resource newUserResource;
/** The new-role resource */
private Resource newRoleResource;
/** The delete-role resource */
private Resource deleteRoleResource;
/** The delete-user resource */
private Resource deleteUserResource;
/** The change-user resource */
private Resource changeUserResource;
/** The name of the context attribute, where isLoaded is stored */
private final String attributeName;
/** The handler contexts */
private List handlerContexts = new ArrayList(2);
/**
* Create a new handler object.
*/
public Handler(String name) {
this.name = name;
this.attributeName = "authentication_H_" + this.name;
}
/**
* 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://") ) {
this.redirectURI =
this.redirectURI.substring("cocoon://".length());
} else if ( this.redirectURI.startsWith("cocoon:/") ) {
this.redirectURI =
this.redirectURI.substring("cocoon:/".length());
}
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 = new Resource(resolver,
child.getAttribute("uri"));
this.authenticationResource.setResourceParameters(SourceParameters.create(child));
// get load resource (optional)
child = conf.getChild("load", false);
if (child != null) {
this.loadResource = new Resource(resolver,
child.getAttribute("uri"));
this.loadResource.setResourceParameters(SourceParameters.create(child));
}
// get save resource (optional)
child = conf.getChild("save", false);
if (child != null) {
this.saveResource = new Resource(resolver,
child.getAttribute("uri"));
this.saveResource.setResourceParameters(SourceParameters.create(child));
}
// get load-users resource (optional)
child = conf.getChild("load-users", false);
if (child != null) {
this.loadUsersResource = new Resource(resolver,
child.getAttribute("uri"));
this.loadUsersResource.setResourceParameters(SourceParameters.create(child));
}
// get load-roles resource (optional)
child = conf.getChild("load-roles", false);
if (child != null) {
this.loadRolesResource = new Resource(resolver,
child.getAttribute("uri"));
this.loadRolesResource.setResourceParameters(SourceParameters.create(child));
}
// get new user resource (optional)
child = conf.getChild("new-user", false);
if (child != null) {
this.newUserResource = new Resource(resolver,
child.getAttribute("uri"));
this.newUserResource.setResourceParameters(SourceParameters.create(child));
}
// get new role resource (optional)
child = conf.getChild("new-role", false);
if (child != null) {
this.newRoleResource = new Resource(resolver,
child.getAttribute("uri"));
this.newRoleResource.setResourceParameters(SourceParameters.create(child));
}
// get delete user resource (optional)
child = conf.getChild("delete-user", false);
if (child != null) {
this.deleteUserResource = new Resource(resolver,
child.getAttribute("uri"));
this.deleteUserResource.setResourceParameters(SourceParameters.create(child));
}
// get delete role resource (optional)
child = conf.getChild("delete-role", false);
if (child != null) {
this.deleteRoleResource = new Resource(resolver,
child.getAttribute("uri"));
this.deleteRoleResource.setResourceParameters(SourceParameters.create(child));
}
// get change user resource (optional)
child = conf.getChild("change-user", false);
if (child != null) {
this.changeUserResource = new Resource(resolver,
child.getAttribute("uri"));
this.changeUserResource.setResourceParameters(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
ApplicationHandler apphandler = new
ApplicationHandler(this, appName);
// store handler
this.applications.put(appName, apphandler);
// configure
apphandler.configure(resolver, appconf);
}
}
}
}
/**
* 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 Resource getAuthenticationResource() {
return this.authenticationResource;
}
/**
* Get the load users resource
*/
public Resource getLoadUsersResource() { return loadUsersResource; }
/**
* Get the load roles resource
*/
public Resource getLoadRolesResource() { return loadRolesResource; }
/**
* Get the new user resource
*/
public Resource getNewUserResource() { return this.newUserResource; }
/**
* Get the new role resource
*/
public Resource getNewRoleResource() { return this.newRoleResource; }
/** Get the delete user resource */
public Resource getDeleteUserResource() { return this.deleteUserResource;
}
/** Get the delete role resource */
public Resource getDeleteRoleResource() { return this.deleteRoleResource;
}
/** Get the change user resource */
public Resource getChangeUserResource() { return this.changeUserResource;
}
/** Get the save resource */
public Resource getSaveResource() { return this.saveResource; }
/** Get the save resource */
public Resource getLoadResource() { return this.loadResource; }
/**
* Get the applications map
*/
public Map getApplications() { return applications; }
public void setApplicationsLoaded(SessionContext context, boolean value)
throws ProcessingException {
Boolean bool = new Boolean(value);
context.setAttribute(this.attributeName, bool);
}
public boolean getApplicationsLoaded(SessionContext context)
throws ProcessingException {
if (this.applications.isEmpty() == true) {
return true;
} else {
boolean result = false;
Boolean bool = (Boolean)context.getAttribute(this.attributeName);
if (bool != null) result = bool.booleanValue();
return result;
}
}
/**
* Add a handler context
*/
public void addHandlerContext(SessionContext context) {
this.handlerContexts.add( context );
}
/**
* Get handler contexts
*/
public List getHandlerContexts() {
return this.handlerContexts;
}
/**
* Clear handler contexts
*/
public void clearHandlerContexts() {
this.handlerContexts.clear();
}
/**
* toString()
*/
public String toString() {
return "authentication-Handler " + this.name;
}
}
1.1
xml-cocoon2/src/java/org/apache/cocoon/webapps/authentication/context/SessionContextImpl.java
Index: SessionContextImpl.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2002 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.io.IOException;
import java.util.Map;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.ContentHandler;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.AttributesImpl;
import org.apache.avalon.excalibur.source.SourceParameters;
import org.apache.avalon.framework.component.ComponentException;
import org.apache.avalon.framework.component.ComponentManager;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.webapps.session.context.SessionContext;
import org.apache.cocoon.webapps.session.connector.ResourceConnector;
import org.apache.cocoon.webapps.session.connector.Resource;
import org.apache.cocoon.webapps.session.xml.XMLUtil;
import org.apache.cocoon.webapps.authentication.components.*;
/**
*
* @author <a href="mailto:[EMAIL PROTECTED]">Carsten Ziegeler</a>
* @version CVS $Id: SessionContextImpl.java,v 1.1 2002/04/17 10:04:52
cziegeler Exp $
*/
public final class SessionContextImpl
implements SessionContext {
private String name;
private SessionContext authContext;
private Resource loadResource;
private Resource saveResource;
private Resource authLoadResource;
private Resource authSaveResource;
private String handlerName;
private String applicationName;
public SessionContextImpl(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();
if (this.applicationName != null) {
ApplicationHandler appHandler =
(ApplicationHandler)handler.getApplications().get(this.applicationName);
this.loadResource = appHandler.getLoadResource();
this.saveResource = appHandler.getSaveResource();
}
} 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, Resource load, Resource 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.");
}
ResourceConnector connector = null;
try {
synchronized(this.authContext) {
DocumentFragment fragment = this.getXML(path);
if (fragment == null) {
// create empty fake fragment
fragment =
XMLUtil.createDocument().createDocumentFragment();
}
if (parameters != null) {
parameters = (SourceParameters)parameters.clone();
parameters.add(this.authSaveResource.getResourceParameters());
} else if (this.authSaveResource.getResourceParameters() !=
null) {
parameters =
(SourceParameters)this.authSaveResource.getResourceParameters().clone();
}
parameters = this.createParameters(parameters,
this.handlerName,
path,
null);
connector =
(ResourceConnector)manager.lookup(ResourceConnector.ROLE);
connector.saveXML(this.authSaveResource.getResourceType(),
null,
this.authSaveResource.getResourceIdentifier(), parameters,
fragment);
} // end synchronized
} catch (ComponentException ce) {
throw new ProcessingException("Unable to lookup the resource
connector.", ce);
} finally {
manager.release( connector );
}
}
/**
* 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.");
}
ResourceConnector connector = null;
try {
synchronized(this.authContext) {
if (parameters != null) {
parameters = (SourceParameters)parameters.clone();
parameters.add(this.authLoadResource.getResourceParameters());
} else if (this.authLoadResource.getResourceParameters() !=
null) {
parameters =
(SourceParameters)this.authLoadResource.getResourceParameters().clone();
}
parameters = this.createParameters(parameters,
this.handlerName,
path,
null);
connector =
(ResourceConnector)manager.lookup(ResourceConnector.ROLE);
DocumentFragment frag =
connector.loadXML(this.authLoadResource.getResourceType(), null,
this.authLoadResource.getResourceIdentifier(), parameters);
this.setXML(path, frag);
} // end synchronized
} catch (ComponentException ce) {
throw new ProcessingException("Unable to lookup the resource
connector.", ce);
} finally {
manager.release( connector );
}
}
/**
* 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) {
final String loadResourceName =
this.loadResource.getResourceIdentifier();
final int loadResourceType =
this.loadResource.getResourceType();
final SourceParameters loadParameters =
this.loadResource.getResourceParameters();
if (parameters != null) {
parameters = (SourceParameters)parameters.clone();
parameters.add(loadParameters);
} else if (loadParameters != null) {
parameters = (SourceParameters)loadParameters.clone();
}
parameters = this.createParameters(parameters,
this.handlerName,
path,
this.applicationName);
DocumentFragment fragment;
ResourceConnector connector = null;
try {
connector =
(ResourceConnector)manager.lookup(ResourceConnector.ROLE);
fragment = connector.loadXML(loadResourceType, null,
loadResourceName, parameters);
this.setXML(path, fragment);
} catch (ComponentException ce) {
throw new ProcessingException("Unable to lookup the resource
connector.", ce);
} finally {
manager.release( connector );
}
} // 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) {
final String saveResourceName =
this.saveResource.getResourceIdentifier();
final int saveResourceType =
this.saveResource.getResourceType();
final SourceParameters saveParameters =
this.saveResource.getResourceParameters();
if (parameters != null) {
parameters = (SourceParameters)parameters.clone();
parameters.add(saveParameters);
} else if (saveParameters != null) {
parameters = (SourceParameters)saveParameters.clone();
}
parameters = this.createParameters(parameters,
this.handlerName,
path,
this.applicationName);
DocumentFragment fragment = this.getXML("/application" + path);
if (fragment == null) {
// create empty fake fragment
fragment = XMLUtil.createDocument().createDocumentFragment();
}
ResourceConnector connector = null;
try {
connector =
(ResourceConnector)manager.lookup(ResourceConnector.ROLE);
connector.saveXML(saveResourceType, null,
saveResourceName, parameters,
fragment);
} catch (ComponentException ce) {
throw new ProcessingException("Unable to lookup the resource
connector.", ce);
} finally {
manager.release( connector );
}
} // 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;
}
}
1.1
xml-cocoon2/src/java/org/apache/cocoon/webapps/authentication/context/SessionContextProviderImpl.java
Index: SessionContextProviderImpl.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2002 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.environment.ObjectModelHelper;
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.session.context.SessionContext;
import org.apache.cocoon.webapps.session.context.SessionContextProvider;
import org.apache.cocoon.webapps.session.components.SessionManager;
/**
* Context provider for the authentication context
*
* @author <a href="mailto:[EMAIL PROTECTED]">Carsten Ziegeler</a>
* @version CVS $Id: SessionContextProviderImpl.java,v 1.1 2002/04/17
10:04:52 cziegeler Exp $
*/
public final class SessionContextProviderImpl
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
* @result 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)
== true) {
final Request req = ObjectModelHelper.getRequest(objectModel);
final String handlerName =
(String)req.getAttribute(AuthenticationConstants.REQUEST_ATTRIBUTE_HANDLER_NAME);
final String appName =
(String)req.getAttribute(AuthenticationConstants.REQUEST_ATTRIBUTE_APPLICATION_NAME);
final Session session = req.getSession(false);
if (session != null && handlerName != null) {
context =
(SessionContext)session.getAttribute(AuthenticationConstants.SESSION_ATTRIBUTE_CONTEXT_NAME);
context = new SessionContextImpl(context, name, handlerName,
appName, resolver, manager);
}
}
return context;
}
}
1.1
xml-cocoon2/src/java/org/apache/cocoon/webapps/authentication/generation/ConfigurationGenerator.java
Index: ConfigurationGenerator.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2002 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.generation;
import java.io.IOException;
import org.xml.sax.SAXException;
import org.apache.avalon.framework.component.ComponentException;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.generation.ComposerGenerator;
import
org.apache.cocoon.webapps.authentication.components.AuthenticationManager;
/**
* This is the authentication Configuration Generator.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Carsten Ziegeler</a>
* @version CVS $Id: ConfigurationGenerator.java,v 1.1 2002/04/17 10:04:52
cziegeler Exp $
*/
public final class ConfigurationGenerator
extends ComposerGenerator {
public void generate()
throws IOException, SAXException, ProcessingException {
this.xmlConsumer.startDocument();
AuthenticationManager authManager = null;
try {
authManager =
(AuthenticationManager)this.manager.lookup(AuthenticationManager.ROLE);
if (authManager.isAuthenticated() == true) {
authManager.showConfiguration(this.xmlConsumer, this.source);
}
} catch (ComponentException ex) {
throw new ProcessingException("ComponentManagerException: " + ex,
ex);
} finally {
this.manager.release( authManager );
}
this.xmlConsumer.endDocument();
}
}
1.1
xml-cocoon2/src/java/org/apache/cocoon/webapps/authentication/selection/MediaSelector.java
Index: MediaSelector.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2002 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.selection;
import java.util.Map;
import org.apache.avalon.framework.component.ComponentManager;
import org.apache.avalon.framework.component.ComponentException;
import org.apache.avalon.framework.component.Composable;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.avalon.framework.thread.ThreadSafe;
import org.apache.cocoon.selection.Selector;
import
org.apache.cocoon.webapps.authentication.components.AuthenticationManager;
/**
* This selector uses the authentication media management.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Carsten Ziegeler</a>
* @version CVS $Id: MediaSelector.java,v 1.1 2002/04/17 10:04:52 cziegeler
Exp $
*/
public final class MediaSelector
implements Composable, Selector, ThreadSafe {
private ComponentManager manager;
/**
* Composable
*/
public void compose(ComponentManager manager) {
this.manager = manager;
}
/**
* Selector
*/
public boolean select (String expression, Map objectModel, Parameters
parameters) {
AuthenticationManager authManager = null;
boolean result;
try {
authManager = (AuthenticationManager) this.manager.lookup(
AuthenticationManager.ROLE );
result = authManager.testMedia(objectModel, expression);
} catch (Exception local) {
// ignore me
result = false;
} finally {
this.manager.release( authManager );
}
return result;
}
}
1.2 +2 -2
xml-cocoon2/src/java/org/apache/cocoon/webapps/session/context/SessionContextProvider.java
Index: SessionContextProvider.java
===================================================================
RCS file:
/home/cvs/xml-cocoon2/src/java/org/apache/cocoon/webapps/session/context/SessionContextProvider.java,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -r1.1 -r1.2
--- SessionContextProvider.java 17 Apr 2002 08:43:57 -0000 1.1
+++ SessionContextProvider.java 17 Apr 2002 10:04:52 -0000 1.2
@@ -58,12 +58,12 @@
/**
* Interface for a context provider.
- * Objects of this class provide special context, e.g. sunRise or sunSpot.
+ * Objects of this class provide special context, e.g. authentication or
portal.
* The context is (if used) got once by the <code>SessionManager</code>
component
* for each request.
*
* @author <a href="mailto:[EMAIL PROTECTED]">Carsten Ziegeler</a>
- * @version CVS $Id: SessionContextProvider.java,v 1.1 2002/04/17 08:43:57
cziegeler Exp $
+ * @version CVS $Id: SessionContextProvider.java,v 1.2 2002/04/17 10:04:52
cziegeler Exp $
*/
public interface SessionContextProvider {
----------------------------------------------------------------------
In case of troubles, e-mail: [EMAIL PROTECTED]
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]