001// Copyright 2006-2013 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; 018import java.io.PrintWriter; 019 020import org.apache.tapestry5.MarkupWriter; 021import org.apache.tapestry5.http.ContentType; 022import org.apache.tapestry5.http.services.RequestGlobals; 023import org.apache.tapestry5.http.services.Response; 024import org.apache.tapestry5.internal.structure.Page; 025import org.apache.tapestry5.services.MarkupWriterFactory; 026import org.slf4j.Logger; 027 028public class PageResponseRendererImpl implements PageResponseRenderer 029{ 030 private final RequestGlobals requestGlobals; 031 032 private final PageMarkupRenderer markupRenderer; 033 034 private final MarkupWriterFactory markupWriterFactory; 035 036 private final PageContentTypeAnalyzer pageContentTypeAnalyzer; 037 038 private final Response response; 039 040 private final Logger logger; 041 042 public PageResponseRendererImpl(RequestGlobals requestGlobals, MarkupWriterFactory markupWriterFactory, 043 PageMarkupRenderer markupRenderer, PageContentTypeAnalyzer pageContentTypeAnalyzer, Response response, 044 Logger logger) 045 { 046 this.requestGlobals = requestGlobals; 047 this.markupWriterFactory = markupWriterFactory; 048 this.markupRenderer = markupRenderer; 049 this.pageContentTypeAnalyzer = pageContentTypeAnalyzer; 050 this.response = response; 051 this.logger = logger; 052 } 053 054 public void renderPageResponse(Page page) throws IOException 055 { 056 assert page != null; 057 058 requestGlobals.storeActivePageName(page.getName()); 059 060 ContentType contentType = pageContentTypeAnalyzer.findContentType(page); 061 062 MarkupWriter writer = markupWriterFactory.newMarkupWriter(page); 063 064 markupRenderer.renderPageMarkup(page, writer); 065 066 PrintWriter pw = response.getPrintWriter(contentType.toString()); 067 long startNanos = -1l; 068 boolean debugEnabled = logger.isDebugEnabled(); 069 if (debugEnabled) 070 { 071 startNanos = System.nanoTime(); 072 } 073 writer.toMarkup(pw); 074 075 076 if (debugEnabled) 077 { 078 long endNanos = System.nanoTime(); 079 long elapsedNanos = endNanos - startNanos; 080 double elapsedSeconds = ((float) elapsedNanos) / 1000000000F; 081 082 logger.debug(String.format("Response DOM streamed to markup in %.3f seconds", elapsedSeconds)); 083 } 084 085 pw.close(); 086 } 087}