001// Copyright 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.markup;
016
017import java.io.CharArrayWriter;
018import java.io.PrintWriter;
019
020import org.apache.tapestry.IMarkupWriter;
021import org.apache.tapestry.NestedMarkupWriter;
022
023/**
024 * Nested implementation of {@link org.apache.tapestry.IMarkupWriter}. Accumulates content in a
025 * {@link java.io.CharArrayWriter}, and prints the buffered content (raw) on {@link #close()}.
026 * 
027 * @author Howard M. Lewis Ship
028 * @since 4.0
029 * @see org.apache.tapestry.IMarkupWriter#getNestedWriter()
030 */
031public class NestedMarkupWriterImpl extends MarkupWriterImpl implements NestedMarkupWriter
032{
033    private final IMarkupWriter _parent;
034
035    private final CharArrayWriter _charArrayWriter;
036
037    private boolean _closed;
038
039    public String getBuffer()
040    {
041        if (_closed)
042            throw new IllegalStateException(MarkupMessages.closeOnce());
043
044        _closed = true;
045
046        super.close();
047
048        return _charArrayWriter.toString();
049    }
050
051    public NestedMarkupWriterImpl(IMarkupWriter parent, MarkupFilter filter)
052    {
053        // Need to do this awkward double constructor because we want
054        // to create an object and pass it to the parent constructor.
055        // Java language rules get in the way here.
056
057        this(parent, new CharArrayWriter(), filter);
058    }
059
060    private NestedMarkupWriterImpl(IMarkupWriter parent, CharArrayWriter writer, MarkupFilter filter)
061    {
062        super(parent.getContentType(), new PrintWriter(writer), filter);
063
064        _parent = parent;
065        _charArrayWriter = writer;
066    }
067
068    /**
069     * Closes the internal {@link CharArrayWriter}, then captures its content and invokes
070     * {@link org.apache.tapestry.IMarkupWriter#printRaw(String)} on the parent markup writer
071     * (the writer that created this writer).
072     */
073
074    public void close()
075    {
076        String content = getBuffer();
077
078        _parent.printRaw(content);
079    }
080}