001// Copyright 2004, 2005 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.tapestry.services.impl;
016
017import java.io.IOException;
018import java.io.PrintWriter;
019
020import org.apache.tapestry.IMarkupWriter;
021import org.apache.tapestry.IPage;
022import org.apache.tapestry.IRequestCycle;
023import org.apache.tapestry.markup.MarkupWriterSource;
024import org.apache.tapestry.services.RequestLocaleManager;
025import org.apache.tapestry.services.ResponseRenderer;
026import org.apache.tapestry.util.ContentType;
027import org.apache.tapestry.web.WebResponse;
028
029/**
030 * Responsible for rendering a response to the client.
031 * 
032 * @author Howard M. Lewis Ship
033 * @since 4.0
034 */
035public class ResponseRendererImpl implements ResponseRenderer
036{
037    private RequestLocaleManager _localeManager;
038
039    private MarkupWriterSource _markupWriterSource;
040
041    private WebResponse _webResponse;
042
043    /**
044     * Inside a {@link org.apache.tapestry.util.ContentType}, the output encoding is called
045     * "charset".
046     */
047
048    public static final String ENCODING_KEY = "charset";
049
050    public void renderResponse(IRequestCycle cycle) throws IOException
051    {
052        _localeManager.persistLocale();
053
054        IPage page = cycle.getPage();
055
056        ContentType contentType = page.getResponseContentType();
057
058        String encoding = contentType.getParameter(ENCODING_KEY);
059
060        if (encoding == null)
061        {
062            encoding = cycle.getEngine().getOutputEncoding();
063
064            contentType.setParameter(ENCODING_KEY, encoding);
065        }
066
067        PrintWriter printWriter = _webResponse.getPrintWriter(contentType);
068
069        IMarkupWriter writer = _markupWriterSource.newMarkupWriter(printWriter, contentType);
070
071        cycle.renderPage(writer);
072
073        writer.close();
074    }
075
076    public void setLocaleManager(RequestLocaleManager localeManager)
077    {
078        _localeManager = localeManager;
079    }
080
081    public void setMarkupWriterSource(MarkupWriterSource markupWriterSource)
082    {
083        _markupWriterSource = markupWriterSource;
084    }
085
086    public void setWebResponse(WebResponse webResponse)
087    {
088        _webResponse = webResponse;
089    }
090}