001/* 
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     bstefanescu
011 *
012 * $Id$
013 */
014
015package org.nuxeo.ecm.platform.rendering.wiki;
016
017import java.io.IOException;
018import java.io.Writer;
019import java.util.ArrayList;
020import java.util.List;
021
022import org.apache.commons.logging.Log;
023import org.apache.commons.logging.LogFactory;
024import org.wikimodel.wem.IWikiPrinter;
025
026/**
027 * Special writer used to split the serialization result in dynamic or static segments. This way we can generate final
028 * output after parsing the entire file. This is needed for example to generate TOC.
029 *
030 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
031 */
032public class WikiWriter implements IWikiPrinter, WikiText {
033
034    protected static final Log log = LogFactory.getLog(WikiWriter.class);
035
036    protected static final String LINE_SEP = System.getProperty("line.separator");
037
038    protected WikiWriter parent;
039
040    protected final List<String> segments = new ArrayList<String>();
041
042    protected final List<WikiText> dynamicSegments = new ArrayList<WikiText>();
043
044    protected final StringBuilder buf = new StringBuilder();
045
046    public WikiWriter() {
047    }
048
049    public WikiWriter(WikiWriter parent) {
050        this.parent = parent;
051    }
052
053    public void print(String str) {
054        buf.append(str);
055    }
056
057    public void println() {
058        buf.append(LINE_SEP);
059    }
060
061    public void println(String str) {
062        buf.append(str);
063        buf.append(LINE_SEP);
064    }
065
066    public void writeText(WikiText text) {
067        segments.add(buf.toString());
068        buf.setLength(0);
069        dynamicSegments.add(text);
070    }
071
072    public WikiWriter getParent() {
073        return parent;
074    }
075
076    public StringBuilder getBuffer() {
077        return buf;
078    }
079
080    public void writeTo(WikiSerializerHandler handler, Writer writer) throws IOException {
081        for (int i = 0, len = segments.size(); i < len; i++) {
082            writer.write(segments.get(i));
083            dynamicSegments.get(i).writeTo(handler, writer);
084        }
085        writer.write(buf.toString());
086    }
087
088}