1 22 package org.jboss.deployers.plugins.deployers.helpers; 23 24 import java.io.InputStream ; 25 26 import javax.xml.transform.Source ; 27 import javax.xml.transform.Templates ; 28 import javax.xml.transform.Transformer ; 29 import javax.xml.transform.TransformerFactory ; 30 import javax.xml.transform.dom.DOMResult ; 31 import javax.xml.transform.dom.DOMSource ; 32 import javax.xml.transform.stream.StreamSource ; 33 34 import org.jboss.deployers.spi.deployer.DeploymentUnit; 35 import org.jboss.util.xml.DOMWriter; 36 import org.jboss.util.xml.JBossErrorHandler; 37 import org.jboss.virtual.VirtualFile; 38 import org.w3c.dom.Document ; 39 40 47 public abstract class XSLDeployer<T> extends JAXPDeployer<T> 48 { 49 50 protected String xslPath; 51 52 53 private Templates templates; 54 55 61 public XSLDeployer(Class <T> deploymentType) 62 { 63 super(deploymentType); 64 } 65 66 71 public String getXSLPath() 72 { 73 return xslPath; 74 } 75 76 81 public void setXSLPath(String xslPath) 82 { 83 this.xslPath = xslPath; 84 } 85 86 92 public Templates getTemplates() 93 { 94 if (templates == null) 95 throw new IllegalStateException ("Templates have not been constructed"); 96 return templates; 97 } 98 99 104 public void create() throws Exception 105 { 106 super.create(); 107 108 TransformerFactory tf = TransformerFactory.newInstance(); 109 110 InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(xslPath); 111 try 112 { 113 StreamSource ss = new StreamSource (is); 114 ss.setSystemId(xslPath); 115 templates = tf.newTemplates(ss); 116 log.debug("Created templates: " + templates); 117 } 118 finally 119 { 120 try 121 { 122 is.close(); 123 } 124 catch (Exception ignored) 125 { 126 } 127 } 128 } 129 130 133 public void destroy() 134 { 135 super.destroy(); 136 templates = null; 137 } 138 139 @Override 140 protected T parse(DeploymentUnit unit, VirtualFile file, T root) throws Exception 141 { 142 if (file == null) 143 throw new IllegalArgumentException ("Null file"); 144 145 Document document = doParse(unit, file); 146 147 Transformer trans = getTemplates().newTransformer(); 148 trans.setErrorListener(new JBossErrorHandler(file.getPathName(), null)); 149 Source s = new DOMSource (document); 150 DOMResult r = new DOMResult (); 151 setParameters(trans); 152 153 trans.transform(s, r); 154 155 document = (Document ) r.getNode(); 156 String docStr = DOMWriter.printNode(document, true); 157 log.debug("Transformed " + file.getPathName() + " into " + docStr); 158 159 return parse(unit, file, document); 160 } 161 162 168 protected void setParameters(Transformer trans) throws Exception 169 { 170 } 172 173 182 protected abstract T parse(DeploymentUnit unit, VirtualFile file, Document document) throws Exception ; 183 } 184 | Popular Tags |