You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@tapestry.apache.org by hl...@apache.org on 2012/08/02 02:57:35 UTC

git commit: Store the partial-page-render response elements inside a "_tapestry" key of the JSON response

Updated Branches:
  refs/heads/5.4-js-rewrite d9ec4eb89 -> 9dc4943d4


Store the partial-page-render response elements inside a "_tapestry" key of the JSON response


Project: http://git-wip-us.apache.org/repos/asf/tapestry-5/repo
Commit: http://git-wip-us.apache.org/repos/asf/tapestry-5/commit/9dc4943d
Tree: http://git-wip-us.apache.org/repos/asf/tapestry-5/tree/9dc4943d
Diff: http://git-wip-us.apache.org/repos/asf/tapestry-5/diff/9dc4943d

Branch: refs/heads/5.4-js-rewrite
Commit: 9dc4943d4828821cbeb6f3d37309c61938ba4a82
Parents: d9ec4eb
Author: Howard M. Lewis Ship <hl...@apache.org>
Authored: Wed Aug 1 17:57:22 2012 -0700
Committer: Howard M. Lewis Ship <hl...@apache.org>
Committed: Wed Aug 1 17:57:22 2012 -0700

----------------------------------------------------------------------
 .../META-INF/modules/core/pageinit.coffee          |   42 +-
 .../tapestry5/internal/InternalConstants.java      |   12 +-
 .../AjaxLinkComponentEventResultProcessor.java     |    5 +-
 .../services/DefaultRequestExceptionHandler.java   |  468 ++++++++-------
 .../services/PartialMarkupDocumentLinker.java      |   33 +-
 .../ajax/SingleZonePartialRendererFilter.java      |   15 +-
 .../resources/org/apache/tapestry5/tapestry.js     |   22 +-
 .../PartialMarkupDocumentLinkerTest.groovy         |    6 +-
 8 files changed, 323 insertions(+), 280 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/tapestry-5/blob/9dc4943d/tapestry-core/src/main/coffeescript/META-INF/modules/core/pageinit.coffee
----------------------------------------------------------------------
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/core/pageinit.coffee b/tapestry-core/src/main/coffeescript/META-INF/modules/core/pageinit.coffee
index 3935caf..458166b 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/core/pageinit.coffee
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/core/pageinit.coffee
@@ -136,39 +136,49 @@ define ["_", "core/console"], (_, console) ->
 
     # Passed the JSON object response from an Ajax request, when the request is succesful.
     # This is used for any request that attaches partial-page-render data to the main JSON object
-    # reponse.  If no such data is attached, the callback is simply invoked immediately.
+    # response.  If no such data is attached, the callback is simply invoked immediately.
     # Otherwise, Tapestry processes the partial-page-render data. This may involve loading some number
-    # of scripts and CSS style sheets, and a number of direct updates to the DOM. After DOM updates,
+    # of JavaScript libraries and CSS style sheets, and a number of direct updates to the DOM. After DOM updates,
     # the callback is invoked, passed the response (with any Tapestry-specific data removed).
     # After the callback is invoked, page initializations occur.  This method returns null.
     # response - the JSON response object
     # callback - invoked after scripts are loaded, but before page initializations occur (may be null)
     # context - optional: context used when invoking the callback
     handlePartialPageRenderResponse: (response, callback, context) ->
-      # Temporarily dealing with the 5.3 format before updating for 5.4:
+
+      # Capture the partial page response portion of the overall response, and
+      # then remove it so it doesn't interfere elsewhere.
+      partial = response._tapestry
+      delete response._tapestry
 
       # Extreme case: the data has a redirectURL which forces an immediate redirect to the URL.
       # No other initialization or callback invocation occurs.
-      if response.redirectURL
-        window.location.href = response.redirectURL
+      if partial?.redirectURL
+        window.location.href = partial.redirectURL
         return
 
-      addStylesheets response.stylesheets
-
-      exports.loadScripts response.scripts, ->
-        # TODO: Strip out Tapestry specific stuff from transport before invoking.
-        callback and callback.call context, response
-
-        exports.initialize response.inits, Tapestry.onDomLoadedCallback
-
-      return
-
-
+      addStylesheets partial?.stylesheets
 
+      # Make sure all libraries are loaded
+      exports.loadScripts partial?.libraries, ->
 
+        # Libraries are loaded, update each zone:
+        _(partial?.content).each ([id, content]) ->
+          # Looking forward to stripping out thie ZoneManager nonsense
+          console.debug "Updating content for zone #{id}"
 
+          zoneMgr = Tapestry.findZoneManagerForZone id
 
+          zoneMgr && zoneMgr.show content
 
+        # Invoke the callback, if present.  The callback may do its own content updates.
+        callback and callback.call context, response
 
+        # Now that all content updates are, presumably, complete, it is time to
+        # perform initializations.  Once those complete, use the onDomLoadedCallback()
+        # to do some final changes and event registrations (hopefully, to be removed
+        # soon).
 
+        exports.initialize partial?.inits, Tapestry.onDomLoadedCallback
 
+      return

http://git-wip-us.apache.org/repos/asf/tapestry-5/blob/9dc4943d/tapestry-core/src/main/java/org/apache/tapestry5/internal/InternalConstants.java
----------------------------------------------------------------------
diff --git a/tapestry-core/src/main/java/org/apache/tapestry5/internal/InternalConstants.java b/tapestry-core/src/main/java/org/apache/tapestry5/internal/InternalConstants.java
index b3b813a..6bf8f1b 100644
--- a/tapestry-core/src/main/java/org/apache/tapestry5/internal/InternalConstants.java
+++ b/tapestry-core/src/main/java/org/apache/tapestry5/internal/InternalConstants.java
@@ -1,4 +1,4 @@
-// Copyright 2006, 2007, 2008, 2009, 2010, 2011 The Apache Software Foundation
+// Copyright 2006-2012 The Apache Software Foundation
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -151,9 +151,17 @@ public final class InternalConstants
     /**
      * Request attribute that can be set to bypass page activation.
      *
-     * @since 5.4
      * @see org.apache.tapestry5.internal.services.StreamPageContentResultProcessor
      * @see org.apache.tapestry5.internal.services.PageRenderRequestHandlerImpl
+     * @since 5.4
      */
     public static final String BYPASS_ACTIVATION = "tapestry.bypass-page-activation";
+
+    /**
+     * Key inside the response that contains the partial page render keys that are used
+     * to update the client.
+     *
+     * @since 5.4
+     */
+    public static final String PARTIAL_KEY = "_tapestry";
 }

http://git-wip-us.apache.org/repos/asf/tapestry-5/blob/9dc4943d/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/AjaxLinkComponentEventResultProcessor.java
----------------------------------------------------------------------
diff --git a/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/AjaxLinkComponentEventResultProcessor.java b/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/AjaxLinkComponentEventResultProcessor.java
index 39288ca..ada06d9 100644
--- a/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/AjaxLinkComponentEventResultProcessor.java
+++ b/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/AjaxLinkComponentEventResultProcessor.java
@@ -1,4 +1,4 @@
-//  Copyright 2008, 2010 The Apache Software Foundation
+//  Copyright 2008, 2010, 2012 The Apache Software Foundation
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -15,6 +15,7 @@
 package org.apache.tapestry5.internal.services;
 
 import org.apache.tapestry5.Link;
+import org.apache.tapestry5.internal.InternalConstants;
 import org.apache.tapestry5.json.JSONObject;
 import org.apache.tapestry5.services.Ajax;
 import org.apache.tapestry5.services.ComponentEventResultProcessor;
@@ -38,7 +39,7 @@ public class AjaxLinkComponentEventResultProcessor implements ComponentEventResu
     {
         JSONObject response = new JSONObject();
 
-        response.put("redirectURL", value.toRedirectURI());
+        response.in(InternalConstants.PARTIAL_KEY).put("redirectURL", value.toRedirectURI());
 
         masterProcessor.processResultValue(response);
     }

http://git-wip-us.apache.org/repos/asf/tapestry-5/blob/9dc4943d/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/DefaultRequestExceptionHandler.java
----------------------------------------------------------------------
diff --git a/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/DefaultRequestExceptionHandler.java b/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/DefaultRequestExceptionHandler.java
index 20101f8..969c756 100644
--- a/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/DefaultRequestExceptionHandler.java
+++ b/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/DefaultRequestExceptionHandler.java
@@ -1,221 +1,247 @@
-// Copyright 2006, 2008, 2010, 2011 The Apache Software Foundation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package org.apache.tapestry5.internal.services;
-
-import java.io.IOException;
-import java.io.OutputStream;
-import java.net.URLEncoder;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.tapestry5.ContextAwareException;
-import org.apache.tapestry5.ExceptionHandlerAssistant;
-import org.apache.tapestry5.Link;
-import org.apache.tapestry5.SymbolConstants;
-import org.apache.tapestry5.internal.structure.Page;
-import org.apache.tapestry5.ioc.ServiceResources;
-import org.apache.tapestry5.ioc.annotations.Symbol;
-import org.apache.tapestry5.ioc.internal.OperationException;
-import org.apache.tapestry5.ioc.internal.util.InternalUtils;
-import org.apache.tapestry5.runtime.ComponentEventException;
-import org.apache.tapestry5.services.ComponentClassResolver;
-import org.apache.tapestry5.services.ExceptionReporter;
-import org.apache.tapestry5.services.Request;
-import org.apache.tapestry5.services.RequestExceptionHandler;
-import org.apache.tapestry5.services.Response;
-import org.slf4j.Logger;
-
-/**
- * Default implementation of {@link RequestExceptionHandler} that displays the standard ExceptionReport page. The page
- * must implement the {@link ExceptionReporter} interface.
- */
-public class DefaultRequestExceptionHandler implements RequestExceptionHandler
-{
-    private final RequestPageCache pageCache;
-
-    private final PageResponseRenderer renderer;
-
-    private final Logger logger;
-
-    private final String pageName;
-
-    private final Request request;
-
-    private final Response response;
-    
-    private final ComponentClassResolver componentClassResolver;
-    
-    private final LinkSource linkSource;
-    
-    // should be Class<? extends Throwable>, Object but it's not allowed to configure subtypes
-    private final Map<Class, Object> configuration;
-    
-    @SuppressWarnings("rawtypes")
-    public DefaultRequestExceptionHandler(RequestPageCache pageCache, PageResponseRenderer renderer, Logger logger,
-
-    @Symbol(SymbolConstants.EXCEPTION_REPORT_PAGE)
-    String pageName,
-
-    Request request, Response response, ComponentClassResolver componentClassResolver, LinkSource linkSource, ServiceResources serviceResources, Map<Class, Object> configuration)
-    {
-        this.pageCache = pageCache;
-        this.renderer = renderer;
-        this.logger = logger;
-        this.pageName = pageName;
-        this.request = request;
-        this.response = response;
-        this.componentClassResolver = componentClassResolver;
-        this.linkSource = linkSource;
-        
-        Map<Class<ExceptionHandlerAssistant>, ExceptionHandlerAssistant> handlerAssistants = new HashMap<Class<ExceptionHandlerAssistant>, ExceptionHandlerAssistant>();
-        
-        for (Entry<Class, Object> entry : configuration.entrySet()) {
-            if (!Throwable.class.isAssignableFrom(entry.getKey()))
-                throw new IllegalArgumentException(Throwable.class.getName() + " is the only allowable key type but " + entry.getKey().getName()
-                        + " was contributed");
-            
-            if (ExceptionHandlerAssistant.class.isAssignableFrom((Class) entry.getValue())) {
-                @SuppressWarnings("unchecked")
-                Class<ExceptionHandlerAssistant> handlerType = (Class<ExceptionHandlerAssistant>) entry.getValue();
-                ExceptionHandlerAssistant assistant = handlerAssistants.get(handlerType); 
-                if (assistant == null) {
-                    assistant = (ExceptionHandlerAssistant) serviceResources.autobuild(handlerType);
-                    handlerAssistants.put(handlerType, assistant);
-                }
-                entry.setValue(assistant);
-            }
-        }
-        this.configuration = configuration;
-    }
-
-    public void handleRequestException(Throwable exception) throws IOException
-    {
-        // skip handling of known exceptions if there are none configured 
-        if (configuration.isEmpty()) {
-            renderException(exception);
-            return;
-        }
-        
-        Throwable cause = exception;
-
-        // Depending on where the error was thrown, there could be several levels of wrappers..
-        // For exceptions in component operations, it's OperationException -> ComponentEventException -> <Target>Exception
-
-        // Throw away the wrapped exceptions first
-        while (cause instanceof OperationException || cause instanceof ComponentEventException) {
-            if (cause.getCause() == null) break;
-            cause = cause.getCause();
-        }
-
-        Class<?> causeClass = cause.getClass();
-        if (!configuration.containsKey(causeClass)) {
-            // try at most two level of superclasses before delegating back to the default exception handler
-            causeClass = causeClass.getSuperclass();
-            if (causeClass == null || !configuration.containsKey(causeClass)) {
-                causeClass = causeClass.getSuperclass();
-                if (causeClass == null || !configuration.containsKey(causeClass)) {
-                    renderException(exception);
-                    return;
-                }
-            }
-        }
-
-        Object[] exceptionContext = formExceptionContext(cause);
-        Object value = configuration.get(causeClass);
-        Object page = null;
-        ExceptionHandlerAssistant assistant = null;
-        if (value instanceof ExceptionHandlerAssistant) {
-            assistant = (ExceptionHandlerAssistant) value;
-            // in case the assistant changes the context
-            List context = Arrays.asList(exceptionContext);
-            page = assistant.handleRequestException(exception, context);
-            exceptionContext = context.toArray();
-        }
-        else if (!(value instanceof Class)) {
-            renderException(exception);
-            return;
-        } else page = value;
-
-        if (page == null) return;
-
-        try {
-            if (page instanceof Class) page = componentClassResolver.resolvePageClassNameToPageName(((Class) page).getName());
-            Link link = page instanceof Link ? (Link) page : linkSource.createPageRenderLink(page.toString(), false, exceptionContext);
-            if (request.isXHR()) {
-                OutputStream os = response.getOutputStream("application/json;charset=UTF-8");
-                os.write(("{\"redirectURL\":\"" + link.toAbsoluteURI() + "\"}").getBytes());
-                os.close();
-            } else response.sendRedirect(link);
-        }
-        // The above could throw an exception if we are already on a render request, but it's
-        // user's responsibility not to abuse the mechanism
-        catch (Exception e) {
-            // Nothing to do but delegate
-            renderException(exception);
-        }
-    }
-    
-    private void renderException(Throwable exception) throws IOException
-    {
-        logger.error(String.format("Processing of request failed with uncaught exception: %s", exception), exception);
-
-        // TAP5-233: Make sure the client knows that an error occurred.
-
-        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
-
-        String rawMessage = InternalUtils.toMessage(exception);
-
-        // Encode it compatibly with the JavaScript escape() function.
-
-        String encoded = URLEncoder.encode(rawMessage, "UTF-8").replace("+", "%20");
-
-        response.setHeader("X-Tapestry-ErrorMessage", encoded);
-
-        Page page = pageCache.get(pageName);
-
-        ExceptionReporter rootComponent = (ExceptionReporter) page.getRootComponent();
-
-        // Let the page set up for the new exception.
-
-        rootComponent.reportException(exception);
-
-        renderer.renderPageResponse(page);
-    }
-    
-    @SuppressWarnings({ "unchecked", "rawtypes" })
-    protected Object[] formExceptionContext(Throwable exception) {
-        if (exception instanceof ContextAwareException) return ((ContextAwareException) exception).getContext();
-
-        Class exceptionClass = exception.getClass();
-        // pick the first class in the hierarchy that's not anonymous, probably no reason check for array types
-        while ("".equals(exceptionClass.getSimpleName()))
-            exceptionClass = exceptionClass.getSuperclass();
-
-        // check if exception type is plain runtimeException - yes, we really want the test to be this way
-        if (exceptionClass.isAssignableFrom(RuntimeException.class))
-            return exception.getMessage() == null ? new Object[0] : new Object[] { exception.getMessage().toLowerCase() };
-
-        // otherwise, form the context from the exception type name
-        String exceptionType = exceptionClass.getSimpleName();
-        if (exceptionType.endsWith("Exception")) exceptionType = exceptionType.substring(0, exceptionType.length() - 9);
-        return new Object[] { exceptionType.toLowerCase() };
-    }
-    
-}
+// Copyright 2006, 2008, 2010, 2011, 2012 The Apache Software Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package org.apache.tapestry5.internal.services;
+
+import org.apache.tapestry5.ContextAwareException;
+import org.apache.tapestry5.ExceptionHandlerAssistant;
+import org.apache.tapestry5.Link;
+import org.apache.tapestry5.SymbolConstants;
+import org.apache.tapestry5.internal.InternalConstants;
+import org.apache.tapestry5.internal.structure.Page;
+import org.apache.tapestry5.ioc.ServiceResources;
+import org.apache.tapestry5.ioc.annotations.Symbol;
+import org.apache.tapestry5.ioc.internal.OperationException;
+import org.apache.tapestry5.ioc.internal.util.InternalUtils;
+import org.apache.tapestry5.json.JSONObject;
+import org.apache.tapestry5.runtime.ComponentEventException;
+import org.apache.tapestry5.services.*;
+import org.slf4j.Logger;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.URLEncoder;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+/**
+ * Default implementation of {@link RequestExceptionHandler} that displays the standard ExceptionReport page. The page
+ * must implement the {@link ExceptionReporter} interface.
+ */
+public class DefaultRequestExceptionHandler implements RequestExceptionHandler
+{
+    private final RequestPageCache pageCache;
+
+    private final PageResponseRenderer renderer;
+
+    private final Logger logger;
+
+    private final String pageName;
+
+    private final Request request;
+
+    private final Response response;
+
+    private final ComponentClassResolver componentClassResolver;
+
+    private final LinkSource linkSource;
+
+    // should be Class<? extends Throwable>, Object but it's not allowed to configure subtypes
+    private final Map<Class, Object> configuration;
+
+    @SuppressWarnings("rawtypes")
+    public DefaultRequestExceptionHandler(RequestPageCache pageCache, PageResponseRenderer renderer, Logger logger,
+
+                                          @Symbol(SymbolConstants.EXCEPTION_REPORT_PAGE)
+                                          String pageName,
+
+                                          Request request, Response response, ComponentClassResolver componentClassResolver, LinkSource linkSource, ServiceResources serviceResources, Map<Class, Object> configuration)
+    {
+        this.pageCache = pageCache;
+        this.renderer = renderer;
+        this.logger = logger;
+        this.pageName = pageName;
+        this.request = request;
+        this.response = response;
+        this.componentClassResolver = componentClassResolver;
+        this.linkSource = linkSource;
+
+        Map<Class<ExceptionHandlerAssistant>, ExceptionHandlerAssistant> handlerAssistants = new HashMap<Class<ExceptionHandlerAssistant>, ExceptionHandlerAssistant>();
+
+        for (Entry<Class, Object> entry : configuration.entrySet())
+        {
+            if (!Throwable.class.isAssignableFrom(entry.getKey()))
+                throw new IllegalArgumentException(Throwable.class.getName() + " is the only allowable key type but " + entry.getKey().getName()
+                        + " was contributed");
+
+            if (ExceptionHandlerAssistant.class.isAssignableFrom((Class) entry.getValue()))
+            {
+                @SuppressWarnings("unchecked")
+                Class<ExceptionHandlerAssistant> handlerType = (Class<ExceptionHandlerAssistant>) entry.getValue();
+                ExceptionHandlerAssistant assistant = handlerAssistants.get(handlerType);
+                if (assistant == null)
+                {
+                    assistant = (ExceptionHandlerAssistant) serviceResources.autobuild(handlerType);
+                    handlerAssistants.put(handlerType, assistant);
+                }
+                entry.setValue(assistant);
+            }
+        }
+        this.configuration = configuration;
+    }
+
+    public void handleRequestException(Throwable exception) throws IOException
+    {
+        // skip handling of known exceptions if there are none configured 
+        if (configuration.isEmpty())
+        {
+            renderException(exception);
+            return;
+        }
+
+        Throwable cause = exception;
+
+        // Depending on where the error was thrown, there could be several levels of wrappers..
+        // For exceptions in component operations, it's OperationException -> ComponentEventException -> <Target>Exception
+
+        // Throw away the wrapped exceptions first
+        while (cause instanceof OperationException || cause instanceof ComponentEventException)
+        {
+            if (cause.getCause() == null) break;
+            cause = cause.getCause();
+        }
+
+        Class<?> causeClass = cause.getClass();
+        if (!configuration.containsKey(causeClass))
+        {
+            // try at most two level of superclasses before delegating back to the default exception handler
+            causeClass = causeClass.getSuperclass();
+            if (causeClass == null || !configuration.containsKey(causeClass))
+            {
+                causeClass = causeClass.getSuperclass();
+                if (causeClass == null || !configuration.containsKey(causeClass))
+                {
+                    renderException(exception);
+                    return;
+                }
+            }
+        }
+
+        Object[] exceptionContext = formExceptionContext(cause);
+        Object value = configuration.get(causeClass);
+        Object page = null;
+        ExceptionHandlerAssistant assistant = null;
+        if (value instanceof ExceptionHandlerAssistant)
+        {
+            assistant = (ExceptionHandlerAssistant) value;
+            // in case the assistant changes the context
+            List context = Arrays.asList(exceptionContext);
+            page = assistant.handleRequestException(exception, context);
+            exceptionContext = context.toArray();
+        } else if (!(value instanceof Class))
+        {
+            renderException(exception);
+            return;
+        } else page = value;
+
+        if (page == null) return;
+
+        try
+        {
+            if (page instanceof Class)
+                page = componentClassResolver.resolvePageClassNameToPageName(((Class) page).getName());
+
+            Link link = page instanceof Link
+                    ? (Link) page
+                    : linkSource.createPageRenderLink(page.toString(), false, exceptionContext);
+
+            if (request.isXHR())
+            {
+                OutputStream os = response.getOutputStream("application/json;charset=UTF-8");
+
+                JSONObject reply = new JSONObject();
+                reply.in(InternalConstants.PARTIAL_KEY).put("redirectURL", link.toAbsoluteURI());
+
+                os.write(reply.toCompactString().getBytes("UTF-8"));
+
+                os.close();
+
+                return;
+            }
+
+            // Normal behavior is just a redirect.
+
+            response.sendRedirect(link);
+        }
+        // The above could throw an exception if we are already on a render request, but it's
+        // user's responsibility not to abuse the mechanism
+        catch (Exception e)
+        {
+            // Nothing to do but delegate
+            renderException(exception);
+        }
+    }
+
+    private void renderException(Throwable exception) throws IOException
+    {
+        logger.error(String.format("Processing of request failed with uncaught exception: %s", exception), exception);
+
+        // TAP5-233: Make sure the client knows that an error occurred.
+
+        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+
+        String rawMessage = InternalUtils.toMessage(exception);
+
+        // Encode it compatibly with the JavaScript escape() function.
+
+        String encoded = URLEncoder.encode(rawMessage, "UTF-8").replace("+", "%20");
+
+        response.setHeader("X-Tapestry-ErrorMessage", encoded);
+
+        Page page = pageCache.get(pageName);
+
+        ExceptionReporter rootComponent = (ExceptionReporter) page.getRootComponent();
+
+        // Let the page set up for the new exception.
+
+        rootComponent.reportException(exception);
+
+        renderer.renderPageResponse(page);
+    }
+
+    @SuppressWarnings({"unchecked", "rawtypes"})
+    protected Object[] formExceptionContext(Throwable exception)
+    {
+        if (exception instanceof ContextAwareException) return ((ContextAwareException) exception).getContext();
+
+        Class exceptionClass = exception.getClass();
+        // pick the first class in the hierarchy that's not anonymous, probably no reason check for array types
+        while ("".equals(exceptionClass.getSimpleName()))
+            exceptionClass = exceptionClass.getSuperclass();
+
+        // check if exception type is plain runtimeException - yes, we really want the test to be this way
+        if (exceptionClass.isAssignableFrom(RuntimeException.class))
+            return exception.getMessage() == null ? new Object[0] : new Object[]{exception.getMessage().toLowerCase()};
+
+        // otherwise, form the context from the exception type name
+        String exceptionType = exceptionClass.getSimpleName();
+        if (exceptionType.endsWith("Exception")) exceptionType = exceptionType.substring(0, exceptionType.length() - 9);
+        return new Object[]{exceptionType.toLowerCase()};
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/tapestry-5/blob/9dc4943d/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/PartialMarkupDocumentLinker.java
----------------------------------------------------------------------
diff --git a/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/PartialMarkupDocumentLinker.java b/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/PartialMarkupDocumentLinker.java
index 809aa18..f6d7813 100644
--- a/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/PartialMarkupDocumentLinker.java
+++ b/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/PartialMarkupDocumentLinker.java
@@ -14,6 +14,7 @@
 
 package org.apache.tapestry5.internal.services;
 
+import org.apache.tapestry5.internal.InternalConstants;
 import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
 import org.apache.tapestry5.ioc.internal.util.InternalUtils;
 import org.apache.tapestry5.json.JSONArray;
@@ -74,16 +75,6 @@ public class PartialMarkupDocumentLinker implements DocumentLinker
      */
     public void commit(JSONObject reply)
     {
-        if (scripts.length() > 0)
-        {
-            reply.put("scripts", scripts);
-        }
-
-        if (stylesheets.length() > 0)
-        {
-            reply.put("stylesheets", stylesheets);
-        }
-
         JSONArray fullInits = new JSONArray();
 
         for (InitializationPriority p : InitializationPriority.values())
@@ -99,9 +90,29 @@ public class PartialMarkupDocumentLinker implements DocumentLinker
             }
         }
 
+        boolean hasWork = scripts.length() > 0 || stylesheets.length() > 0 || fullInits.length() > 0;
+
+        if (!hasWork)
+        {
+            return;
+        }
+
+        JSONObject partial = reply.in(InternalConstants.PARTIAL_KEY);
+
+
+        if (scripts.length() > 0)
+        {
+            partial.put("libraries", scripts);
+        }
+
+        if (stylesheets.length() > 0)
+        {
+            partial.put("stylesheets", stylesheets);
+        }
+
         if (fullInits.length() > 0)
         {
-            reply.put("inits", fullInits);
+            partial.put("inits", fullInits);
         }
     }
 }

http://git-wip-us.apache.org/repos/asf/tapestry-5/blob/9dc4943d/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/ajax/SingleZonePartialRendererFilter.java
----------------------------------------------------------------------
diff --git a/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/ajax/SingleZonePartialRendererFilter.java b/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/ajax/SingleZonePartialRendererFilter.java
index a1d59b1..4b5634d 100644
--- a/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/ajax/SingleZonePartialRendererFilter.java
+++ b/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/ajax/SingleZonePartialRendererFilter.java
@@ -1,4 +1,4 @@
-// Copyright 2009, 2010, 2011 The Apache Software Foundation
+// Copyright 2009-2012 The Apache Software Foundation
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -16,7 +16,9 @@ package org.apache.tapestry5.internal.services.ajax;
 
 import org.apache.tapestry5.MarkupWriter;
 import org.apache.tapestry5.dom.Element;
+import org.apache.tapestry5.internal.InternalConstants;
 import org.apache.tapestry5.internal.services.PageRenderQueue;
+import org.apache.tapestry5.json.JSONArray;
 import org.apache.tapestry5.json.JSONObject;
 import org.apache.tapestry5.runtime.RenderCommand;
 import org.apache.tapestry5.runtime.RenderQueue;
@@ -77,12 +79,11 @@ public class SingleZonePartialRendererFilter implements PartialMarkupRendererFil
 
                         zoneContainer.remove();
 
-                        if (!reply.has("zones"))
-                        {
-                            reply.put("zones", new JSONObject());
-                        }
-
-                        reply.getJSONObject("zones").put(zoneId, zoneUpdateContent);
+                        // This has changed a bit in 5.4;
+                        // In 5.3, it was just "zones", and was key/value pairs for id and content.
+                        // In 5.4, it is "content", and is an array of id/content arrays
+                        reply.in(InternalConstants.PARTIAL_KEY).append("content",
+                                new JSONArray(zoneId, zoneUpdateContent));
                     }
                 });
 

http://git-wip-us.apache.org/repos/asf/tapestry-5/blob/9dc4943d/tapestry-core/src/main/resources/org/apache/tapestry5/tapestry.js
----------------------------------------------------------------------
diff --git a/tapestry-core/src/main/resources/org/apache/tapestry5/tapestry.js b/tapestry-core/src/main/resources/org/apache/tapestry5/tapestry.js
index 2b83bb9..9cfb82b 100644
--- a/tapestry-core/src/main/resources/org/apache/tapestry5/tapestry.js
+++ b/tapestry-core/src/main/resources/org/apache/tapestry5/tapestry.js
@@ -1,4 +1,4 @@
-/* Copyright 2007, 2008, 2009, 2010, 2011 The Apache Software Foundation
+/* Copyright 2007-2012 The Apache Software Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -1808,9 +1808,8 @@ Tapestry.ZoneManager = Class.create({
 
     /**
      * Invoked with a reply (i.e., transport.responseJSON), this updates the
-     * managed element and processes any JavaScript in the reply. The response
-     * should have a content key, and may have script, scripts and stylesheets
-     * keys.
+     * managed element and processes any JavaScript in the reply. The zone's
+     * content is only updated if the response has a content key.
      *
      * @param reply
      *            response in JSON format appropriate to a Tapestry.Zone
@@ -1819,22 +1818,9 @@ Tapestry.ZoneManager = Class.create({
         Tapestry.loadScriptsInReply(reply, function () {
             /*
              * In a multi-zone update, the reply.content may be missing, in
-             * which case, leave the curent content in place. TAP5-1177
+             * which case, leave the current content in place. TAP5-1177
              */
             reply.content != undefined && this.show(reply.content);
-
-            /*
-             * zones is an object of zone ids and zone content that will be
-             * present in a multi-zone update response.
-             */
-            reply.zones && Object.keys(reply.zones).each(function (zoneId) {
-                var manager = Tapestry.findZoneManagerForZone(zoneId);
-
-                if (manager) {
-                    var zoneContent = reply.zones[zoneId];
-                    manager.show(zoneContent);
-                }
-            });
         }.bind(this));
     },
 

http://git-wip-us.apache.org/repos/asf/tapestry-5/blob/9dc4943d/tapestry-core/src/test/groovy/org/apache/tapestry5/internal/services/PartialMarkupDocumentLinkerTest.groovy
----------------------------------------------------------------------
diff --git a/tapestry-core/src/test/groovy/org/apache/tapestry5/internal/services/PartialMarkupDocumentLinkerTest.groovy b/tapestry-core/src/test/groovy/org/apache/tapestry5/internal/services/PartialMarkupDocumentLinkerTest.groovy
index 4d4abfe..5fe85d6 100644
--- a/tapestry-core/src/test/groovy/org/apache/tapestry5/internal/services/PartialMarkupDocumentLinkerTest.groovy
+++ b/tapestry-core/src/test/groovy/org/apache/tapestry5/internal/services/PartialMarkupDocumentLinkerTest.groovy
@@ -30,7 +30,7 @@ class PartialMarkupDocumentLinkerTest extends Assert {
 
         linker.commit(reply)
 
-        assert reply.toCompactString() ==  /{"scripts":["foo.js","bar.js"]}/
+        assert reply.toCompactString() == /{"_tapestry":{"libraries":["foo.js","bar.js"]}}/
 
     }
 
@@ -45,7 +45,7 @@ class PartialMarkupDocumentLinkerTest extends Assert {
 
         linker.commit(reply)
 
-        JSONObject expected = new JSONObject(/{'stylesheets':[{'href':'foo.css', 'media':'print'}, {'href':'bar.css'}]}/)
+        JSONObject expected = new JSONObject(/{"_tapestry":{'stylesheets':[{'href':'foo.css', 'media':'print'}, {'href':'bar.css'}]}}/)
 
         assert reply == expected
     }
@@ -63,6 +63,6 @@ class PartialMarkupDocumentLinkerTest extends Assert {
 
         JSONArray expected = new JSONArray("[['core/init:order', 'immediate'], ['core/init:order', 'normal']]")
 
-        assert reply.get("inits") == expected
+        assert reply.in("_tapestry").get("inits") == expected
     }
 }