1 22 23 package org.continuent.sequoia.common.xml; 24 25 import java.io.StringReader ; 26 import java.io.StringWriter ; 27 28 import javax.xml.transform.Transformer ; 29 import javax.xml.transform.TransformerFactory ; 30 import javax.xml.transform.stream.StreamResult ; 31 import javax.xml.transform.stream.StreamSource ; 32 33 import org.continuent.sequoia.common.i18n.Translate; 34 import org.continuent.sequoia.common.log.Trace; 35 36 42 public final class XmlTools 43 { 44 45 46 static Trace logger = Trace 47 .getLogger("org.continuent.sequoia.common.xml"); 48 49 private static final String PRETTIFY_XSL = "org/continuent/sequoia/common/xml/prettify.xsl"; 50 51 52 private static TransformerFactory tFactory; 53 private static Transformer infoTransformer; 54 55 62 public static String prettyXml(String xml) throws Exception 63 { 64 return applyXsl(xml, PRETTIFY_XSL); 65 } 66 67 74 private static String applyXsl(String xml, String xsl) 75 { 76 try 77 { 78 StringWriter result = new StringWriter (); 79 if (tFactory == null) 80 tFactory = TransformerFactory.newInstance(); 81 if (logger.isDebugEnabled()) 82 logger.debug(Translate.get("controller.xml.use.xsl", xsl)); 83 infoTransformer = tFactory.newTransformer(new StreamSource (ClassLoader 85 .getSystemResourceAsStream(xsl))); 86 infoTransformer.transform(new StreamSource (new StringReader (xml)), 87 new StreamResult (result)); 88 return result.toString(); 89 } 90 catch (Exception e) 91 { 92 String msg = Translate.get("controller.xml.transformation.failed", e); 93 94 if (logger.isDebugEnabled()) 95 logger.debug(msg, e); 96 logger.error(msg, e); 97 return msg; 98 } 99 } 100 101 112 public static String insertDoctype(String xml, String doctype) 113 { 114 int index = xml.indexOf("?>"); 115 if (index < 0) 116 { 117 return xml; 118 } 119 String xmlWithDoctype = xml.substring(0, index + 2); 120 xmlWithDoctype += "\n"; 121 xmlWithDoctype += doctype; 122 xmlWithDoctype += "\n"; 123 xmlWithDoctype += xml.substring(index + 3, xml.length()); 124 return xmlWithDoctype; 125 } 126 } | Popular Tags |