001/* 
002 * (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     bstefanescu
018 *
019 * $Id$
020 */
021
022package org.nuxeo.ecm.platform.rendering.wiki;
023
024import java.io.IOException;
025import java.io.Writer;
026import java.util.ArrayList;
027import java.util.List;
028
029import org.apache.commons.logging.Log;
030import org.apache.commons.logging.LogFactory;
031import org.wikimodel.wem.IWikiPrinter;
032
033/**
034 * Special writer used to split the serialization result in dynamic or static segments. This way we can generate final
035 * output after parsing the entire file. This is needed for example to generate TOC.
036 *
037 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
038 */
039public class WikiWriter implements IWikiPrinter, WikiText {
040
041    protected static final Log log = LogFactory.getLog(WikiWriter.class);
042
043    protected static final String LINE_SEP = System.getProperty("line.separator");
044
045    protected WikiWriter parent;
046
047    protected final List<String> segments = new ArrayList<String>();
048
049    protected final List<WikiText> dynamicSegments = new ArrayList<WikiText>();
050
051    protected final StringBuilder buf = new StringBuilder();
052
053    public WikiWriter() {
054    }
055
056    public WikiWriter(WikiWriter parent) {
057        this.parent = parent;
058    }
059
060    public void print(String str) {
061        buf.append(str);
062    }
063
064    public void println() {
065        buf.append(LINE_SEP);
066    }
067
068    public void println(String str) {
069        buf.append(str);
070        buf.append(LINE_SEP);
071    }
072
073    public void writeText(WikiText text) {
074        segments.add(buf.toString());
075        buf.setLength(0);
076        dynamicSegments.add(text);
077    }
078
079    public WikiWriter getParent() {
080        return parent;
081    }
082
083    public StringBuilder getBuffer() {
084        return buf;
085    }
086
087    public void writeTo(WikiSerializerHandler handler, Writer writer) throws IOException {
088        for (int i = 0, len = segments.size(); i < len; i++) {
089            writer.write(segments.get(i));
090            dynamicSegments.get(i).writeTo(handler, writer);
091        }
092        writer.write(buf.toString());
093    }
094
095}