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<>(); 048 049 protected final List<WikiText> dynamicSegments = new ArrayList<>(); 050 051 protected final StringBuilder sb = new StringBuilder(); 052 053 public WikiWriter() { 054 } 055 056 public WikiWriter(WikiWriter parent) { 057 this.parent = parent; 058 } 059 060 @Override 061 public void print(String str) { 062 sb.append(str); 063 } 064 065 public void println() { 066 sb.append(LINE_SEP); 067 } 068 069 @Override 070 public void println(String str) { 071 sb.append(str); 072 sb.append(LINE_SEP); 073 } 074 075 public void writeText(WikiText text) { 076 segments.add(sb.toString()); 077 sb.setLength(0); 078 dynamicSegments.add(text); 079 } 080 081 public WikiWriter getParent() { 082 return parent; 083 } 084 085 public StringBuilder getBuffer() { 086 return sb; 087 } 088 089 @Override 090 public void writeTo(WikiSerializerHandler handler, Writer writer) throws IOException { 091 for (int i = 0, len = segments.size(); i < len; i++) { 092 writer.write(segments.get(i)); 093 dynamicSegments.get(i).writeTo(handler, writer); 094 } 095 writer.write(sb.toString()); 096 } 097 098}