You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tapestry.apache.org by hl...@apache.org on 2006/11/06 19:45:08 UTC

svn commit: r471819 - in /tapestry/tapestry5/tapestry-core/trunk/src: main/java/org/apache/tapestry/ main/java/org/apache/tapestry/internal/services/ main/java/org/apache/tapestry/internal/structure/ main/java/org/apache/tapestry/internal/util/ main/ja...

Author: hlship
Date: Mon Nov  6 10:45:06 2006
New Revision: 471819

URL: http://svn.apache.org/viewvc?view=rev&rev=471819
Log:
Add "dirty page" checks to the page pool, such that a page in an unknown/dirty state is discarded, not returned to the page pool.

Modified:
    tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/ComponentEventHandler.java
    tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/ComponentEventDispatcher.java
    tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/ComponentEventImpl.java
    tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/InternalModule.java
    tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/OnEventWorker.java
    tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/PagePoolImpl.java
    tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/RenderQueueImpl.java
    tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/RequestPageCacheImpl.java
    tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/ServicesMessages.java
    tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/structure/ComponentPageElementImpl.java
    tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/structure/Page.java
    tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/structure/PageImpl.java
    tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/structure/StructureMessages.java
    tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/util/AcceptVoidEventHandler.java
    tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/runtime/ComponentEvent.java
    tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/runtime/LifecycleEvent.java
    tapestry/tapestry5/tapestry-core/trunk/src/main/resources/org/apache/tapestry/internal/services/ServicesStrings.properties
    tapestry/tapestry5/tapestry-core/trunk/src/main/resources/org/apache/tapestry/internal/structure/StructureStrings.properties
    tapestry/tapestry5/tapestry-core/trunk/src/test/java/org/apache/tapestry/internal/services/ComponentEventImplTest.java
    tapestry/tapestry5/tapestry-core/trunk/src/test/java/org/apache/tapestry/internal/services/OnEventWorkerTest.java
    tapestry/tapestry5/tapestry-core/trunk/src/test/java/org/apache/tapestry/internal/services/PagePoolImplTest.java
    tapestry/tapestry5/tapestry-core/trunk/src/test/java/org/apache/tapestry/internal/structure/PageImplTest.java

Modified: tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/ComponentEventHandler.java
URL: http://svn.apache.org/viewvc/tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/ComponentEventHandler.java?view=diff&rev=471819&r1=471818&r2=471819
==============================================================================
--- tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/ComponentEventHandler.java (original)
+++ tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/ComponentEventHandler.java Mon Nov  6 10:45:06 2006
@@ -14,21 +14,18 @@
 
 package org.apache.tapestry;
 
+import org.apache.tapestry.runtime.Component;
 import org.apache.tapestry.runtime.ComponentEvent;
 
 /**
  * Handler for a {@link ComponentEvent}, notified when a non-null value is returned from some event
  * handler method.
  * <p>
- * TODO: Generify interface?
- * <p>
  * TODO: Allow handler to return boolean (abort vs. don't abort)
  * <p>
  * TODO: Multiple handlers for different result types / strategy pattern?
- * 
- * 
  */
-public interface ComponentEventHandler
+public interface ComponentEventHandler<T>
 {
     /**
      * Invoked to handle a non-null event handler method result. The handler should determine
@@ -36,8 +33,10 @@
      * 
      * @param result
      *            the result value provided by a method
+     * @param component
+     *            the component from which the result was obtained
      * @param methodDescription
      *            a string description of the class and method name (used when errors occur).
      */
-    void handleResult(Object result, String methodDescription);
+    void handleResult(T result, Component component, String methodDescription);
 }

Modified: tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/ComponentEventDispatcher.java
URL: http://svn.apache.org/viewvc/tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/ComponentEventDispatcher.java?view=diff&rev=471819&r1=471818&r2=471819
==============================================================================
--- tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/ComponentEventDispatcher.java (original)
+++ tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/ComponentEventDispatcher.java Mon Nov  6 10:45:06 2006
@@ -20,6 +20,7 @@
 import org.apache.tapestry.Link;
 import org.apache.tapestry.internal.structure.ComponentPageElement;
 import org.apache.tapestry.internal.structure.Page;
+import org.apache.tapestry.runtime.Component;
 import org.apache.tapestry.services.Dispatcher;
 import org.apache.tapestry.services.WebRequest;
 import org.apache.tapestry.services.WebResponse;
@@ -74,7 +75,7 @@
 
         ComponentEventHandler handler = new ComponentEventHandler()
         {
-            public void handleResult(Object result, String methodDescription)
+            public void handleResult(Object result, Component component, String methodDescription)
             {
                 // Does nothing, right now. Accepts any return value.
             }

Modified: tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/ComponentEventImpl.java
URL: http://svn.apache.org/viewvc/tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/ComponentEventImpl.java?view=diff&rev=471819&r1=471818&r2=471819
==============================================================================
--- tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/ComponentEventImpl.java (original)
+++ tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/ComponentEventImpl.java Mon Nov  6 10:45:06 2006
@@ -17,6 +17,7 @@
 import org.apache.tapestry.ComponentEventHandler;
 import org.apache.tapestry.ComponentResources;
 import org.apache.tapestry.ioc.services.TypeCoercer;
+import org.apache.tapestry.runtime.Component;
 import org.apache.tapestry.runtime.ComponentEvent;
 import org.apache.tapestry.util.Defense;
 
@@ -36,6 +37,7 @@
 
     private boolean _aborted;
 
+    private Component _component;
     private String _methodDescription;
 
     /**
@@ -96,8 +98,9 @@
         return false;
     }
 
-    public void setMethod(String methodDescription)
+    public void setSource(Component component, String methodDescription)
     {
+        _component = component;
         _methodDescription = methodDescription;
     }
 
@@ -114,7 +117,7 @@
         if (result == null)
             return false;
 
-        _handler.handleResult(result, _methodDescription);
+        _handler.handleResult(result, _component, _methodDescription);
 
         _aborted = true;
 

Modified: tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/InternalModule.java
URL: http://svn.apache.org/viewvc/tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/InternalModule.java?view=diff&rev=471819&r1=471818&r2=471819
==============================================================================
--- tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/InternalModule.java (original)
+++ tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/InternalModule.java Mon Nov  6 10:45:06 2006
@@ -172,10 +172,10 @@
         return service;
     }
 
-    public PagePool buildPagePool(@InjectService("PageLoader")
+    public PagePool buildPagePool(Log log, @InjectService("PageLoader")
     PageLoader pageLoader)
     {
-        PagePoolImpl service = new PagePoolImpl(pageLoader);
+        PagePoolImpl service = new PagePoolImpl(log, pageLoader);
 
         // This covers invalidations due to changes to classes
 

Modified: tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/OnEventWorker.java
URL: http://svn.apache.org/viewvc/tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/OnEventWorker.java?view=diff&rev=471819&r1=471818&r2=471819
==============================================================================
--- tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/OnEventWorker.java (original)
+++ tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/OnEventWorker.java Mon Nov  6 10:45:06 2006
@@ -102,7 +102,7 @@
 
         // Several subsequent calls need to know the method name.
 
-        builder.addln("$1.setMethod(\"%s.%s\");", transformation.getClassName(), method
+        builder.addln("$1.setSource(this, \"%s.%s\");", transformation.getClassName(), method
                 .getMediumDescription());
 
         boolean isNonVoid = !method.getReturnType().equals("void");

Modified: tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/PagePoolImpl.java
URL: http://svn.apache.org/viewvc/tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/PagePoolImpl.java?view=diff&rev=471819&r1=471818&r2=471819
==============================================================================
--- tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/PagePoolImpl.java (original)
+++ tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/PagePoolImpl.java Mon Nov  6 10:45:06 2006
@@ -18,6 +18,7 @@
 import java.util.Locale;
 import java.util.Map;
 
+import org.apache.commons.logging.Log;
 import org.apache.tapestry.events.InvalidationListener;
 import org.apache.tapestry.internal.structure.Page;
 import org.apache.tapestry.util.CollectionFactory;
@@ -27,17 +28,18 @@
  * <p>
  * Registered as an invalidation listener with the
  * {@link org.apache.tapestry.internal.services.PageLoader}; thus the pool is cleared whenever
- * 
- * 
  */
 public class PagePoolImpl implements PagePool, InvalidationListener
 {
+    private final Log _log;
+
     private final PageLoader _pageLoader;
 
     private final Map<String, List<Page>> _pool = CollectionFactory.newMap();
 
-    public PagePoolImpl(PageLoader pageLoader)
+    public PagePoolImpl(Log log, PageLoader pageLoader)
     {
+        _log = log;
         _pageLoader = pageLoader;
     }
 
@@ -55,7 +57,13 @@
 
     public synchronized void release(Page page)
     {
-        page.detached();
+        boolean dirty = page.detached();
+
+        if (dirty)
+        {
+            _log.error(ServicesMessages.pageIsDirty(page));
+            return;
+        }
 
         String key = page.getName();
         List<Page> pages = _pool.get(key);
@@ -72,10 +80,6 @@
     public synchronized void objectWasInvalidated()
     {
         _pool.clear();
-
-        // The synchronized is not really needed, since invalidation events are published
-        // when Tapestry is in a single-threaded mode. Because of that, we don't have to worry about
-        // some thread release()ing a page from before the invalidation event.
     }
 
 }

Modified: tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/RenderQueueImpl.java
URL: http://svn.apache.org/viewvc/tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/RenderQueueImpl.java?view=diff&rev=471819&r1=471818&r2=471819
==============================================================================
--- tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/RenderQueueImpl.java (original)
+++ tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/RenderQueueImpl.java Mon Nov  6 10:45:06 2006
@@ -23,9 +23,6 @@
 import org.apache.tapestry.runtime.RenderCommand;
 import org.apache.tapestry.runtime.RenderQueue;
 
-/**
- * 
- */
 public class RenderQueueImpl implements RenderQueue
 {
     private final LinkedList<RenderCommand> _queue = newLinkedList();
@@ -60,6 +57,9 @@
         }
         catch (RuntimeException ex)
         {
+            // This will likely leave the page in a dirty state, and it will not go back into the
+            // page pool.
+
             _log.error(ServicesMessages.renderQueueError(command, ex), ex);
 
             throw ex;

Modified: tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/RequestPageCacheImpl.java
URL: http://svn.apache.org/viewvc/tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/RequestPageCacheImpl.java?view=diff&rev=471819&r1=471818&r2=471819
==============================================================================
--- tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/RequestPageCacheImpl.java (original)
+++ tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/RequestPageCacheImpl.java Mon Nov  6 10:45:06 2006
@@ -22,9 +22,6 @@
 import org.apache.tapestry.ioc.services.ThreadCleanupListener;
 import org.apache.tapestry.services.ComponentClassResolver;
 
-/**
- * 
- */
 public class RequestPageCacheImpl implements RequestPageCache, ThreadCleanupListener
 {
     private final ComponentClassResolver _resolver;

Modified: tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/ServicesMessages.java
URL: http://svn.apache.org/viewvc/tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/ServicesMessages.java?view=diff&rev=471819&r1=471818&r2=471819
==============================================================================
--- tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/ServicesMessages.java (original)
+++ tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/services/ServicesMessages.java Mon Nov  6 10:45:06 2006
@@ -230,4 +230,9 @@
     {
         return MESSAGES.format("parameter-name-must-be-unique", parameterName, parameterValue);
     }
+
+    static String pageIsDirty(Object page)
+    {
+        return MESSAGES.format("page-is-dirty", page);
+    }
 }

Modified: tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/structure/ComponentPageElementImpl.java
URL: http://svn.apache.org/viewvc/tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/structure/ComponentPageElementImpl.java?view=diff&rev=471819&r1=471818&r2=471819
==============================================================================
--- tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/structure/ComponentPageElementImpl.java (original)
+++ tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/structure/ComponentPageElementImpl.java Mon Nov  6 10:45:06 2006
@@ -37,8 +37,8 @@
 import org.apache.tapestry.ioc.services.TypeCoercer;
 import org.apache.tapestry.model.ComponentModel;
 import org.apache.tapestry.model.ParameterModel;
-import org.apache.tapestry.runtime.ComponentEvent;
 import org.apache.tapestry.runtime.Component;
+import org.apache.tapestry.runtime.ComponentEvent;
 import org.apache.tapestry.runtime.LifecycleEvent;
 import org.apache.tapestry.runtime.PageLifecycleListener;
 import org.apache.tapestry.runtime.RenderCommand;
@@ -60,306 +60,125 @@
 public class ComponentPageElementImpl extends BaseLocatable implements ComponentPageElement,
         PageLifecycleListener
 {
-    private final Page _page;
-
-    private final String _id;
-
-    private final String _nestedId;
-
-    private final String _completeId;
-
-    // For the momement, every component will have a template, even if it consists of
-    // just a page element to queue up a BeforeRenderBody phase.
-
-    private final List<PageElement> _template = newList();
-
-    private List<PageElement> _body;
-
-    private final ComponentPageElement _container;
-
-    private final Log _log;
-
-    // The user-provided class, with runtime code enhancements.
-    private final Component _component;
-
-    private final InternalComponentResources _coreResources;
-
-    private Map<String, ComponentPageElement> _children;
-
-    private boolean _rendering;
-
-    private boolean _loaded;
-
-    private final TypeCoercer _typeCoercer;
-
-    /** Map from mixin name to resources for the mixin. */
-    private Map<String, InternalComponentResources> _mixinsByShortName;
-
-    /**
-     * Component lifecycle instances for all mixins; the core component is added to this list during
-     * page load.
-     */
-    private final List<Component> _components = newList();
-
-    /**
-     * Constructor for the root component of a page.
-     */
-    public ComponentPageElementImpl(Page page, Instantiator instantiator, TypeCoercer typeCoercer)
-    {
-        this(page, null, null, instantiator, typeCoercer, null);
-    }
-
-    /**
-     * Constructor for other components embedded within the root component or at deeper levels of
-     * the hierarchy.
-     * 
-     * @param page
-     *            ultimately containing this component
-     * @param container
-     *            component immediately containing this component (may be null for a root component)
-     * @param id
-     *            unique (within the container) id for this component (may be null for a root
-     *            component)
-     * @param instantiator
-     *            used to create the new component instance and access the component's model
-     * @param typeCoercer
-     *            used when coercing parameter values
-     * @param location
-     *            location of the element (within a template), used as part of exception reporting
-     */
-
-    public ComponentPageElementImpl(Page page, ComponentPageElement container, String id,
-            Instantiator instantiator, TypeCoercer typeCoercer, Location location)
+    private static final ComponentCallback CONTAINING_PAGE_DID_ATTACH = new ComponentCallback()
     {
-        super(location);
-
-        ComponentModel model = instantiator.getModel();
-
-        _container = container;
-        _id = id;
-        _page = page;
-        _typeCoercer = typeCoercer;
-        _log = model.getLog();
-
-        _coreResources = new InternalComponentResourcesImpl(this, instantiator, _typeCoercer);
-
-        _component = _coreResources.getComponent();
-
-        String componentClassName = _component.getClass().getName();
-
-        // A page (really, the root component of a page) does not have a container.
-
-        if (container == null)
+        public void run(Component component)
         {
-            _completeId = componentClassName;
-            _nestedId = null;
-        }
-        else
-        {
-            String parentNestedId = container.getNestedId();
-
-            // The root element has no nested id.
-            // The children of the root element have an id.
-
-            if (parentNestedId == null)
-            {
-                _nestedId = id;
-                _completeId = _page.getName() + ":" + id;
-            }
-            else
-            {
-                _nestedId = parentNestedId + "." + id;
-                _completeId = container.getCompleteId() + "." + id;
-            }
+            component.containingPageDidAttach();
         }
-    }
-
-    public String getCompleteId()
-    {
-        return _completeId;
-    }
-
-    public String getNestedId()
-    {
-        return _nestedId;
-    }
-
-    public Page getContainingPage()
-    {
-        return _page;
-    }
-
-    public ComponentPageElement getContainer()
-    {
-        return _container;
-    }
-
-    public Component getPage()
-    {
-        return _page.getRootElement().getComponent();
-    }
-
-    public void addToBody(PageElement element)
-    {
-        if (_body == null)
-            _body = newList();
-
-        _body.add(element);
-    }
-
-    public void addToTemplate(PageElement element)
-    {
-        _template.add(element);
-    }
+    };
 
-    public void addParameter(String parameterName, Binding binding)
+    private static final ComponentCallback CONTAINING_PAGE_DID_DETACH = new ComponentCallback()
     {
-        // Maybe should use colon here? Depends on what works best in the template,
-        // don't want to lock this out as just
-        int dotx = parameterName.lastIndexOf('.');
-
-        if (dotx > 0)
+        public void run(Component component)
         {
-            String mixinName = parameterName.substring(0, dotx);
-            InternalComponentResources mixinResources = InternalUtils.get(
-                    _mixinsByShortName,
-                    mixinName);
-
-            if (mixinResources == null)
-                throw new TapestryException(StructureMessages.missingMixinForParameter(
-                        _completeId,
-                        mixinName,
-                        parameterName), binding, null);
-
-            String simpleName = parameterName.substring(dotx + 1);
-
-            mixinResources.addParameter(simpleName, binding);
+            component.containingPageDidDetach();
         }
+    };
 
-        // Does it match a formal parameter name of the core component? That takes precedence
-
-        if (_coreResources.getComponentModel().getParameterModel(parameterName) != null)
+    private static final ComponentCallback CONTAINING_PAGE_DID_LOAD = new ComponentCallback()
+    {
+        public void run(Component component)
         {
-            _coreResources.addParameter(parameterName, binding);
-            return;
+            component.containingPageDidLoad();
         }
+    };
 
-        for (String mixinName : InternalUtils.sortedKeys(_mixinsByShortName))
+    private static final ComponentCallback POST_RENDER_CLEANUP = new ComponentCallback()
+    {
+        public void run(Component component)
         {
-            InternalComponentResources resources = _mixinsByShortName.get(mixinName);
-            if (resources.getComponentModel().getParameterModel(parameterName) != null)
-            {
-                resources.addParameter(parameterName, binding);
-                return;
-            }
+            component.postRenderCleanup();
         }
+    };
 
-        // For the moment, informal parameters accumulate in the core component's resources, but
-        // that will likely change.
-
-        _coreResources.addParameter(parameterName, binding);
-    }
-
-    public void addEmbeddedElement(ComponentPageElement child)
-    {
-        if (_children == null)
-            _children = newMap();
-
-        String childId = child.getId();
-
-        // TODO: Check for conflicts!
-
-        _children.put(childId, child);
-    }
+    // For the momement, every component will have a template, even if it consists of
+    // just a page element to queue up a BeforeRenderBody phase.
 
-    public Component getEmbeddedComponent(String embeddedId)
+    private final RenderCommand _afterRender = new RenderCommand()
     {
-        return getEmbeddedElement(embeddedId).getComponent();
-    }
+        public void render(final MarkupWriter writer, RenderQueue queue)
+        {
+            final LifecycleEvent<Boolean> event = newEvent(false);
 
-    public String getId()
-    {
-        return _id;
-    }
+            ComponentCallback callback = new ComponentCallback()
+            {
+                public void run(Component component)
+                {
+                    component.afterRender(writer, event);
+                }
+            };
 
-    private LifecycleEvent<Boolean> newEvent(boolean defaultValue)
-    {
-        return new LifecycleEvent<Boolean>(_log, Boolean.class, defaultValue);
-    }
+            invoke(true, callback);
 
-    // NOTE: May want to investigate lazy creation of these.
+            if (event.getResult())
+                queue.push(_beginRender);
+        }
 
-    // This is the state machine for rendering an individual component.
+        @Override
+        public String toString()
+        {
+            return String.format("AfterRender[%s]", _completeId);
+        }
+    };
 
-    private final RenderCommand _setupRender = new RenderCommand()
+    private final RenderCommand _afterRenderBody = new RenderCommand()
     {
-        public void render(MarkupWriter writer, RenderQueue queue)
+        public void render(final MarkupWriter writer, RenderQueue queue)
         {
-            _rendering = true;
-
-            LifecycleEvent<Boolean> event = newEvent(true);
-
-            for (Component component : _components)
-                component.setupRender(writer, event);
+            final LifecycleEvent<Boolean> event = newEvent(false);
 
-            // Here's the problem: if an exception gets thrown during rendering, then
-            // some components may never see their CleanupRender phase cleanup occur, leaving
-            // the page as a whole in an undesirable state. I suppose
-            // that the pageDidDetach() would be another place to clean things up, but perhaps
-            // RenderQueue needs to catch exceptions and invoke commands that related to cleanup?
-            // Or have a way to determine if the page is "dirty" and should not go back into the
-            // pool?
+            ComponentCallback callback = new ComponentCallback()
+            {
+                public void run(Component component)
+                {
+                    component.afterRenderBody(writer, event);
+                }
+            };
 
-            queue.push(_cleanupRender);
+            invoke(true, callback);
 
             if (event.getResult())
-                queue.push(_beginRender);
+                queue.push(_beforeRenderBody);
         }
 
         @Override
         public String toString()
         {
-            return String.format("SetupRender[%s]", _completeId);
+            return String.format("AfterRenderBody[%s]", _completeId);
         }
     };
 
-    private final RenderCommand _beginRender = new RenderCommand()
+    private final RenderCommand _afterRenderTemplate = new RenderCommand()
     {
         public void render(final MarkupWriter writer, final RenderQueue queue)
         {
-            final LifecycleEvent<Boolean> event = newEvent(true);
+            final LifecycleEvent<Boolean> event = newEvent(false);
 
             ComponentCallback callback = new ComponentCallback()
             {
                 public void run(Component component)
                 {
-                    component.beginRender(writer, event);
+                    component.afterRenderTemplate(writer, event);
                 }
             };
 
-            invoke(false, callback);
-
-            // If the component has no template whatsoever, then a
-            // renderBody element is added as the lone element of the component's template.
-            // So every component will have a non-empty template.
+            invoke(true, callback);
 
             if (event.getResult())
-            {
-                queue.push(_afterRender);
                 queue.push(_beforeRenderTemplate);
-            }
         }
 
         @Override
         public String toString()
         {
-            return String.format("BeginRender[%s]", _completeId);
+            return String.format("BeforeRenderTemplate[%s]", _completeId);
         }
     };
 
-    private final RenderCommand _beforeRenderTemplate = new RenderCommand()
+    private final RenderCommand _beforeRenderBody = new RenderCommand()
     {
-        public void render(final MarkupWriter writer, final RenderQueue queue)
+        public void render(final MarkupWriter writer, RenderQueue queue)
         {
             final LifecycleEvent<Boolean> event = newEvent(true);
 
@@ -367,43 +186,45 @@
             {
                 public void run(Component component)
                 {
-                    component.beforeRenderTemplate(writer, event);
+                    component.beforeRenderBody(writer, event);
                 }
             };
 
             invoke(false, callback);
 
-            queue.push(_afterRenderTemplate);
+            queue.push(_afterRenderBody);
 
             if (event.getResult())
-                pushElements(queue, _template);
+                pushElements(queue, _body);
         }
 
         @Override
         public String toString()
         {
-            return String.format("BeforeRenderTemplate[%s]", _completeId);
+            return String.format("BeforeRenderBody[%s]", _completeId);
         }
     };
 
-    private final RenderCommand _afterRenderTemplate = new RenderCommand()
+    private final RenderCommand _beforeRenderTemplate = new RenderCommand()
     {
         public void render(final MarkupWriter writer, final RenderQueue queue)
         {
-            final LifecycleEvent<Boolean> event = newEvent(false);
+            final LifecycleEvent<Boolean> event = newEvent(true);
 
             ComponentCallback callback = new ComponentCallback()
             {
                 public void run(Component component)
                 {
-                    component.afterRenderTemplate(writer, event);
+                    component.beforeRenderTemplate(writer, event);
                 }
             };
 
-            invoke(true, callback);
+            invoke(false, callback);
+
+            queue.push(_afterRenderTemplate);
 
             if (event.getResult())
-                queue.push(_beforeRenderTemplate);
+                pushElements(queue, _template);
         }
 
         @Override
@@ -413,9 +234,9 @@
         }
     };
 
-    private final RenderCommand _beforeRenderBody = new RenderCommand()
+    private final RenderCommand _beginRender = new RenderCommand()
     {
-        public void render(final MarkupWriter writer, RenderQueue queue)
+        public void render(final MarkupWriter writer, final RenderQueue queue)
         {
             final LifecycleEvent<Boolean> event = newEvent(true);
 
@@ -423,27 +244,35 @@
             {
                 public void run(Component component)
                 {
-                    component.beforeRenderBody(writer, event);
+                    component.beginRender(writer, event);
                 }
             };
 
             invoke(false, callback);
 
-            queue.push(_afterRenderBody);
+            // If the component has no template whatsoever, then a
+            // renderBody element is added as the lone element of the component's template.
+            // So every component will have a non-empty template.
 
             if (event.getResult())
-                pushElements(queue, _body);
+            {
+                queue.push(_afterRender);
+                queue.push(_beforeRenderTemplate);
+            }
         }
 
         @Override
         public String toString()
         {
-            return String.format("BeforeRenderBody[%s]", _completeId);
+            return String.format("BeginRender[%s]", _completeId);
         }
-
     };
 
-    private final RenderCommand _afterRenderBody = new RenderCommand()
+    private List<PageElement> _body;
+
+    private Map<String, ComponentPageElement> _children;
+
+    private final RenderCommand _cleanupRender = new RenderCommand()
     {
         public void render(final MarkupWriter writer, RenderQueue queue)
         {
@@ -453,38 +282,88 @@
             {
                 public void run(Component component)
                 {
-                    component.afterRenderBody(writer, event);
+                    component.cleanupRender(writer, event);
                 }
             };
 
             invoke(true, callback);
 
             if (event.getResult())
-                queue.push(_beforeRenderBody);
+            {
+                queue.push(_setupRender);
+            }
+            else
+            {
+                _rendering = false;
+
+                invoke(false, POST_RENDER_CLEANUP);
+
+                // NOW and only now the component is done rendering and fully cleaned up. Decrement
+                // the page's dirty count. If the entire render goes well, then the page will be
+                // clean and can be stored into the pool for later reuse.
+
+                _page.decrementDirtyCount();
+            }
+
         }
 
         @Override
         public String toString()
         {
-            return String.format("AfterRenderBody[%s]", _completeId);
+            return String.format("CleanupRender[%s]", _completeId);
         }
     };
 
-    private final RenderCommand _afterRender = new RenderCommand()
+    private final String _completeId;
+
+    // The user-provided class, with runtime code enhancements.
+    private final Component _component;
+
+    /**
+     * Component lifecycle instances for all mixins; the core component is added to this list during
+     * page load. This is only used in the case that a component has mixins (in which case, the core
+     * component is listed last).
+     */
+    private List<Component> _components = null;
+
+    private final ComponentPageElement _container;
+
+    private final InternalComponentResources _coreResources;
+
+    private final String _id;
+
+    private boolean _loaded;
+
+    private final Log _log;
+
+    /** Map from mixin name to resources for the mixin. Created when first mixin is added. */
+    private Map<String, InternalComponentResources> _mixinsByShortName;
+
+    private final String _nestedId;
+
+    private final Page _page;
+
+    private boolean _rendering;
+
+    private final RenderCommand _setupRender = new RenderCommand()
     {
         public void render(final MarkupWriter writer, RenderQueue queue)
         {
-            final LifecycleEvent<Boolean> event = newEvent(false);
+            _rendering = true;
+
+            final LifecycleEvent<Boolean> event = newEvent(true);
 
             ComponentCallback callback = new ComponentCallback()
             {
                 public void run(Component component)
                 {
-                    component.afterRender(writer, event);
+                    component.setupRender(writer, event);
                 }
             };
 
-            invoke(true, callback);
+            invoke(false, callback);
+
+            queue.push(_cleanupRender);
 
             if (event.getResult())
                 queue.push(_beginRender);
@@ -493,64 +372,214 @@
         @Override
         public String toString()
         {
-            return String.format("AfterRender[%s]", _completeId);
+            return String.format("SetupRender[%s]", _completeId);
         }
     };
 
-    private final RenderCommand _cleanupRender = new RenderCommand()
+    private final List<PageElement> _template = newList();
+
+    private final TypeCoercer _typeCoercer;
+
+    /**
+     * Constructor for other components embedded within the root component or at deeper levels of
+     * the hierarchy.
+     * 
+     * @param page
+     *            ultimately containing this component
+     * @param container
+     *            component immediately containing this component (may be null for a root component)
+     * @param id
+     *            unique (within the container) id for this component (may be null for a root
+     *            component)
+     * @param instantiator
+     *            used to create the new component instance and access the component's model
+     * @param typeCoercer
+     *            used when coercing parameter values
+     * @param location
+     *            location of the element (within a template), used as part of exception reporting
+     */
+
+    public ComponentPageElementImpl(Page page, ComponentPageElement container, String id,
+            Instantiator instantiator, TypeCoercer typeCoercer, Location location)
     {
-        public void render(final MarkupWriter writer, RenderQueue queue)
-        {
-            final LifecycleEvent<Boolean> event = newEvent(false);
+        super(location);
 
-            ComponentCallback callback = new ComponentCallback()
-            {
-                public void run(Component component)
-                {
-                    component.cleanupRender(writer, event);
-                }
-            };
+        ComponentModel model = instantiator.getModel();
 
-            invoke(true, callback);
+        _container = container;
+        _id = id;
+        _page = page;
+        _typeCoercer = typeCoercer;
+        _log = model.getLog();
 
-            if (event.getResult())
+        _coreResources = new InternalComponentResourcesImpl(this, instantiator, _typeCoercer);
+
+        _component = _coreResources.getComponent();
+
+        String componentClassName = _component.getClass().getName();
+
+        // A page (really, the root component of a page) does not have a container.
+
+        if (container == null)
+        {
+            _completeId = componentClassName;
+            _nestedId = null;
+        }
+        else
+        {
+            String parentNestedId = container.getNestedId();
+
+            // The root element has no nested id.
+            // The children of the root element have an id.
+
+            if (parentNestedId == null)
             {
-                queue.push(_setupRender);
+                _nestedId = id;
+                _completeId = _page.getName() + ":" + id;
             }
             else
             {
-                _rendering = false;
+                _nestedId = parentNestedId + "." + id;
+                _completeId = container.getCompleteId() + "." + id;
+            }
+        }
+    }
 
-                // Order here should not matter.
+    /**
+     * Constructor for the root component of a page.
+     */
+    public ComponentPageElementImpl(Page page, Instantiator instantiator, TypeCoercer typeCoercer)
+    {
+        this(page, null, null, instantiator, typeCoercer, null);
+    }
 
-                for (Component component : _components)
-                    component.postRenderCleanup();
-            }
+    public void addEmbeddedElement(ComponentPageElement child)
+    {
+        if (_children == null)
+            _children = newMap();
+
+        String childId = child.getId();
+
+        // TODO: Check for conflicts!
+
+        _children.put(childId, child);
+    }
+
+    public void addMixin(Instantiator instantiator)
+    {
+        if (_mixinsByShortName == null)
+        {
+            _mixinsByShortName = newMap();
+            _components = newList();
         }
 
-        @Override
-        public String toString()
+        String mixinClassName = instantiator.getModel().getComponentClassName();
+        String mixinName = IOCUtilities.toSimpleId(mixinClassName);
+
+        InternalComponentResourcesImpl resources = new InternalComponentResourcesImpl(this,
+                instantiator, _typeCoercer);
+
+        // TODO: Check for name collision?
+
+        _mixinsByShortName.put(mixinName, resources);
+
+        _components.add(resources.getComponent());
+    }
+
+    public void addParameter(String parameterName, Binding binding)
+    {
+        // Maybe should use colon here? Depends on what works best in the template,
+        // don't want to lock this out as just
+        int dotx = parameterName.lastIndexOf('.');
+
+        if (dotx > 0)
         {
-            return String.format("CleanupRender[%s]", _completeId);
+            String mixinName = parameterName.substring(0, dotx);
+            InternalComponentResources mixinResources = InternalUtils.get(
+                    _mixinsByShortName,
+                    mixinName);
+
+            if (mixinResources == null)
+                throw new TapestryException(StructureMessages.missingMixinForParameter(
+                        _completeId,
+                        mixinName,
+                        parameterName), binding, null);
+
+            String simpleName = parameterName.substring(dotx + 1);
+
+            mixinResources.addParameter(simpleName, binding);
         }
-    };
 
-    /** Pushes the SetupRender phase state onto the queue. */
-    public final void render(MarkupWriter writer, RenderQueue queue)
+        // Does it match a formal parameter name of the core component? That takes precedence
+
+        if (_coreResources.getComponentModel().getParameterModel(parameterName) != null)
+        {
+            _coreResources.addParameter(parameterName, binding);
+            return;
+        }
+
+        for (String mixinName : InternalUtils.sortedKeys(_mixinsByShortName))
+        {
+            InternalComponentResources resources = _mixinsByShortName.get(mixinName);
+            if (resources.getComponentModel().getParameterModel(parameterName) != null)
+            {
+                resources.addParameter(parameterName, binding);
+                return;
+            }
+        }
+
+        // For the moment, informal parameters accumulate in the core component's resources, but
+        // that will likely change.
+
+        _coreResources.addParameter(parameterName, binding);
+    }
+
+    public void addToBody(PageElement element)
+    {
+        if (_body == null)
+            _body = newList();
+
+        _body.add(element);
+    }
+
+    public void addToTemplate(PageElement element)
+    {
+        _template.add(element);
+    }
+
+    public void containingPageDidAttach()
+    {
+        invoke(false, CONTAINING_PAGE_DID_ATTACH);
+    }
+
+    public void containingPageDidDetach()
     {
-        queue.push(_setupRender);
+        invoke(false, CONTAINING_PAGE_DID_DETACH);
     }
 
-    private int size(List<?> list)
+    public void containingPageDidLoad()
     {
-        return list == null ? 0 : list.size();
+        verifyRequiredParametersAreBound();
+
+        _loaded = true;
+
+        // If this component has mixins, add the core component to the end of the list, after the
+        // mixins.
+
+        if (_components != null)
+            _components.add(_component);
+
+        invoke(false, CONTAINING_PAGE_DID_LOAD);
     }
 
-    private void pushElements(RenderQueue queue, List<PageElement> list)
+    /**
+     * Delegates to the
+     * {@link Page#createActionLink(ComponentPageElement, String, boolean, Object[]) the containing page}.
+     * Why the extra layer? Because
+     */
+    public Link createActionLink(String action, boolean forForm, Object... context)
     {
-        int count = size(list);
-        for (int i = count - 1; i >= 0; i--)
-            queue.push(list.get(i));
+        return _page.createActionLink(this, action, forForm, context);
     }
 
     public void enqueueBeforeRenderBody(RenderQueue queue)
@@ -561,10 +590,9 @@
             queue.push(_beforeRenderBody);
     }
 
-    @Override
-    public String toString()
+    public String getCompleteId()
     {
-        return String.format("ComponentPageElement[%s]", _completeId);
+        return _completeId;
     }
 
     public Component getComponent()
@@ -572,113 +600,94 @@
         return _component;
     }
 
-    public boolean isRendering()
+    public InternalComponentResources getComponentResources()
     {
-        return _rendering;
+        return _coreResources;
     }
 
-    public void containingPageDidAttach()
+    public ComponentPageElement getContainer()
     {
-        for (Component component : _components)
-            component.containingPageDidAttach();
+        return _container;
     }
 
-    public void containingPageDidDetach()
+    public Page getContainingPage()
     {
-        for (Component component : _components)
-            component.containingPageDidDetach();
+        return _page;
     }
 
-    public boolean isLoaded()
+    public Component getEmbeddedComponent(String embeddedId)
     {
-        return _loaded;
+        return getEmbeddedElement(embeddedId).getComponent();
     }
 
-    public void containingPageDidLoad()
+    public ComponentPageElement getEmbeddedElement(String embeddedId)
     {
-        verifyRequiredParametersAreBound();
-
-        _loaded = true;
-
-        // Add the core component in *after* all the mixins
-
-        _components.add(_component);
+        ComponentPageElement embeddedElement = InternalUtils.get(_children, embeddedId);
 
-        for (Component component : _components)
-            component.containingPageDidLoad();
+        if (embeddedElement == null)
+            throw new IllegalArgumentException(StructureMessages.noSuchComponent(this, embeddedId));
 
+        return embeddedElement;
     }
 
-    private void verifyRequiredParametersAreBound()
+    public Object getFieldChange(String fieldName)
     {
-        List<String> unbound = newList();
-
-        addUnboundParameterNames(null, unbound, _coreResources);
-
-        for (String name : InternalUtils.sortedKeys(_mixinsByShortName))
-            addUnboundParameterNames(name, unbound, _mixinsByShortName.get(name));
+        return _page.getFieldChange(this, fieldName);
+    }
 
-        if (unbound.isEmpty())
-            return;
+    public String getId()
+    {
+        return _id;
+    }
 
-        throw new TapestryException(StructureMessages.missingParameters(unbound, this), this, null);
+    public Log getLog()
+    {
+        return _coreResources.getLog();
     }
 
-    private void addUnboundParameterNames(String prefix, List<String> unbound,
-            InternalComponentResources resource)
+    public Component getMixinByClassName(String mixinClassName)
     {
-        ComponentModel model = resource.getComponentModel();
+        Component result = null;
 
-        for (String name : model.getParameterNames())
+        if (_mixinsByShortName != null)
         {
-            if (resource.isBound(name))
-                continue;
-
-            ParameterModel parameterModel = model.getParameterModel(name);
-
-            if (parameterModel.isRequired())
+            for (InternalComponentResources resources : _mixinsByShortName.values())
             {
-                String fullName = prefix == null ? name : prefix + "." + name;
-
-                unbound.add(fullName);
+                if (resources.getComponentModel().getComponentClassName().equals(mixinClassName))
+                {
+                    result = resources.getComponent();
+                    break;
+                }
             }
         }
+
+        if (result == null)
+            throw new IllegalArgumentException(StructureMessages.unknownMixin(
+                    _completeId,
+                    mixinClassName));
+
+        return result;
     }
 
-    /**
-     * Delegates to the
-     * {@link Page#createActionLink(ComponentPageElement, String, boolean, Object[]) the containing page}.
-     * Why the extra layer? Because
-     */
-    public Link createActionLink(String action, boolean forForm, Object... context)
+    public String getNestedId()
     {
-        return _page.createActionLink(this, action, forForm, context);
+        return _nestedId;
     }
 
-    public boolean triggerEvent(String eventType, Object[] context, ComponentEventHandler handler)
+    public Component getPage()
     {
-        boolean result = false;
-
-        ComponentEvent event = new ComponentEventImpl(eventType, _id, context, handler,
-                _typeCoercer);
-
-        ComponentPageElement component = this;
-
-        while (component != null)
-        {
-            result |= component.handleEvent(event);
-
-            if (event.isAborted())
-                return result;
-
-            component = component.getContainer();
-        }
-
-        return result;
+        return _page.getRootElement().getComponent();
     }
 
     public boolean handleEvent(ComponentEvent event)
     {
+        // Simple case: no mixins
+
+        if (_components == null)
+            return _component.handleComponentEvent(event);
+
+        // Otherwise, iterate over mixins + core component
+
         boolean result = false;
 
         for (Component component : _components)
@@ -692,14 +701,19 @@
         return result;
     }
 
-    public ComponentPageElement getEmbeddedElement(String embeddedId)
+    public boolean hasFieldChange(String fieldName)
     {
-        ComponentPageElement embeddedElement = InternalUtils.get(_children, embeddedId);
+        return getFieldChange(fieldName) != null;
+    }
 
-        if (embeddedElement == null)
-            throw new IllegalArgumentException(StructureMessages.noSuchComponent(this, embeddedId));
+    public boolean isLoaded()
+    {
+        return _loaded;
+    }
 
-        return embeddedElement;
+    public boolean isRendering()
+    {
+        return _rendering;
     }
 
     public void persistFieldChange(String fieldName, Object newValue)
@@ -711,65 +725,63 @@
             _page.persistFieldChange(this, fieldName, newValue);
     }
 
-    public Object getFieldChange(String fieldName)
+    /** Pushes the SetupRender phase state onto the queue. */
+    public final void render(MarkupWriter writer, RenderQueue queue)
     {
-        return _page.getFieldChange(this, fieldName);
+        // Once we start rendering, the page is considered dirty, until we cleanup post render.
+
+        _page.incrementDirtyCount();
+
+        queue.push(_setupRender);
     }
 
-    public boolean hasFieldChange(String fieldName)
+    @Override
+    public String toString()
     {
-        return getFieldChange(fieldName) != null;
+        return String.format("ComponentPageElement[%s]", _completeId);
     }
 
-    public void addMixin(Instantiator instantiator)
+    public boolean triggerEvent(String eventType, Object[] context, ComponentEventHandler handler)
     {
-        if (_mixinsByShortName == null)
-            _mixinsByShortName = newMap();
+        boolean result = false;
 
-        String mixinClassName = instantiator.getModel().getComponentClassName();
-        String mixinName = IOCUtilities.toSimpleId(mixinClassName);
+        ComponentEvent event = new ComponentEventImpl(eventType, _id, context, handler,
+                _typeCoercer);
 
-        InternalComponentResourcesImpl resources = new InternalComponentResourcesImpl(this,
-                instantiator, _typeCoercer);
+        ComponentPageElement component = this;
 
-        // TODO: Check for name collision?
+        while (component != null)
+        {
+            result |= component.handleEvent(event);
 
-        _mixinsByShortName.put(mixinName, resources);
-        _components.add(resources.getComponent());
-    }
+            if (event.isAborted())
+                return result;
 
-    public InternalComponentResources getComponentResources()
-    {
-        return _coreResources;
-    }
+            component = component.getContainer();
+        }
 
-    public Log getLog()
-    {
-        return _coreResources.getLog();
+        return result;
     }
 
-    public Component getMixinByClassName(String mixinClassName)
+    private void addUnboundParameterNames(String prefix, List<String> unbound,
+            InternalComponentResources resource)
     {
-        Component result = null;
+        ComponentModel model = resource.getComponentModel();
 
-        if (_mixinsByShortName != null)
+        for (String name : model.getParameterNames())
         {
-            for (InternalComponentResources resources : _mixinsByShortName.values())
+            if (resource.isBound(name))
+                continue;
+
+            ParameterModel parameterModel = model.getParameterModel(name);
+
+            if (parameterModel.isRequired())
             {
-                if (resources.getComponentModel().getComponentClassName().equals(mixinClassName))
-                {
-                    result = resources.getComponent();
-                    break;
-                }
+                String fullName = prefix == null ? name : prefix + "." + name;
+
+                unbound.add(fullName);
             }
         }
-
-        if (result == null)
-            throw new IllegalArgumentException(StructureMessages.unknownMixin(
-                    _completeId,
-                    mixinClassName));
-
-        return result;
     }
 
     /**
@@ -786,9 +798,9 @@
         // Optimization: In the most general case (just the one component, no mixins)
         // invoke the callback on the component and be done ... no iterators, no nothing.
 
-        if (_components.size() == 1)
+        if (_components == null)
         {
-            callback.run(_coreResources.getComponent());
+            callback.run(_component);
             return;
         }
 
@@ -797,6 +809,38 @@
 
         while (i.hasNext())
             callback.run(i.next());
+    }
+
+    private LifecycleEvent<Boolean> newEvent(boolean defaultValue)
+    {
+        return new LifecycleEvent<Boolean>(_log, Boolean.class, defaultValue);
+    }
+
+    private static void pushElements(RenderQueue queue, List<PageElement> list)
+    {
+        int count = size(list);
+        for (int i = count - 1; i >= 0; i--)
+            queue.push(list.get(i));
+    }
+
+    private static int size(List<?> list)
+    {
+        return list == null ? 0 : list.size();
+    }
+
+    private void verifyRequiredParametersAreBound()
+    {
+        List<String> unbound = newList();
+
+        addUnboundParameterNames(null, unbound, _coreResources);
+
+        for (String name : InternalUtils.sortedKeys(_mixinsByShortName))
+            addUnboundParameterNames(name, unbound, _mixinsByShortName.get(name));
+
+        if (unbound.isEmpty())
+            return;
+
+        throw new TapestryException(StructureMessages.missingParameters(unbound, this), this, null);
     }
 
 }

Modified: tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/structure/Page.java
URL: http://svn.apache.org/viewvc/tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/structure/Page.java?view=diff&rev=471819&r1=471818&r2=471819
==============================================================================
--- tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/structure/Page.java (original)
+++ tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/structure/Page.java Mon Nov  6 10:45:06 2006
@@ -62,10 +62,17 @@
     /**
      * Invoked to inform the page that it is being detached from the current request. This occurs
      * just before the page is returned to the page pool.
+     * <p>
+     * A page may be clean or dirty. A page is dirty if its dirty count is greater than zero
+     * (meaning that, during the render of the page, some components did not fully render), or if
+     * any of its listeners throw an exception from containingPageDidDetech().
+     * <p>
+     * The page pool should discard pages that are dirty, rather than store them into the pool.
      * 
+     * @return true if the page is "clean", false otherwise
      * @see org.apache.tapestry.runtime.PageLifecycleListener#containingPageDidDetach()
      */
-    void detached();
+    boolean detached();
 
     /**
      * Invoked to inform the page that it is attached to the current request. This occurs when a
@@ -133,4 +140,14 @@
      * @return the value, or null if no value is stored
      */
     Object getFieldChange(ComponentPageElement element, String fieldName);
+
+    /**
+     * Called as a component initially starts to render itself. This is used to check for the cases
+     * where a component causes a runtime exception that aborts the render early, leaving the page
+     * in an invalid state.
+     */
+    void incrementDirtyCount();
+
+    /** Called as a component finishes rendering itself. */
+    void decrementDirtyCount();
 }

Modified: tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/structure/PageImpl.java
URL: http://svn.apache.org/viewvc/tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/structure/PageImpl.java?view=diff&rev=471819&r1=471818&r2=471819
==============================================================================
--- tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/structure/PageImpl.java (original)
+++ tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/structure/PageImpl.java Mon Nov  6 10:45:06 2006
@@ -40,6 +40,8 @@
 
     private final List<PageLifecycleListener> _listeners = newList();
 
+    private int _dirtyCount;
+
     /**
      * Obtained from the {@link PersistentFieldManager} when first needed, discarded at the end of
      * the request.
@@ -96,12 +98,26 @@
         _listeners.add(listener);
     }
 
-    public void detached()
+    public boolean detached()
     {
+        boolean result = _dirtyCount > 0;
+
         for (PageLifecycleListener listener : _listeners)
-            listener.containingPageDidDetach();
+        {
+            try
+            {
+                listener.containingPageDidDetach();
+            }
+            catch (RuntimeException ex)
+            {
+                getLog().error(StructureMessages.detachFailure(listener, ex), ex);
+                result = true;
+            }
+        }
 
         _fieldBundle = null;
+
+        return result;
     }
 
     public void loaded()
@@ -112,13 +128,16 @@
 
     public void attached()
     {
+        if (_dirtyCount != 0)
+            throw new IllegalStateException("Page was stored into the page pool in a dirty state.");
+
         for (PageLifecycleListener listener : _listeners)
             listener.containingPageDidAttach();
     }
 
     public Log getLog()
     {
-        return _rootElement.getComponentResources().getLog();
+        return _rootElement.getLog();
     }
 
     public Link createActionLink(ComponentPageElement element, String action, boolean forForm,
@@ -143,6 +162,16 @@
             _fieldBundle = _persistentFieldManager.gatherChanges(_name);
 
         return _fieldBundle.getValue(element.getNestedId(), fieldName);
+    }
+
+    public void decrementDirtyCount()
+    {
+        _dirtyCount--;
+    }
+
+    public void incrementDirtyCount()
+    {
+        _dirtyCount++;
     }
 
 }

Modified: tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/structure/StructureMessages.java
URL: http://svn.apache.org/viewvc/tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/structure/StructureMessages.java?view=diff&rev=471819&r1=471818&r2=471819
==============================================================================
--- tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/structure/StructureMessages.java (original)
+++ tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/structure/StructureMessages.java Mon Nov  6 10:45:06 2006
@@ -60,4 +60,9 @@
     {
         return MESSAGES.format("unknown-mixin", componentId, mixinClassName);
     }
+
+    static String detachFailure(Object listener, Throwable cause)
+    {
+        return MESSAGES.format("detach-failure", listener, cause);
+    }
 }

Modified: tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/util/AcceptVoidEventHandler.java
URL: http://svn.apache.org/viewvc/tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/util/AcceptVoidEventHandler.java?view=diff&rev=471819&r1=471818&r2=471819
==============================================================================
--- tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/util/AcceptVoidEventHandler.java (original)
+++ tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/internal/util/AcceptVoidEventHandler.java Mon Nov  6 10:45:06 2006
@@ -15,6 +15,7 @@
 package org.apache.tapestry.internal.util;
 
 import org.apache.tapestry.ComponentEventHandler;
+import org.apache.tapestry.runtime.Component;
 
 /**
  * A {@link ComponentEventHandler} that does not accept any value. This is used when an event is
@@ -32,7 +33,7 @@
         _completeId = completeId;
     }
 
-    public void handleResult(Object result, String methodDescription)
+    public void handleResult(Object result, Component component, String methodDescription)
     {
         // Don't even need a null check because this is only invoked if a method returns non-null.
 

Modified: tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/runtime/ComponentEvent.java
URL: http://svn.apache.org/viewvc/tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/runtime/ComponentEvent.java?view=diff&rev=471819&r1=471818&r2=471819
==============================================================================
--- tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/runtime/ComponentEvent.java (original)
+++ tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/runtime/ComponentEvent.java Mon Nov  6 10:45:06 2006
@@ -56,9 +56,11 @@
      * {@link #storeResult(Object, String)} to identify, to the event, what method is being acted
      * upon (used for some kinds of exception reporting).
      * 
+     * @param component
+     *            the component instance from which the result was obtained
      * @param methodDescription
      */
-    void setMethod(String methodDescription);
+    void setSource(Component component, String methodDescription);
 
     /**
      * Stores a result for the event. Storing a non-null result value will abort the event.

Modified: tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/runtime/LifecycleEvent.java
URL: http://svn.apache.org/viewvc/tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/runtime/LifecycleEvent.java?view=diff&rev=471819&r1=471818&r2=471819
==============================================================================
--- tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/runtime/LifecycleEvent.java (original)
+++ tapestry/tapestry5/tapestry-core/trunk/src/main/java/org/apache/tapestry/runtime/LifecycleEvent.java Mon Nov  6 10:45:06 2006
@@ -23,7 +23,9 @@
  * which terminates the chain (potentially skipping some of the method invocations).
  * <p>
  * TODO: It's beginning to look like LifecycleEvents will always accept only boolean values, so we
- * may want to un-genericize this type.
+ * may want to un-genericize this type. Alternately, the return type may include strings (component
+ * ids) or component instances, which also will cause grief. This class should probably merge
+ * together with {@link ComponentEvent}.
  */
 public final class LifecycleEvent<T>
 {

Modified: tapestry/tapestry5/tapestry-core/trunk/src/main/resources/org/apache/tapestry/internal/services/ServicesStrings.properties
URL: http://svn.apache.org/viewvc/tapestry/tapestry5/tapestry-core/trunk/src/main/resources/org/apache/tapestry/internal/services/ServicesStrings.properties?view=diff&rev=471819&r1=471818&r2=471819
==============================================================================
--- tapestry/tapestry5/tapestry-core/trunk/src/main/resources/org/apache/tapestry/internal/services/ServicesStrings.properties (original)
+++ tapestry/tapestry5/tapestry-core/trunk/src/main/resources/org/apache/tapestry/internal/services/ServicesStrings.properties Mon Nov  6 10:45:06 2006
@@ -56,4 +56,5 @@
 could-not-resolve-page-name=Unable to resolve page '%s' to a component class name.
 could-not-resolve-component-type=Unable to resolve component type '%s' to a component class name.
 could-not-resolve-mixin-type=Unable to resolve mixin type '%s' to a component class name.
-parameter-name-must-be-unique=Parameter names are required to be unique.  Parameter '%s' already has the value '%s'.
\ No newline at end of file
+parameter-name-must-be-unique=Parameter names are required to be unique.  Parameter '%s' already has the value '%s'.
+page-is-dirty=Page %s is dirty, and will be discarded (rather than returned to the page pool).
\ No newline at end of file

Modified: tapestry/tapestry5/tapestry-core/trunk/src/main/resources/org/apache/tapestry/internal/structure/StructureStrings.properties
URL: http://svn.apache.org/viewvc/tapestry/tapestry5/tapestry-core/trunk/src/main/resources/org/apache/tapestry/internal/structure/StructureStrings.properties?view=diff&rev=471819&r1=471818&r2=471819
==============================================================================
--- tapestry/tapestry5/tapestry-core/trunk/src/main/resources/org/apache/tapestry/internal/structure/StructureStrings.properties (original)
+++ tapestry/tapestry5/tapestry-core/trunk/src/main/resources/org/apache/tapestry/internal/structure/StructureStrings.properties Mon Nov  6 10:45:06 2006
@@ -17,4 +17,5 @@
 get-parameter-failure=Failure reading parameter %s of component %s: %s
 write-parameter-failure=Failure writing parameter %s of component %s: %s
 missing-mixin-for-parameter=Component %s does not contain a mixin named '%s' (setting parameter '%s').
-unknown-mixin=Component %s does not contain a mixin of type %s.
\ No newline at end of file
+unknown-mixin=Component %s does not contain a mixin of type %s.
+detach-failure=Listener %s failed during page detach: %s

Modified: tapestry/tapestry5/tapestry-core/trunk/src/test/java/org/apache/tapestry/internal/services/ComponentEventImplTest.java
URL: http://svn.apache.org/viewvc/tapestry/tapestry5/tapestry-core/trunk/src/test/java/org/apache/tapestry/internal/services/ComponentEventImplTest.java?view=diff&rev=471819&r1=471818&r2=471819
==============================================================================
--- tapestry/tapestry5/tapestry-core/trunk/src/test/java/org/apache/tapestry/internal/services/ComponentEventImplTest.java (original)
+++ tapestry/tapestry5/tapestry-core/trunk/src/test/java/org/apache/tapestry/internal/services/ComponentEventImplTest.java Mon Nov  6 10:45:06 2006
@@ -98,7 +98,7 @@
         ComponentEvent event = new ComponentEventImpl("eventType", "someId", new String[]
         { "27" }, handler, _coercer);
 
-        event.setMethod("foo.Bar.baz()");
+        event.setSource(null, "foo.Bar.baz()");
 
         try
         {
@@ -124,7 +124,7 @@
         ComponentEvent event = new ComponentEventImpl("eventType", "someId", new String[]
         { "abc" }, handler, _coercer);
 
-        event.setMethod("foo.Bar.baz()");
+        event.setSource(null, "foo.Bar.baz()");
 
         try
         {
@@ -151,14 +151,14 @@
 
         ComponentEventHandler handler = newComponentEventHandler();
 
-        handler.handleResult(result, methodDescription);
+        handler.handleResult(result, null, methodDescription);
 
         replay();
 
         ComponentEvent event = new ComponentEventImpl("eventType", "someId", null, handler,
                 _coercer);
 
-        event.setMethod(methodDescription);
+        event.setSource(null, methodDescription);
 
         assertFalse(event.isAborted());
 
@@ -197,19 +197,19 @@
         Object result = new Object();
         ComponentEventHandler handler = newComponentEventHandler();
 
-        handler.handleResult(result, "foo.Bar.baz()");
+        handler.handleResult(result, null, "foo.Bar.baz()");
 
         replay();
 
         ComponentEvent event = new ComponentEventImpl("eventType", "someId", null, handler,
                 _coercer);
 
-        event.setMethod("foo.Bar.baz()");
+        event.setSource(null, "foo.Bar.baz()");
         event.storeResult(result);
 
         try
         {
-            event.setMethod("foo.Bar.biff()");
+            event.setSource(null, "foo.Bar.biff()");
             event.storeResult(null);
             unreachable();
         }

Modified: tapestry/tapestry5/tapestry-core/trunk/src/test/java/org/apache/tapestry/internal/services/OnEventWorkerTest.java
URL: http://svn.apache.org/viewvc/tapestry/tapestry5/tapestry-core/trunk/src/test/java/org/apache/tapestry/internal/services/OnEventWorkerTest.java?view=diff&rev=471819&r1=471818&r2=471819
==============================================================================
--- tapestry/tapestry5/tapestry-core/trunk/src/test/java/org/apache/tapestry/internal/services/OnEventWorkerTest.java (original)
+++ tapestry/tapestry5/tapestry-core/trunk/src/test/java/org/apache/tapestry/internal/services/OnEventWorkerTest.java Mon Nov  6 10:45:06 2006
@@ -80,7 +80,7 @@
                 "{",
                 BOILERPLATE_1,
                 BOILERPLATE_2,
-                "$1.setMethod(\"foo.Bar.foo()\");",
+                "$1.setSource(this, \"foo.Bar.foo()\");",
                 "foo();",
                 "}");
 
@@ -124,7 +124,7 @@
                 "if ($1.matchesByEventType(_v))",
                 "{",
                 BOILERPLATE_2,
-                "$1.setMethod(\"foo.Bar.foo()\");",
+                "$1.setSource(this, \"foo.Bar.foo()\");",
                 "foo();",
                 "}",
                 "}");
@@ -170,7 +170,7 @@
                 "if ($1.matchesByComponentId(_res, _ids))",
                 "{",
                 BOILERPLATE_2,
-                "$1.setMethod(\"foo.Bar.foo()\");",
+                "$1.setSource(this, \"foo.Bar.foo()\");",
                 "foo();",
                 "}",
                 "}");
@@ -223,7 +223,7 @@
                 "if ($1.matchesByComponentId(_res, _ids))",
                 "{",
                 BOILERPLATE_2,
-                "$1.setMethod(\"foo.Bar.foo()\");",
+                "$1.setSource(this, \"foo.Bar.foo()\");",
                 "foo();",
                 "}",
                 "}",
@@ -263,7 +263,7 @@
                 "{",
                 BOILERPLATE_1,
                 BOILERPLATE_2,
-                "$1.setMethod(\"foo.Bar.foo()\");",
+                "$1.setSource(this, \"foo.Bar.foo()\");",
                 "if ($1.storeResult(foo()) return;",
                 "}");
 
@@ -301,7 +301,7 @@
                 "{",
                 BOILERPLATE_1,
                 BOILERPLATE_2,
-                "$1.setMethod(\"foo.Bar.foo(java.lang.String)\");",
+                "$1.setSource(this, \"foo.Bar.foo(java.lang.String)\");",
                 "foo($1.coerceContext(0, \"java.lang.String\"));",
                 "}");
 
@@ -339,7 +339,7 @@
                 "{",
                 BOILERPLATE_1,
                 BOILERPLATE_2,
-                "$1.setMethod(\"foo.Bar.foo(boolean)\");",
+                "$1.setSource(this, \"foo.Bar.foo(boolean)\");",
                 "foo(((java.lang.Boolean)$1.coerceContext(0, \"java.lang.Boolean\")).booleanValue());",
                 "}");
 
@@ -378,7 +378,7 @@
                 "{",
                 BOILERPLATE_1,
                 BOILERPLATE_2,
-                "$1.setMethod(\"foo.Bar.foo(java.lang.String, java.lang.Integer)\");",
+                "$1.setSource(this, \"foo.Bar.foo(java.lang.String, java.lang.Integer)\");",
                 "foo($1.coerceContext(0, \"java.lang.String\"), ",
                 "$1.coerceContext(1, \"java.lang.Integer\"));",
                 "}");

Modified: tapestry/tapestry5/tapestry-core/trunk/src/test/java/org/apache/tapestry/internal/services/PagePoolImplTest.java
URL: http://svn.apache.org/viewvc/tapestry/tapestry5/tapestry-core/trunk/src/test/java/org/apache/tapestry/internal/services/PagePoolImplTest.java?view=diff&rev=471819&r1=471818&r2=471819
==============================================================================
--- tapestry/tapestry5/tapestry-core/trunk/src/test/java/org/apache/tapestry/internal/services/PagePoolImplTest.java (original)
+++ tapestry/tapestry5/tapestry-core/trunk/src/test/java/org/apache/tapestry/internal/services/PagePoolImplTest.java Mon Nov  6 10:45:06 2006
@@ -14,8 +14,11 @@
 
 package org.apache.tapestry.internal.services;
 
+import static org.easymock.EasyMock.contains;
+
 import java.util.Locale;
 
+import org.apache.commons.logging.Log;
 import org.apache.tapestry.internal.structure.Page;
 import org.apache.tapestry.internal.test.InternalBaseTestCase;
 import org.testng.annotations.Test;
@@ -41,7 +44,7 @@
 
         replay();
 
-        PagePool pool = new PagePoolImpl(loader);
+        PagePool pool = new PagePoolImpl(null, loader);
 
         assertSame(page, pool.checkout(PAGE_NAME));
 
@@ -55,14 +58,14 @@
         Page page1 = newPage();
         Page page2 = newPage();
 
-        page1.detached();
+        train_detached(page1, false);
         train_getName(page1, PAGE_NAME);
 
         train_loadPage(loader, PAGE_NAME, _locale, page2);
 
         replay();
 
-        PagePool pool = new PagePoolImpl(loader);
+        PagePool pool = new PagePoolImpl(null, loader);
 
         pool.release(page1);
 
@@ -75,6 +78,13 @@
         verify();
     }
 
+    protected final void train_detached(Page page, boolean dirty)
+    {
+        page.detached();
+
+        setReturnValue(dirty);
+    }
+
     @Test
     public void release_last_in_first_out()
     {
@@ -82,23 +92,45 @@
         Page page1 = newPage();
         Page page2 = newPage();
 
-        page1.detached();
+        train_detached(page1, false);
 
         train_getName(page1, PAGE_NAME);
 
-        page2.detached();
+        train_detached(page2, false);
 
         train_getName(page2, PAGE_NAME);
 
         replay();
 
-        PagePool pool = new PagePoolImpl(loader);
+        PagePool pool = new PagePoolImpl(null, loader);
 
         pool.release(page1);
         pool.release(page2);
 
         assertSame(page2, pool.checkout(PAGE_NAME));
         assertSame(page1, pool.checkout(PAGE_NAME));
+
+        verify();
+    }
+
+    @Test
+    public void dirty_pages_are_not_pooled()
+    {
+        PageLoader loader = newPageLoader();
+        Page page = newPage();
+        Log log = newLog();
+
+        train_detached(page, true);
+
+        log.error(contains("is dirty, and will be discarded"));
+
+        // The fact that we don't ask the page for its name is our clue that it is not being cached.
+
+        replay();
+
+        PagePool pool = new PagePoolImpl(log, loader);
+
+        pool.release(page);
 
         verify();
     }

Modified: tapestry/tapestry5/tapestry-core/trunk/src/test/java/org/apache/tapestry/internal/structure/PageImplTest.java
URL: http://svn.apache.org/viewvc/tapestry/tapestry5/tapestry-core/trunk/src/test/java/org/apache/tapestry/internal/structure/PageImplTest.java?view=diff&rev=471819&r1=471818&r2=471819
==============================================================================
--- tapestry/tapestry5/tapestry-core/trunk/src/test/java/org/apache/tapestry/internal/structure/PageImplTest.java (original)
+++ tapestry/tapestry5/tapestry-core/trunk/src/test/java/org/apache/tapestry/internal/structure/PageImplTest.java Mon Nov  6 10:45:06 2006
@@ -14,8 +14,12 @@
 
 package org.apache.tapestry.internal.structure;
 
+import static org.easymock.EasyMock.contains;
+import static org.easymock.EasyMock.same;
+
 import java.util.Locale;
 
+import org.apache.commons.logging.Log;
 import org.apache.tapestry.internal.test.InternalBaseTestCase;
 import org.apache.tapestry.runtime.PageLifecycleListener;
 import org.testng.annotations.Test;
@@ -62,9 +66,71 @@
         page.addLifecycleListener(listener1);
         page.addLifecycleListener(listener2);
 
-        page.detached();
+        assertFalse(page.detached());
 
         verify();
+    }
+
+    /** Also checks that listeners are invoked, even if the page is dirty. */
+    @Test
+    public void detach_dirty_if_dirty_count_non_zero()
+    {
+        PageLifecycleListener listener = newPageLifecycle();
+
+        listener.containingPageDidDetach();
+
+        replay();
+
+        Page page = new PageImpl(PAGE_NAME, _locale, null, null);
+
+        page.addLifecycleListener(listener);
+
+        page.incrementDirtyCount();
+
+        assertTrue(page.detached());
+
+        verify();
+    }
+
+    /**
+     * Also checks that all listeners are invoked, even if one of them throws an exception.
+     */
+    @Test
+    public void detach_dirty_if_listener_throws_exception()
+    {
+        ComponentPageElement element = newComponentPageElement();
+        Log log = newLog();
+        PageLifecycleListener listener1 = newPageLifecycle();
+        PageLifecycleListener listener2 = newPageLifecycle();
+        RuntimeException t = new RuntimeException("Listener detach exception.");
+
+        train_getLog(element, log);
+
+        listener1.containingPageDidDetach();
+        setThrowable(t);
+
+        log.error(contains("failed during page detach"), same(t));
+
+        listener2.containingPageDidDetach();
+
+        replay();
+
+        Page page = new PageImpl(PAGE_NAME, _locale, null, null);
+        page.setRootElement(element);
+
+        page.addLifecycleListener(listener1);
+        page.addLifecycleListener(listener2);
+
+        assertTrue(page.detached());
+
+        verify();
+
+    }
+
+    protected final void train_getLog(ComponentPageElement element, Log log)
+    {
+        element.getLog();
+        setReturnValue(log);
     }
 
     @Test