    001// Copyright 2014, 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.
    014package org.apache.tapestry5.internal.services;
    015
    016import org.apache.tapestry5.MarkupWriter;
    017import org.apache.tapestry5.dom.Document;
    018import org.apache.tapestry5.ioc.services.TypeCoercer;
    019import org.apache.tapestry5.runtime.RenderCommand;
    020import org.apache.tapestry5.services.PartialTemplateRenderer;
    021import org.slf4j.Logger;
    022import org.slf4j.LoggerFactory;
    023
    024public class PartialTemplateRendererImpl implements PartialTemplateRenderer
    025{
    026
    027    final private static Logger LOGGER = LoggerFactory.getLogger(PartialTemplateRendererImpl.class);
    028
    029    final private TypeCoercer typeCoercer;
    030
    031    public PartialTemplateRendererImpl(TypeCoercer typeCoercer)
    032    {
    033        super();
    034        this.typeCoercer = typeCoercer;
    035    }
    036
    037    public Document renderAsDocument(Object object)
    038    {
    039        RenderCommand renderCommand = toRenderCommand(object);
    040        MarkupWriter markupWriter = new MarkupWriterImpl();
    041        RenderQueueImpl renderQueue = new RenderQueueImpl(LOGGER);
    042        renderQueue.push(renderCommand);
    043        renderQueue.run(markupWriter);
    044        return markupWriter.getDocument();
    045    }
    046
    047    public String render(Object object)
    048    {
    049        return renderAsDocument(object).toString();
    050    }
    051
    052    private RenderCommand toRenderCommand(Object object)
    053    {
    054        RenderCommand renderCommand = null;
    055        if (object instanceof RenderCommand)
    056        {
    057            renderCommand = (RenderCommand) object;
    058        }
    059        else {
    060            try {
    061                renderCommand = typeCoercer.coerce(object, RenderCommand.class);
    062            }
    063            catch (RuntimeException e) {
    064                throw new IllegalArgumentException(
    065                        String.format("Couldn't find a coercion from %s to RenderCommand", object.getClass().getName()), e);
    066            }
    067        }
    068        return renderCommand;
    069    }
    070
    071}