1 16 package org.apache.cocoon.serialization; 17 18 import org.apache.avalon.framework.configuration.Configuration; 19 import org.apache.avalon.framework.configuration.ConfigurationException; 20 import org.apache.cocoon.CascadingIOException; 21 import org.apache.cocoon.xml.XMLUtils; 22 23 import org.xml.sax.SAXException ; 24 import org.xml.sax.Attributes ; 25 26 import javax.xml.transform.OutputKeys ; 27 import javax.xml.transform.sax.TransformerHandler ; 28 import javax.xml.transform.stream.StreamResult ; 29 import java.io.IOException ; 30 import java.io.OutputStream ; 31 32 44 public class TextSerializer extends AbstractTextSerializer { 45 46 49 private boolean hasRootElement; 50 51 54 private boolean hadNoRootElement; 55 56 59 public void configure(Configuration conf) throws ConfigurationException { 60 super.configure(conf); 61 this.format.put(OutputKeys.METHOD, "text"); 62 } 63 64 68 public void setOutputStream(OutputStream out) throws IOException { 69 super.setOutputStream(out); 70 try { 71 TransformerHandler handler = this.getTransformerHandler(); 72 handler.getTransformer().setOutputProperties(format); 73 handler.setResult(new StreamResult (this.output)); 74 this.setContentHandler(handler); 75 this.setLexicalHandler(handler); 76 } catch (Exception e) { 77 final String message = "Cannot set TextSerializer outputstream"; 78 throw new CascadingIOException(message, e); 79 } 80 } 81 82 public void startElement(String uri, String loc, String raw, Attributes a) 83 throws SAXException { 84 this.hasRootElement = true; 85 super.startElement(uri, loc, raw, a); 86 } 87 88 public void characters(char c[], int start, int len) 89 throws SAXException { 90 if (!this.hasRootElement) { 91 this.hasRootElement = this.hadNoRootElement = true; 92 getLogger().warn("Encountered text before root element. Creating <text> wrapper element."); 93 super.startElement("", "text", "text", XMLUtils.EMPTY_ATTRIBUTES); 94 } 95 super.characters(c, start, len); 96 } 97 98 public void endDocument() throws SAXException { 99 if (this.hadNoRootElement) { 100 super.endElement("", "text", "text"); 101 } 102 super.endDocument(); 103 } 104 105 public void recycle() { 106 super.recycle(); 107 this.hasRootElement = false; 108 this.hadNoRootElement = false; 109 } 110 } 111 | Popular Tags |