1 16 package com.ibatis.db.sqlmap.upgrade; 17 18 import com.ibatis.common.exception.NestedRuntimeException; 19 import com.ibatis.common.resources.Resources; 20 import com.ibatis.sqlmap.client.SqlMapException; 21 import com.ibatis.sqlmap.engine.builder.xml.XmlConverter; 22 23 import javax.xml.transform.Transformer ; 24 import javax.xml.transform.TransformerException ; 25 import javax.xml.transform.TransformerFactory ; 26 import javax.xml.transform.stream.StreamResult ; 27 import javax.xml.transform.stream.StreamSource ; 28 import java.io.*; 29 30 public class SqlMapXmlConverter implements XmlConverter { 31 32 public void convertXml(Reader reader, Writer writer) { 33 try { 34 DocTypeReader xml = new DocTypeReader(reader); 35 String docType = xml.getDocType(); 36 Reader xsl = null; 37 if (docType == null) { 38 throw new SqlMapException("Could not convert document because DOCTYPE was null."); 39 } else { 40 if (docType.indexOf("sql-map-config") > -1) { 41 xsl = Resources.getResourceAsReader("com/ibatis/db/sqlmap/upgrade/SqlMapConfig.xsl"); 42 } else if (docType.indexOf("sql-map") > -1) { 43 xsl = Resources.getResourceAsReader("com/ibatis/db/sqlmap/upgrade/SqlMap.xsl"); 44 } else { 45 throw new SqlMapException("Could not convert document because DOCTYPE was not recognized: " + docType); 46 } 47 } 48 transformXml(xsl, xml, writer); 49 } catch (IOException e) { 50 throw new NestedRuntimeException("Error. Cause: " + e, e); 51 } catch (TransformerException e) { 52 throw new NestedRuntimeException("Error. Cause: " + e, e); 53 } 54 } 55 56 public Reader convertXml(Reader reader) { 57 StringWriter out = new StringWriter(); 58 convertXml(reader, out); 59 return new StringReader(out.getBuffer().toString()); 60 } 61 62 public void convertFile(String fromFileName, String toFileName) throws IOException { 63 File fromFile = new File(fromFileName); 64 File toFile = new File(toFileName); 65 convertFile(fromFile, toFile); 66 } 67 68 public void convertFile(File fromFile, File toFile) throws IOException { 69 Reader reader = new FileReader(fromFile); 70 Writer writer = new FileWriter(toFile); 71 convertXml(reader, writer); 72 writer.flush(); 73 writer.close(); 74 reader.close(); 75 } 76 77 protected void transformXml(Reader xslReader, Reader xmlReader, Writer xmlWriter) throws TransformerException { 78 StreamSource xslSource = new StreamSource (xslReader); 79 StreamSource xmlSource = new StreamSource (xmlReader); 80 StreamResult xmlResult = new StreamResult (xmlWriter); 81 82 TransformerFactory transformerFactory = TransformerFactory.newInstance(); 83 Transformer transformer = transformerFactory.newTransformer(xslSource); 84 transformer.setParameter("http://xml.org/sax/features/validation", new Boolean (false)); 85 transformer.setParameter("http://apache.org/xml/features/nonvalidating/load-dtd", new Boolean (false)); 86 87 transformer.transform(xmlSource, xmlResult); 88 } 89 90 } 91 92 | Popular Tags |