001// Copyright 2008 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 org.apache.tapestry5.EventConstants;
018import org.apache.tapestry5.internal.InternalConstants;
019import org.apache.tapestry5.internal.structure.Page;
020import org.apache.tapestry5.services.*;
021
022import java.io.IOException;
023
024public class ImmediateActionRenderResponseFilter implements ComponentEventRequestFilter
025{
026    private final Request request;
027
028    private final Response response;
029
030    private final PageResponseRenderer renderer;
031
032    public ImmediateActionRenderResponseFilter(Request request, PageResponseRenderer renderer, Response response)
033    {
034        this.request = request;
035        this.renderer = renderer;
036        this.response = response;
037    }
038
039    public void handle(ComponentEventRequestParameters parameters, ComponentEventRequestHandler handler)
040            throws IOException
041    {
042        handler.handle(parameters);
043
044        // If markup or a redirect has already been generated, then we're good.
045
046        if (response.isCommitted()) return;
047
048        // Otherwise, we should be operating in immediate mode.  Figure out which page
049        // was selected to render.
050
051        Page page = (Page) request.getAttribute(InternalConstants.IMMEDIATE_RESPONSE_PAGE_ATTRIBUTE);
052
053        if (page != null)
054        {
055            // We don't have a context to provide but this still nags me as not the right thing to do.
056
057            page.getRootElement().triggerEvent(EventConstants.ACTIVATE, new Object[0], null);
058
059            renderer.renderPageResponse(page);
060            return;
061        }
062
063        throw new IllegalStateException(
064                "Sanity check - neither a stream response nor a redirect response was generated for this action request.");
065    }
066}