001// Copyright 2007-2013, 2026 The Apache Software Foundation
002//
003// Licensed under the Apache License, Version 2.0 (the "License");
004// you may not use this file except in compliance with the License.
005// You may obtain a copy of the License at
006//
007// http://www.apache.org/licenses/LICENSE-2.0
008//
009// Unless required by applicable law or agreed to in writing, software
010// distributed under the License is distributed on an "AS IS" BASIS,
011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012// See the License for the specific language governing permissions and
013// limitations under the License.
014
015package org.apache.tapestry5.internal.services;
016
017import java.io.IOException;
018
019import org.apache.tapestry5.TrackableComponentEventCallback;
020import org.apache.tapestry5.commons.internal.util.TapestryException;
021import org.apache.tapestry5.http.services.Request;
022import org.apache.tapestry5.internal.EmptyEventContext;
023import org.apache.tapestry5.internal.InternalConstants;
024import org.apache.tapestry5.internal.structure.ComponentPageElement;
025import org.apache.tapestry5.internal.structure.Page;
026import org.apache.tapestry5.internal.util.Holder;
027import org.apache.tapestry5.json.JSONObject;
028import org.apache.tapestry5.services.Ajax;
029import org.apache.tapestry5.services.ComponentEventRequestHandler;
030import org.apache.tapestry5.services.ComponentEventRequestParameters;
031import org.apache.tapestry5.services.ComponentEventResultProcessor;
032import org.apache.tapestry5.services.Environment;
033
034/**
035 * Similar to {@link ComponentEventRequestHandlerImpl}, but built around the Ajax request cycle, where the action
036 * request sends back an immediate JSON response containing the new content.
037 */
038@SuppressWarnings({"unchecked", "rawtypes"})
039public class AjaxComponentEventRequestHandler implements ComponentEventRequestHandler
040{
041    private final RequestPageCache cache;
042
043    private final Request request;
044
045    private final PageRenderQueue queue;
046
047    private final ComponentEventResultProcessor resultProcessor;
048
049    private final Environment environment;
050
051    private final AjaxPartialResponseRenderer partialRenderer;
052
053    private final PageActivator pageActivator;
054
055    public AjaxComponentEventRequestHandler(RequestPageCache cache, Request request, PageRenderQueue queue, @Ajax
056    ComponentEventResultProcessor resultProcessor, PageActivator pageActivator,
057                                            Environment environment,
058                                            AjaxPartialResponseRenderer partialRenderer)
059    {
060        this.cache = cache;
061        this.queue = queue;
062        this.resultProcessor = resultProcessor;
063        this.pageActivator = pageActivator;
064        this.request = request;
065        this.environment = environment;
066        this.partialRenderer = partialRenderer;
067    }
068
069    public void handle(ComponentEventRequestParameters parameters) throws IOException
070    {
071        Page activePage = cache.get(parameters.getActivePageName());
072
073        final Holder<Boolean> resultProcessorInvoked = Holder.create();
074        resultProcessorInvoked.put(false);
075
076        ComponentEventResultProcessor interceptor = new ComponentEventResultProcessor()
077        {
078            public void processResultValue(Object value) throws IOException
079            {
080                resultProcessorInvoked.put(true);
081
082                resultProcessor.processResultValue(value);
083            }
084        };
085
086        // If we end up doing a partial render, the page render queue service needs to know the
087        // page that will be rendered (for logging purposes, if nothing else).
088
089        queue.setRenderingPage(activePage);
090
091        request.setAttribute(InternalConstants.PAGE_NAME_ATTRIBUTE_NAME, parameters.getActivePageName());
092
093        if (pageActivator.activatePage(activePage.getRootElement().getComponentResources(), parameters
094                .getPageActivationContext(), interceptor))
095            return;
096
097        Page containerPage = cache.get(parameters.getContainingPageName());
098
099        // When the event targets a component from a different page than the active page, the
100        // containing page also has code executing for this request, so its activation event
101        // should also be triggered.
102        // An empty context is used because the activation context in the request belongs to
103        // the active page.
104        if (containerPage != activePage
105                && pageActivator.activatePage(containerPage.getRootElement().getComponentResources(),
106                        new EmptyEventContext(), interceptor))
107        {
108            return;
109        }
110
111        ComponentPageElement element = containerPage.getComponentElementByNestedId(parameters.getNestedComponentId());
112
113        // In many cases, the triggered element is a Form that needs to be able to
114        // pass its event handler return values to the correct result processor.
115        // This is certainly the case for forms.
116
117        TrackableComponentEventCallback callback = new ComponentResultProcessorWrapper(interceptor);
118
119        environment.push(ComponentEventResultProcessor.class, interceptor);
120        environment.push(TrackableComponentEventCallback.class, callback);
121
122        boolean handled = element
123                .triggerContextEvent(parameters.getEventType(), parameters.getEventContext(), callback);
124
125        if (!handled)
126            throw new TapestryException(String.format("Request event '%s' (on component %s) was not handled; you must provide a matching event handler method in the component or in one of its containers.", parameters.getEventType(), element.getCompleteId()), element,
127                    null);
128
129        environment.pop(TrackableComponentEventCallback.class);
130        environment.pop(ComponentEventResultProcessor.class);
131
132
133        // If the result processor was passed a value, then it will already have rendered. Otherwise it was not passed a value,
134        // but it's still possible that we still want to do a partial page render ... if filters were added to the render queue.
135        // In that event, run the partial page render now and return.
136
137        boolean wasInvoked = resultProcessorInvoked.get();
138
139        if ((!wasInvoked) && queue.isPartialRenderInitialized())
140        {
141            partialRenderer.renderPartialPageMarkup();
142            return;
143        }
144
145        // If the result processor was passed a value, then it will already have rendered, and there is nothing more to do.
146
147        if (wasInvoked) { return; }
148
149        // Send an empty JSON reply if no value was returned from the component event handler method.
150        // This is the typical behavior when an Ajax component event handler returns null. It still
151        // will go through a pipeline that will add information related to partial page rendering.
152
153        resultProcessor.processResultValue(new JSONObject());
154    }
155}