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
015 package org.apache.tapestry.markup;
016
017 import java.io.CharArrayWriter;
018 import java.io.PrintWriter;
019
020 import org.apache.tapestry.IMarkupWriter;
021 import 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 */
031 public 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 NestedMarkupWriterImpl(IMarkupWriter parent, MarkupFilter filter)
040 {
041 // Need to do this awkward double constructor because we want
042 // to create an object and pass it to the parent constructor.
043 // Java language rules get in the way here.
044
045 this(parent, new CharArrayWriter(), filter);
046 }
047
048 private NestedMarkupWriterImpl(IMarkupWriter parent, CharArrayWriter writer, MarkupFilter filter)
049 {
050 super(parent.getContentType(), new PrintWriter(writer), filter);
051
052 _parent = parent;
053 _charArrayWriter = writer;
054 }
055
056 public String getBuffer()
057 {
058 if (_closed)
059 throw new IllegalStateException(MarkupMessages.closeOnce());
060
061 _closed = true;
062
063 super.close();
064
065 return _charArrayWriter.toString();
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 }