You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@myfaces.apache.org by mm...@apache.org on 2006/03/03 02:39:24 UTC

svn commit: r382608 - in /myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/util: AddResource.java AddResourceFactory.java DefaultAddResource.java

Author: mmarinschek
Date: Thu Mar  2 17:39:23 2006
New Revision: 382608

URL: http://svn.apache.org/viewcvs?rev=382608&view=rev
Log:
reapplied Mario's changes to resource handling (lost due to merging)

Modified:
    myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/util/AddResource.java
    myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/util/AddResourceFactory.java
    myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/util/DefaultAddResource.java

Modified: myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/util/AddResource.java
URL: http://svn.apache.org/viewcvs/myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/util/AddResource.java?rev=382608&r1=382607&r2=382608&view=diff
==============================================================================
--- myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/util/AddResource.java (original)
+++ myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/util/AddResource.java Thu Mar  2 17:39:23 2006
@@ -22,11 +22,11 @@
 import java.io.IOException;
 
 /**
- * This interface defines methods necessary to render links to resources used 
+ * This interface defines methods necessary to render links to resources used
  * by custom components.
  * Mostly used to avoid having to include [script src="..."][/script]
  * in the head of the pages before using a component.
- * 
+ *
  * @author Sylvain Vieujot (latest modification by $Author$)
  * @version $Revision$ $Date$
  */
@@ -41,12 +41,17 @@
     // Methods to add resources
 
     /**
+     * set the context path of the web-app
+     */
+    public void setContextPath(String contextPath);
+
+    /**
      * Insert a [script src="url"] entry at the current location in the response.
      * The resource is expected to be in the classpath, at the same location as the
      * specified component + "/resource".
      * <p>
-     * Example: when customComponent is class example.Widget, and 
-     * resourceName is script.js, the resource will be retrieved from 
+     * Example: when customComponent is class example.Widget, and
+     * resourceName is script.js, the resource will be retrieved from
      * "example/Widget/resource/script.js" in the classpath.
      */
     public void addJavaScriptHere(FacesContext context, Class myfacesCustomComponent,
@@ -54,21 +59,21 @@
 
     /**
      * Insert a [script src="url"] entry at the current location in the response.
-     * 
+     *
      * @param uri is the location of the desired resource, relative to the base
-     * directory of the webapp (ie its contextPath). 
+     * directory of the webapp (ie its contextPath).
      */
     public void addJavaScriptHere(FacesContext context, String uri) throws IOException;
 
     /**
      * Insert a [script src="url"] entry at the current location in the response.
-     * 
+     *
      * @param context
-     * 
+     *
      * @param resourceHandler is an object which specifies exactly how to build the url
      * that is emitted into the script tag. Code which needs to generate URLs in ways
      * that this class does not support by default can implement a custom ResourceHandler.
-     * 
+     *
      * @throws IOException
      */
     public void addJavaScriptHere(FacesContext context, ResourceHandler resourceHandler)
@@ -82,7 +87,7 @@
      * document positioy by supplying a resourcehandler instance.
      * <p>
      * Use this method to have full control about building the reference url
-     * to identify the resource and to customize how the resource is 
+     * to identify the resource and to customize how the resource is
      * written to the response. In most cases, however, one of the convenience
      * methods on this class can be used without requiring a custom ResourceHandler
      * to be provided.
@@ -100,12 +105,12 @@
      * Insert a [script src="url"] entry into the document header at the
      * specified document position. If the script has already been
      * referenced, it's added only once.
-     * <p> 
+     * <p>
      * The resource is expected to be in the classpath, at the same location as the
      * specified component + "/resource".
      * <p>
-     * Example: when customComponent is class example.Widget, and 
-     * resourceName is script.js, the resource will be retrieved from 
+     * Example: when customComponent is class example.Widget, and
+     * resourceName is script.js, the resource will be retrieved from
      * "example/Widget/resource/script.js" in the classpath.
      */
     public void addJavaScriptAtPosition(FacesContext context, ResourcePosition position,
@@ -115,7 +120,7 @@
      * Insert a [script src="url"] entry into the document header at the
      * specified document position. If the script has already been
      * referenced, it's added only once.
-     * 
+     *
      * @param defer specifies whether the html attribute "defer" is set on the
      * generated script tag. If this is true then the browser will continue
      * processing the html page without waiting for the specified script to
@@ -128,7 +133,7 @@
      * Insert a [script src="url"] entry into the document header at the
      * specified document position. If the script has already been
      * referenced, it's added only once.
-     * 
+     *
      * @param uri is the location of the desired resource, relative to the base
      * directory of the webapp (ie its contextPath).
      */
@@ -214,9 +219,6 @@
     public void serveResource(ServletContext context, HttpServletRequest request,
             HttpServletResponse response) throws IOException;
 
-
-    public boolean hasHeaderBeginInfos(HttpServletRequest request);
-
     /**
      * Parses the response to mark the positions where code will be inserted
      */
@@ -246,7 +248,7 @@
             HttpServletResponse response) throws IOException;
 
     /**
-     * return true if you require the complete response buffered 
+     * return true if you require the complete response buffered
      */
 	public boolean requiresBuffer();
 
@@ -254,4 +256,9 @@
 	 * called when the response has finished
 	 */
 	public void responseFinished();
+
+    /**
+     * check there is something to write to the header
+     */
+    public boolean hasHeaderBeginInfos();
 }

Modified: myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/util/AddResourceFactory.java
URL: http://svn.apache.org/viewcvs/myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/util/AddResourceFactory.java?rev=382608&r1=382607&r2=382608&view=diff
==============================================================================
--- myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/util/AddResourceFactory.java (original)
+++ myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/util/AddResourceFactory.java Thu Mar  2 17:39:23 2006
@@ -28,6 +28,8 @@
 import java.lang.reflect.InvocationTargetException;
 import java.util.HashMap;
 import java.util.Map;
+import java.util.Collection;
+import java.util.Set;
 
 /**
  * This class provides the ability to instantiate AddResource objects.
@@ -37,10 +39,10 @@
  * can specify an alternative implementation of the AddResource
  * interface. The class must have a constructor with a single String
  * argument, representing the context path.
- * 
+ * <p/>
  * Mostly used to avoid having to include [script src="..."][/script]
  * in the head of the pages before using a component.
- * 
+ *
  * @author Peter Mahoney
  * @author Sylvain Vieujot (latest modification by $Author: mmarinschek $)
  * @version $Revision: 358042 $ $Date: 2005-12-20 17:12:56 +0000 (Tue, 20 Dec 2005) $
@@ -48,125 +50,216 @@
 public class AddResourceFactory
 {
 
+
+    public static class RequestMapWrapper implements Map
+    {
+        private final HttpServletRequest request;
+
+        public RequestMapWrapper(final HttpServletRequest request)
+        {
+            this.request = request;
+        }
+
+        public int size()
+        {
+            throw new UnsupportedOperationException();
+        }
+
+        public boolean isEmpty()
+        {
+            throw new UnsupportedOperationException();
+        }
+
+        public boolean containsKey(Object key)
+        {
+            if (key == null)
+            {
+                throw new UnsupportedOperationException("'null' key not supported");
+            }
+            return request.getAttribute(key.toString()) != null;
+        }
+
+        public boolean containsValue(Object value)
+        {
+            throw new UnsupportedOperationException();
+        }
+
+        public Object get(Object key)
+        {
+            if (key == null)
+            {
+                throw new UnsupportedOperationException("'null' key not supported");
+            }
+            return request.getAttribute(key.toString());
+        }
+
+        public Object put(Object key, Object value)
+        {
+            if (key == null)
+            {
+                throw new UnsupportedOperationException("'null' key not supported");
+            }
+
+            Object old = request.getAttribute(key.toString());
+            request.setAttribute(key.toString(), value);
+            return old;
+        }
+
+        public Object remove(Object key)
+        {
+            if (key == null)
+            {
+                throw new UnsupportedOperationException("'null' key not supported");
+            }
+
+            Object old = request.getAttribute(key.toString());
+            request.removeAttribute(key.toString());
+            return old;
+        }
+
+        public void putAll(Map arg)
+        {
+            throw new UnsupportedOperationException();
+        }
+
+        public void clear()
+        {
+            throw new UnsupportedOperationException();
+        }
+
+        public Set keySet()
+        {
+            throw new UnsupportedOperationException();
+        }
+
+        public Collection values()
+        {
+            throw new UnsupportedOperationException();
+        }
+
+        public Set entrySet()
+        {
+            throw new UnsupportedOperationException();
+        }
+
+    }
+
     protected static final Log log = LogFactory.getLog(AddResourceFactory.class);
 
-    /**
-     * Map of AddResource instances keyed by context path. This map will have
-     * more than one entry only if the myfaces library is in the "shared"
-     * classpath of a container where more than one webapp can see it
-     * simultaneously.
-     */
-    private static final Map _addResourceMap = new HashMap();
+    private final static String CACHE_MAP_KEY = "org.apache.myfaces.AddResourceFactory.CACHE_MAP_KEY";
+
 
     /**
      * Internal factory method.
-     * <p>
+     * <p/>
      * Return an instance of AddResource keyed by context path, or create one
-     * if no such instance already exists. Note that the same AddResource object
-     * is shared among all threads servicing the same webapp, so all methods
-     * on this class are required to be threadsafe.
-     * <p>
+     * if no such instance already exists. The instance will be cached using the
+     * given Map, most likely this will the the request map of your servlet request.
+     * Therefore every request uses its own AddResource instance.
+     * </p>
+     * <p/>
      * Note that this method is package-scope for the purposes of unit-testing only.
      * This method should be treated as private by non-test code.
+     * </p>
+     *
+     * @param cacheMap             the map used for caching of the instance. if null, a new instance will be created all the time (for tests)
+     * @param contextPath          context path of your web-app
+     * @param addResourceClassName class name of a class implementing the @link AddResource interface
      */
-    static AddResource getInstance(String contextPath, String addResourceClassName)
+    static AddResource getInstance(Map cacheMap, String contextPath, String addResourceClassName)
     {
-        // Yes, this method does use a variant of the "double locking" idiom
-        // which is well documented to be invalid for general use. However
-        // it is believed safe for use here because AddResource objects in
-        // _addResourceMap are never removed or replaced.
-        AddResource instance = (AddResource) _addResourceMap.get(contextPath);
+        AddResource instance = null;
+
+        if (cacheMap != null)
+        {
+            instance = (AddResource) cacheMap.get(CACHE_MAP_KEY);
+        }
+
         if (instance == null)
         {
-            synchronized (_addResourceMap)
+            if (addResourceClassName == null)
+            {
+                // For efficiency don't use reflection unless it is necessary
+                instance = new DefaultAddResource();
+                instance.setContextPath(contextPath);
+            }
+            else
             {
-                instance = (AddResource) _addResourceMap.get(contextPath);
-                if (instance == null)
+                try
+                {
+                    Class addResourceClass = ClassUtils.classForName(addResourceClassName);
+
+                    if (AddResource.class.isAssignableFrom(addResourceClass))
+                    {
+                        AddResource tmpInstance = (AddResource) addResourceClass.newInstance();
+                        tmpInstance.setContextPath(contextPath);
+
+                        // only use a fully initialized instance
+                        instance = tmpInstance;
+                    }
+                    else
+                    {
+                        log.error("Invalid AddResource class (" + addResourceClass.getName()
+                                + "). Must implement the AddResource interface.");
+                    }
+                }
+                catch (ClassNotFoundException e)
+                {
+                    log.error("AddResource class not found. Using default class instead", e);
+                }
+                catch (IllegalArgumentException e)
+                {
+                    // This should not happen as the constructor has been checked
+                    log.error(e);
+                }
+                catch (InstantiationException e)
                 {
-                	if (addResourceClassName == null)
-                	{
-                		// For efficiency don't use reflection unless it is necessary
-                        instance = new DefaultAddResource(contextPath);                		
-                	}
-                	else
-                	{
-                		try
-                		{
-                			Class addResourceClass = ClassUtils.classForName(addResourceClassName);
-                			
-                			if (AddResource.class.isAssignableFrom(addResourceClass)) 
-                			{
-                				// Look for an appropriate constructor
-                				Constructor[] constructors = addResourceClass.getDeclaredConstructors();
-                				
-                				for (int i = 0; i < constructors.length; i++)
-                				{
-                					Class[] parameters = constructors[i].getParameterTypes();
-
-                					if (parameters.length == 1 && String.class.isAssignableFrom(parameters[i])) 
-                					{
-                						instance = (AddResource) constructors[i].newInstance(new String[] {contextPath});
-                						log.info("Found AddResource class '" + addResourceClass.getName() + "'");
-                						break;
-                					}
-                				}
-                				
-                				if (instance == null)
-                				{
-                        			log.error("Invalid AddResource class (" + addResourceClass.getName() 
-                    					+ "). Must include single argument (context path) constructor.");                					
-                				}
-                			}
-                			else
-                			{
-                    			log.error("Invalid AddResource class (" + addResourceClass.getName() 
-                    					+ "). Must implement the AddResource interface.");
-                			}
-                		}
-                		catch (ClassNotFoundException e)
-                		{
-                			log.error("AddResource class not found. Using default class instead", e);
-                		} 
-                		catch (IllegalArgumentException e) {
-                			// This should not happen as the constructor has been checked
-                			log.error(e);
-						} 
-                		catch (InstantiationException e) {
-                			log.error("Invalid AddResource class. Must be non-abstract", e);
-						} 
-                		catch (IllegalAccessException e) {
-                			log.error("Could not access AddResource class", e);
-						} 
-                		catch (InvocationTargetException e) {
-                			log.error(e);
-						}
-						finally
-						{
-							// Ensure there is always an AddResource object available
-							if (instance == null)
-							{
-								instance = new DefaultAddResource(contextPath);                			                				
-							}
-						}
-                	}
-                    _addResourceMap.put(contextPath, instance);
+                    log.error("Invalid AddResource class. Must be non-abstract", e);
+                }
+                catch (IllegalAccessException e)
+                {
+                    log.error("Could not access AddResource class", e);
+                }
+                finally
+                {
+                    // Ensure there is always an AddResource object available
+                    if (instance == null)
+                    {
+                        instance = new DefaultAddResource();
+                        instance.setContextPath(contextPath);
+                    }
                 }
             }
+
+            if (cacheMap != null)
+            {
+                cacheMap.put(CACHE_MAP_KEY, instance);
+            }
         }
+
         return instance;
     }
 
-    public static AddResource getInstance(FacesContext context)
+
+    public static AddResource getInstance
+            (FacesContext
+                    context)
     {
-        return getInstance(context.getExternalContext().getRequestContextPath(),
-                           MyfacesConfig.getCurrentInstance(context.getExternalContext()).getAddResourceClass());
+        return getInstance(
+                context.getExternalContext().getRequestMap(),
+                context.getExternalContext().getRequestContextPath(),
+                MyfacesConfig.getCurrentInstance(context.getExternalContext()).getAddResourceClass());
     }
 
-    public static AddResource getInstance(HttpServletRequest request)
+    public static AddResource getInstance
+            (HttpServletRequest
+                    request)
     {
-        ServletContext servletContext = ((HttpServletRequest)request).getSession().getServletContext();
-        return getInstance(request.getContextPath(),
-                           MyfacesConfig.getAddResourceClassFromServletContext(servletContext));
+        ServletContext servletContext = ((HttpServletRequest) request).getSession().getServletContext();
+        return getInstance(
+                new RequestMapWrapper(request),
+                request.getContextPath(),
+                MyfacesConfig.getAddResourceClassFromServletContext(servletContext));
     }
 
 }

Modified: myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/util/DefaultAddResource.java
URL: http://svn.apache.org/viewcvs/myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/util/DefaultAddResource.java?rev=382608&r1=382607&r2=382608&view=diff
==============================================================================
--- myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/util/DefaultAddResource.java (original)
+++ myfaces/shared/trunk/core/src/main/java/org/apache/myfaces/shared/renderkit/html/util/DefaultAddResource.java Thu Mar  2 17:39:23 2006
@@ -39,18 +39,18 @@
  * This is a utility class to render link to resources used by custom components.
  * Mostly used to avoid having to include [script src="..."][/script]
  * in the head of the pages before using a component.
- * <p>
+ * <p/>
  * When used together with the ExtensionsFilter, this class can allow components
  * in the body of a page to emit script and stylesheet references into the page
  * head section. The relevant methods on this object simply queue the changes,
- * and when the page is complete the ExtensionsFilter calls back into this 
+ * and when the page is complete the ExtensionsFilter calls back into this
  * class to allow it to insert the commands into the buffered response.
- * <p>
+ * <p/>
  * This class also works with the ExtensionsFilter to allow components to
  * emit references to javascript/css/etc which are bundled in the component's
  * jar file. Special URLs are generated which the ExtensionsFilter will later
  * handle by retrieving the specified resource from the classpath.
- * <p>
+ * <p/>
  * The special URL format is:
  * <pre>
  * {contextPath}/faces/myFacesExtensionResource/
@@ -59,16 +59,16 @@
  * Where:
  * <ul>
  * <li> {contextPath} is the context path of the current webapp
- * <li> {resourceLoaderName} is the fully-qualified name of a class which 
- *  implements the ResourceLoader interface. When a browser app sends a request
- *  for the specified resource, an instance of the specified ResourceLoader class
- *  will be created and passed the resourceURI part of the URL for resolving to the
- *  actual resource to be served back. The standard MyFaces ResourceLoader
- *  implementation only serves resources for files stored beneath path
- *  org/apache/myfaces/custom in the classpath but non-myfaces code can provide their
- *  own ResourceLoader implementations.
+ * <li> {resourceLoaderName} is the fully-qualified name of a class which
+ * implements the ResourceLoader interface. When a browser app sends a request
+ * for the specified resource, an instance of the specified ResourceLoader class
+ * will be created and passed the resourceURI part of the URL for resolving to the
+ * actual resource to be served back. The standard MyFaces ResourceLoader
+ * implementation only serves resources for files stored beneath path
+ * org/apache/myfaces/custom in the classpath but non-myfaces code can provide their
+ * own ResourceLoader implementations.
  * </ul>
- * 
+ *
  * @author Sylvain Vieujot (latest modification by $Author: mmarinschek $)
  * @version $Revision: 371739 373827 $ $Date: 2006-01-31 14:50:35 +0000 (Tue, 31 Jan 2006) $
  */
@@ -80,22 +80,17 @@
 
     private static final String RESOURCE_VIRTUAL_PATH = "/faces/myFacesExtensionResource";
 
-    private static final String HEADER_BEGIN_INFO_REQUEST_ATTRIBUTE_NAME = AddResource.class
-            .getName()
-            + ".HEADER_BEGIN_INFO";
-
-    private static final String BODY_END_INFO_REQUEST_ATTRIBUTE_NAME = AddResource.class.getName()
-            + ".BODY_END_INFO";
-
-    private static final String BODY_ONLOAD_INFO_REQUEST_ATTRIBUTE_NAME = AddResource.class
-            .getName()
-            + ".BODY_ONLOAD_INFO";
-
     private static final String RESOURCES_CACHE_KEY = AddResource.class.getName() + ".CACHE_KEY";
 
-    protected final String _contextPath;
+    protected String _contextPath;
 
     private StringBuffer originalResponse;
+
+    private Set headerBeginInfo;
+    private Set bodyEndInfo;
+    private Set bodyOnloadInfo;
+
+
     protected boolean parserCalled = false;
     protected int headerInsertPosition = -1;
     protected int bodyInsertPosition = -1;
@@ -103,8 +98,21 @@
     protected int afterBodyContentInsertPosition = -1;
     protected int beforeBodyEndPosition = -1;
 
-    protected DefaultAddResource(String contextPath)
+    protected DefaultAddResource()
+    {
+    }
+
+    /**
+     * the context path for the web-app.<br />
+     * You can set the context path only once, every subsequent set will throw an SecurityException
+     */
+    public void setContextPath(String contextPath)
     {
+        if (_contextPath != null)
+        {
+            throw new SecurityException("context path already set");
+        }
+
         _contextPath = contextPath;
     }
 
@@ -114,22 +122,22 @@
      * Insert a [script src="url"] entry at the current location in the response.
      * The resource is expected to be in the classpath, at the same location as the
      * specified component + "/resource".
-     * <p>
-     * Example: when customComponent is class example.Widget, and 
-     * resourceName is script.js, the resource will be retrieved from 
+     * <p/>
+     * Example: when customComponent is class example.Widget, and
+     * resourceName is script.js, the resource will be retrieved from
      * "example/Widget/resource/script.js" in the classpath.
      */
     public void addJavaScriptHere(FacesContext context, Class myfacesCustomComponent,
-            String resourceName) throws IOException
+                                  String resourceName) throws IOException
     {
         addJavaScriptHere(context, new MyFacesResourceHandler(myfacesCustomComponent, resourceName));
     }
 
     /**
      * Insert a [script src="url"] entry at the current location in the response.
-     * 
+     *
      * @param uri is the location of the desired resource, relative to the base
-     * directory of the webapp (ie its contextPath). 
+     *            directory of the webapp (ie its contextPath).
      */
     public void addJavaScriptHere(FacesContext context, String uri) throws IOException
     {
@@ -144,13 +152,11 @@
 
     /**
      * Insert a [script src="url"] entry at the current location in the response.
-     * 
+     *
      * @param context
-     * 
      * @param resourceHandler is an object which specifies exactly how to build the url
-     * that is emitted into the script tag. Code which needs to generate URLs in ways
-     * that this class does not support by default can implement a custom ResourceHandler.
-     * 
+     *                        that is emitted into the script tag. Code which needs to generate URLs in ways
+     *                        that this class does not support by default can implement a custom ResourceHandler.
      * @throws IOException
      */
     public void addJavaScriptHere(FacesContext context, ResourceHandler resourceHandler)
@@ -183,7 +189,7 @@
      * valid, and the getResourceLoaderClass method must return a
      * Class object whose instances implements the ResourceLoader
      * interface.
-     * 
+     *
      * @param resourceHandler
      */
     protected void validateResourceHandler(ResourceHandler resourceHandler)
@@ -196,9 +202,9 @@
     }
 
     /**
-     * Given a Class object, verify that the instances of that class 
+     * Given a Class object, verify that the instances of that class
      * implement the ResourceLoader interface.
-     * 
+     *
      * @param resourceloader
      */
     protected void validateResourceLoader(Class resourceloader)
@@ -213,21 +219,21 @@
     /**
      * Adds the given Javascript resource to the document header at the specified
      * document positioy by supplying a resourcehandler instance.
-     * <p>
+     * <p/>
      * Use this method to have full control about building the reference url
-     * to identify the resource and to customize how the resource is 
+     * to identify the resource and to customize how the resource is
      * written to the response. In most cases, however, one of the convenience
      * methods on this class can be used without requiring a custom ResourceHandler
      * to be provided.
-     * <p>
+     * <p/>
      * If the script has already been referenced, it's added only once.
-     * <p>
+     * <p/>
      * Note that this method <i>queues</i> the javascript for insertion, and that
      * the script is inserted into the buffered response by the ExtensionsFilter
      * after the page is complete.
      */
     public void addJavaScriptAtPosition(FacesContext context, ResourcePosition position,
-            ResourceHandler resourceHandler)
+                                        ResourceHandler resourceHandler)
     {
         addJavaScriptAtPosition(context, position, resourceHandler, false);
     }
@@ -236,16 +242,16 @@
      * Insert a [script src="url"] entry into the document header at the
      * specified document position. If the script has already been
      * referenced, it's added only once.
-     * <p> 
+     * <p/>
      * The resource is expected to be in the classpath, at the same location as the
      * specified component + "/resource".
-     * <p>
-     * Example: when customComponent is class example.Widget, and 
-     * resourceName is script.js, the resource will be retrieved from 
+     * <p/>
+     * Example: when customComponent is class example.Widget, and
+     * resourceName is script.js, the resource will be retrieved from
      * "example/Widget/resource/script.js" in the classpath.
      */
     public void addJavaScriptAtPosition(FacesContext context, ResourcePosition position,
-            Class myfacesCustomComponent, String resourceName)
+                                        Class myfacesCustomComponent, String resourceName)
     {
         addJavaScriptAtPosition(context, position, new MyFacesResourceHandler(
                 myfacesCustomComponent, resourceName));
@@ -255,14 +261,14 @@
      * Insert a [script src="url"] entry into the document header at the
      * specified document position. If the script has already been
      * referenced, it's added only once.
-     * 
+     *
      * @param defer specifies whether the html attribute "defer" is set on the
-     * generated script tag. If this is true then the browser will continue
-     * processing the html page without waiting for the specified script to
-     * load and be run.
+     *              generated script tag. If this is true then the browser will continue
+     *              processing the html page without waiting for the specified script to
+     *              load and be run.
      */
     public void addJavaScriptAtPosition(FacesContext context, ResourcePosition position,
-            Class myfacesCustomComponent, String resourceName, boolean defer)
+                                        Class myfacesCustomComponent, String resourceName, boolean defer)
     {
         addJavaScriptAtPosition(context, position, new MyFacesResourceHandler(
                 myfacesCustomComponent, resourceName), defer);
@@ -272,9 +278,9 @@
      * Insert a [script src="url"] entry into the document header at the
      * specified document position. If the script has already been
      * referenced, it's added only once.
-     * 
+     *
      * @param uri is the location of the desired resource, relative to the base
-     * directory of the webapp (ie its contextPath). 
+     *            directory of the webapp (ie its contextPath).
      */
     public void addJavaScriptAtPosition(FacesContext context, ResourcePosition position, String uri)
     {
@@ -286,19 +292,19 @@
      * If the script has already been referenced, it's added only once.
      */
     public void addJavaScriptAtPosition(FacesContext context, ResourcePosition position, String uri,
-            boolean defer)
+                                        boolean defer)
     {
-        addPositionedInfo(context, position, getScriptInstance(context, uri, defer));
+        addPositionedInfo(position, getScriptInstance(context, uri, defer));
     }
 
     public void addJavaScriptToBodyTag(FacesContext context, String javascriptEventName,
-            String addedJavaScript)
+                                       String addedJavaScript)
     {
         AttributeInfo info = new AttributeInfo();
         info.setAttributeName(javascriptEventName);
         info.setAttributeValue(addedJavaScript);
 
-        addPositionedInfo(context, BODY_ONLOAD, info);
+        addPositionedInfo(BODY_ONLOAD, info);
     }
 
     /**
@@ -306,10 +312,10 @@
      * If the script has already been referenced, it's added only once.
      */
     public void addJavaScriptAtPosition(FacesContext context, ResourcePosition position,
-            ResourceHandler resourceHandler, boolean defer)
+                                        ResourceHandler resourceHandler, boolean defer)
     {
         validateResourceHandler(resourceHandler);
-        addPositionedInfo(context, position, getScriptInstance(context, resourceHandler, defer));
+        addPositionedInfo(position, getScriptInstance(context, resourceHandler, defer));
     }
 
     /**
@@ -317,7 +323,7 @@
      * If the style sheet has already been referenced, it's added only once.
      */
     public void addStyleSheet(FacesContext context, ResourcePosition position,
-            Class myfacesCustomComponent, String resourceName)
+                              Class myfacesCustomComponent, String resourceName)
     {
         addStyleSheet(context, position, new MyFacesResourceHandler(myfacesCustomComponent,
                 resourceName));
@@ -329,7 +335,7 @@
      */
     public void addStyleSheet(FacesContext context, ResourcePosition position, String uri)
     {
-        addPositionedInfo(context, position, getStyleInstance(context, uri));
+        addPositionedInfo(position, getStyleInstance(context, uri));
     }
 
     /**
@@ -337,10 +343,10 @@
      * If the style sheet has already been referenced, it's added only once.
      */
     public void addStyleSheet(FacesContext context, ResourcePosition position,
-            ResourceHandler resourceHandler)
+                              ResourceHandler resourceHandler)
     {
         validateResourceHandler(resourceHandler);
-        addPositionedInfo(context, position, getStyleInstance(context, resourceHandler));
+        addPositionedInfo(position, getStyleInstance(context, resourceHandler));
     }
 
     /**
@@ -348,20 +354,20 @@
      */
     public void addInlineStyleAtPosition(FacesContext context, ResourcePosition position, String inlineStyle)
     {
-        addPositionedInfo(context, position, getInlineStyleInstance(inlineStyle));
+        addPositionedInfo(position, getInlineStyleInstance(inlineStyle));
     }
 
     /**
      * Adds the given Inline Script at the specified document position.
      */
     public void addInlineScriptAtPosition(FacesContext context, ResourcePosition position,
-            String inlineScript)
+                                          String inlineScript)
     {
-        addPositionedInfo(context, position, getInlineScriptInstance(inlineScript));
+        addPositionedInfo(position, getInlineScriptInstance(inlineScript));
     }
 
     public String getResourceUri(FacesContext context, Class myfacesCustomComponent,
-            String resource, boolean withContextPath)
+                                 String resource, boolean withContextPath)
     {
         return getResourceUri(context,
                 new MyFacesResourceHandler(myfacesCustomComponent, resource), withContextPath);
@@ -389,7 +395,7 @@
      * Get the Path used to retrieve an resource.
      */
     public String getResourceUri(FacesContext context, ResourceHandler resourceHandler,
-            boolean withContextPath)
+                                 boolean withContextPath)
     {
         String uri = resourceHandler.getResourceUri(context);
         if (uri == null)
@@ -425,7 +431,7 @@
      * Get the Path used to retrieve an resource.
      */
     protected String getResourceUri(FacesContext context, Class resourceLoader,
-            boolean withContextPath)
+                                    boolean withContextPath)
     {
         StringBuffer sb = new StringBuffer(200);
         sb.append(RESOURCE_VIRTUAL_PATH);
@@ -440,19 +446,19 @@
     /**
      * Return a value used in the {cacheKey} part of a generated URL for a
      * resource reference.
-     * <p>
+     * <p/>
      * Caching in browsers normally works by having files served to them
      * include last-modified and expiry-time http headers. Until the expiry
      * time is reached, a browser will silently use its cached version. After
      * the expiry time, it will send a "get if modified since {time}" message,
      * where {time} is the last-modified header from the version it has cached.
-     * <p>
+     * <p/>
      * Unfortunately this scheme only works well for resources represented as
      * plain files on disk, where the webserver can easily and efficiently see
      * the last-modified time of the resource file. When that query has to be
      * processed by a servlet that doesn't scale well, even when it is possible
      * to determine the resource's last-modified date from servlet code.
-     * <p>
+     * <p/>
      * Fortunately, for the AddResource class a static resource is only ever
      * accessed because a URL was embedded by this class in a dynamic page.
      * This makes it possible to implement caching by instead marking every
@@ -461,7 +467,7 @@
      * invalid; the browser effectively thinks it is fetching a different
      * resource that it hasn't seen before. This is implemented by embedding
      * a "cache key" in the generated URL.
-     * <p>
+     * <p/>
      * Rather than using the actual modification date of a resource as the
      * cache key, we simply use the webapp deployment time. This means that all
      * data cached by browsers will become invalid after a webapp deploy (all
@@ -503,7 +509,7 @@
     }
 
     public void serveResource(ServletContext context, HttpServletRequest request,
-            HttpServletResponse response) throws IOException
+                              HttpServletResponse response) throws IOException
     {
         String pathInfo = request.getPathInfo();
         String uri = request.getContextPath() + request.getServletPath()
@@ -547,85 +553,70 @@
         }
         catch (Throwable e)
         {
-            log.error("Error while serving resource: " +resourceUri+", message : "+ e.getMessage(), e);
+            log.error("Error while serving resource: " + resourceUri + ", message : " + e.getMessage(), e);
             response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
         }
     }
 
     // Positioned stuffs
 
-    protected Set getHeaderBeginInfos(HttpServletRequest request)
+    protected Set getHeaderBeginInfos()
     {
-        Set set = (Set) request.getAttribute(HEADER_BEGIN_INFO_REQUEST_ATTRIBUTE_NAME);
-        if (set == null)
+        if (headerBeginInfo == null)
         {
-            set = new LinkedHashSet();
-            request.setAttribute(HEADER_BEGIN_INFO_REQUEST_ATTRIBUTE_NAME, set);
+            headerBeginInfo = new LinkedHashSet();
         }
-        return set;
+        return headerBeginInfo;
     }
 
-    protected Set getBodyEndInfos(HttpServletRequest request)
+    protected Set getBodyEndInfos()
     {
-        Set set = (Set) request.getAttribute(BODY_END_INFO_REQUEST_ATTRIBUTE_NAME);
-        if (set == null)
+        if (bodyEndInfo == null)
         {
-            set = new LinkedHashSet();
-            request.setAttribute(BODY_END_INFO_REQUEST_ATTRIBUTE_NAME, set);
+            bodyEndInfo = new LinkedHashSet();
         }
-        return set;
+        return bodyEndInfo;
     }
 
-    protected Set getBodyOnloadInfos(HttpServletRequest request)
+    protected Set getBodyOnloadInfos()
     {
-        Set set = (Set) request.getAttribute(BODY_ONLOAD_INFO_REQUEST_ATTRIBUTE_NAME);
-        if (set == null)
+        if (bodyOnloadInfo == null)
         {
-            set = new LinkedHashSet();
-            request.setAttribute(BODY_ONLOAD_INFO_REQUEST_ATTRIBUTE_NAME, set);
+            bodyOnloadInfo = new LinkedHashSet();
         }
-        return set;
+        return bodyOnloadInfo;
     }
 
-    private void addPositionedInfo(FacesContext context, ResourcePosition position, PositionedInfo info)
+    private void addPositionedInfo(ResourcePosition position, PositionedInfo info)
     {
         if (HEADER_BEGIN.equals(position))
         {
-            //todo: fix this to work in PortletRequest as well
-            HttpServletRequest request = (HttpServletRequest) context.getExternalContext()
-                    .getRequest();
-            Set set = getHeaderBeginInfos(request);
+            Set set = getHeaderBeginInfos();
             set.add(info);
         }
         else if (BODY_END.equals(position))
         {
-            //todo: fix this to work in PortletRequest as well
-            HttpServletRequest request = (HttpServletRequest) context.getExternalContext()
-                    .getRequest();
-            Set set = getBodyEndInfos(request);
+            Set set = getBodyEndInfos();
             set.add(info);
 
         }
         else if (BODY_ONLOAD.equals(position))
         {
-            //todo: fix this to work in PortletRequest as well
-            HttpServletRequest request = (HttpServletRequest) context.getExternalContext()
-                    .getRequest();
-            Set set = getBodyOnloadInfos(request);
+            Set set = getBodyOnloadInfos();
             set.add(info);
         }
     }
 
-    public boolean hasHeaderBeginInfos(HttpServletRequest request)
+    public boolean hasHeaderBeginInfos()
     {
-        return request.getAttribute(HEADER_BEGIN_INFO_REQUEST_ATTRIBUTE_NAME) != null;
+        return headerBeginInfo != null;
     }
 
     /**
      * Parses the response to mark the positions where code will be inserted
      */
     public void parseResponse(HttpServletRequest request, String bufferedResponse,
-            HttpServletResponse response)
+                              HttpServletResponse response)
     {
 
         originalResponse = new StringBuffer(bufferedResponse);
@@ -637,7 +628,7 @@
         bodyInsertPosition = l.getBodyInsertPosition();
         beforeBodyPosition = l.getBeforeBodyPosition();
         afterBodyContentInsertPosition = l.getAfterBodyContentInsertPosition();
-        beforeBodyEndPosition = l.getAfterBodyEndPosition()-7;  // 7, which is the length of </body>
+        beforeBodyEndPosition = l.getAfterBodyEndPosition() - 7;  // 7, which is the length of </body>
 
         parserCalled = true;
     }
@@ -646,19 +637,19 @@
      * Writes the javascript code necessary for myfaces in every page, just befode the closing &lt;/body&gt; tag
      */
     public void writeMyFacesJavascriptBeforeBodyEnd(HttpServletRequest request,
-            HttpServletResponse response) throws IOException
+                                                    HttpServletResponse response) throws IOException
     {
-         if (!parserCalled)
-         {
+        if (!parserCalled)
+        {
             throw new IOException("Method parseResponse has to be called first");
-         }
+        }
 
         if (beforeBodyEndPosition >= 0)
         {
             String myFacesJavascript = (String) request.getAttribute("org.apache.myfaces.myFacesJavascript");
-            if(myFacesJavascript != null)
+            if (myFacesJavascript != null)
             {
-            	originalResponse.insert(beforeBodyEndPosition, myFacesJavascript);
+                originalResponse.insert(beforeBodyEndPosition, myFacesJavascript);
             }
             else
             {
@@ -671,11 +662,11 @@
      * Add the resources to the &lt;head&gt; of the page.
      * If the head tag is missing, but the &lt;body&gt; tag is present, the head tag is added.
      * If both are missing, no resource is added.
-     *
+     * <p/>
      * The ordering is such that the user header CSS & JS override the MyFaces' ones.
      */
     public void writeWithFullHeader(HttpServletRequest request,
-            HttpServletResponse response) throws IOException
+                                    HttpServletResponse response) throws IOException
     {
         if (!parserCalled)
         {
@@ -702,7 +693,7 @@
 
         ResponseWriter writer = new org.apache.myfaces.shared.renderkit.html.HtmlResponseWriterImpl(response.getWriter(), org.apache.myfaces.shared.renderkit.html.HtmlRendererUtils
                 .selectContentType(request.getHeader("accept")),
-                                                                                                    response.getCharacterEncoding());
+                response.getCharacterEncoding());
 
         if (afterBodyContentInsertPosition >= 0)
         {
@@ -710,7 +701,7 @@
             HtmlBufferResponseWriterWrapper writerWrapper = HtmlBufferResponseWriterWrapper
                     .getInstance(writer);
 
-            for (Iterator i = getBodyEndInfos(request).iterator(); i.hasNext();)
+            for (Iterator i = getBodyEndInfos().iterator(); i.hasNext();)
             {
                 writerWrapper.write("\n");
 
@@ -729,11 +720,11 @@
         if (bodyInsertPosition > 0)
         {
             StringBuffer buf = new StringBuffer();
-            Set bodyInfos = getBodyOnloadInfos(request);
+            Set bodyInfos = getBodyOnloadInfos();
             if (bodyInfos.size() > 0)
             {
                 int i = 0;
-                for (Iterator it = getBodyOnloadInfos(request).iterator(); it.hasNext();)
+                for (Iterator it = getBodyOnloadInfos().iterator(); it.hasNext();)
                 {
                     AttributeInfo positionedInfo = (AttributeInfo) it.next();
                     if (i == 0)
@@ -759,7 +750,7 @@
             if (addHeaderTags)
                 writerWrapper.write("<head>");
 
-            for (Iterator i = getHeaderBeginInfos(request).iterator(); i.hasNext();)
+            for (Iterator i = getHeaderBeginInfos().iterator(); i.hasNext();)
             {
                 writerWrapper.write("\n");
 
@@ -785,7 +776,7 @@
      * Writes the response
      */
     public void writeResponse(HttpServletRequest request,
-            HttpServletResponse response) throws IOException
+                              HttpServletResponse response) throws IOException
     {
         ResponseWriter writer = new HtmlResponseWriterImpl(response.getWriter(), org.apache.myfaces.shared.renderkit.html.HtmlRendererUtils
                 .selectContentType(request.getHeader("accept")),
@@ -799,7 +790,7 @@
     }
 
     private PositionedInfo getScriptInstance(FacesContext context, ResourceHandler resourceHandler,
-            boolean defer)
+                                             boolean defer)
     {
         return new ScriptPositionedInfo(getResourceUri(context, resourceHandler), defer);
     }
@@ -1041,8 +1032,10 @@
         private int afterBodyContentInsertPosition = -1;
         private int afterBodyEndPosition = -1;
 
-        public ParseCallbackListener() {}
-        
+        public ParseCallbackListener()
+        {
+        }
+
         public void openedStartTag(int charIndex, int tagIdentifier)
         {
             if (tagIdentifier == ReducedHTMLParser.BODY_TAG)
@@ -1103,17 +1096,18 @@
             return afterBodyContentInsertPosition;
         }
 
-        public int getAfterBodyEndPosition() {
+        public int getAfterBodyEndPosition()
+        {
             return afterBodyEndPosition;
         }
     }
 
-	public boolean requiresBuffer()
-	{
-		return true;
-	}
-
-	public void responseFinished()
-	{
-	}
+    public boolean requiresBuffer()
+    {
+        return true;
+    }
+
+    public void responseFinished()
+    {
+    }
 }