1 33 34 package com.icesoft.faces.context; 35 36 import org.w3c.dom.Document ; 37 import org.w3c.dom.Node ; 38 39 import javax.xml.transform.OutputKeys ; 40 import javax.xml.transform.Result ; 41 import javax.xml.transform.Transformer ; 42 import javax.xml.transform.TransformerConfigurationException ; 43 import javax.xml.transform.TransformerException ; 44 import javax.xml.transform.TransformerFactory ; 45 import javax.xml.transform.dom.DOMSource ; 46 import javax.xml.transform.stream.StreamResult ; 47 import javax.xml.transform.stream.StreamSource ; 48 import java.io.IOException ; 49 import java.io.Writer ; 50 import java.util.Properties ; 51 52 public class JAXPSerializer implements DOMSerializer { 53 private static final TransformerFactory transformerFactory = 54 TransformerFactory.newInstance(); 55 private static Transformer PrettyPrintingTransformer; 56 private static Transformer NormalPrintingTransformer; 57 58 static { 59 try { 60 PrettyPrintingTransformer = transformerFactory 61 .newTransformer(new StreamSource ( 62 JAXPSerializer.class.getResourceAsStream( 63 "pretty-printing.xslt"))); 64 NormalPrintingTransformer = transformerFactory 65 .newTransformer(new StreamSource ( 66 JAXPSerializer.class.getResourceAsStream( 67 "normal-printing.xslt"))); 68 } catch (TransformerConfigurationException e) { 69 throw new RuntimeException (e); 70 } 71 } 72 73 private Result result; 74 private Properties properties = new Properties (); 75 private Transformer transformer = NormalPrintingTransformer; 76 77 public JAXPSerializer(Writer writer) { 78 this.result = new StreamResult (writer); 79 } 80 81 public JAXPSerializer(Writer writer, String publicId, String systemId) { 82 this.result = new StreamResult (writer); 83 properties.setProperty(OutputKeys.DOCTYPE_PUBLIC, publicId); 84 properties.setProperty(OutputKeys.DOCTYPE_SYSTEM, systemId); 85 properties.setProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); 86 } 87 88 public void serialize(Document document) throws IOException { 89 try { 90 transformer.setOutputProperties(properties); 91 transformer.transform(new DOMSource (document), result); 92 } catch (TransformerException e) { 93 throw new IOException (e.getMessage()); 94 } 95 } 96 97 public void serialize(Node node) throws IOException { 98 try { 99 transformer.setOutputProperties(properties); 100 transformer.transform(new DOMSource (node), result); 101 } catch (TransformerException e) { 102 throw new IOException (e.getMessage()); 103 } 104 } 105 106 public void printPretty() { 107 transformer = PrettyPrintingTransformer; 108 } 109 110 public void outputAsHTML() { 111 properties.setProperty(OutputKeys.METHOD, "html"); 112 } 113 114 public void outputAsXML() { 115 properties.setProperty(OutputKeys.METHOD, "xml"); 116 } 117 118 public void ommitXMLDeclaration() { 119 properties.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); 120 } 121 } 122 | Popular Tags |