You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

XSLTProcess.java 16 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. /*
  2. * The Apache Software License, Version 1.1
  3. *
  4. * Copyright (c) 1999 The Apache Software Foundation. All rights
  5. * reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions
  9. * are met:
  10. *
  11. * 1. Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. *
  14. * 2. Redistributions in binary form must reproduce the above copyright
  15. * notice, this list of conditions and the following disclaimer in
  16. * the documentation and/or other materials provided with the
  17. * distribution.
  18. *
  19. * 3. The end-user documentation included with the redistribution, if
  20. * any, must include the following acknowlegement:
  21. * "This product includes software developed by the
  22. * Apache Software Foundation (http://www.apache.org/)."
  23. * Alternately, this acknowlegement may appear in the software itself,
  24. * if and wherever such third-party acknowlegements normally appear.
  25. *
  26. * 4. The names "The Jakarta Project", "Ant", and "Apache Software
  27. * Foundation" must not be used to endorse or promote products derived
  28. * from this software without prior written permission. For written
  29. * permission, please contact apache@apache.org.
  30. *
  31. * 5. Products derived from this software may not be called "Apache"
  32. * nor may "Apache" appear in their names without prior written
  33. * permission of the Apache Group.
  34. *
  35. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  36. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  37. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  38. * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  39. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  41. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  42. * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  43. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  44. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  45. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  46. * SUCH DAMAGE.
  47. * ====================================================================
  48. *
  49. * This software consists of voluntary contributions made by many
  50. * individuals on behalf of the Apache Software Foundation. For more
  51. * information on the Apache Software Foundation, please see
  52. * <http://www.apache.org/>.
  53. */
  54. package org.apache.tools.ant.taskdefs;
  55. import java.io.File;
  56. import java.util.Enumeration;
  57. import java.util.Vector;
  58. import org.apache.tools.ant.BuildException;
  59. import org.apache.tools.ant.DirectoryScanner;
  60. import org.apache.tools.ant.Project;
  61. import org.apache.tools.ant.AntClassLoader;
  62. import org.apache.tools.ant.types.Path;
  63. import org.apache.tools.ant.types.Reference;
  64. import org.apache.tools.ant.util.FileUtils;
  65. /**
  66. * A Task to process via XSLT a set of XML documents. This is
  67. * useful for building views of XML based documentation.
  68. * arguments:
  69. * <ul>
  70. * <li>basedir
  71. * <li>destdir
  72. * <li>style
  73. * <li>includes
  74. * <li>excludes
  75. * </ul>
  76. * Of these arguments, the <b>sourcedir</b> and <b>destdir</b> are required.
  77. * <p>
  78. * This task will recursively scan the sourcedir and destdir
  79. * looking for XML documents to process via XSLT. Any other files,
  80. * such as images, or html files in the source directory will be
  81. * copied into the destination directory.
  82. *
  83. * @author <a href="mailto:kvisco@exoffice.com">Keith Visco</a>
  84. * @author <a href="mailto:rubys@us.ibm.com">Sam Ruby</a>
  85. * @author <a href="mailto:russgold@acm.org">Russell Gold</a>
  86. * @author <a href="stefan.bodewig@epost.de">Stefan Bodewig</a>
  87. */
  88. public class XSLTProcess extends MatchingTask {
  89. private File destDir = null;
  90. private File baseDir = null;
  91. private String xslFile = null;
  92. private String targetExtension = ".html";
  93. private Vector params = new Vector();
  94. private File inFile = null;
  95. private File outFile = null;
  96. private String processor;
  97. private Path classpath = null;
  98. private XSLTLiaison liaison;
  99. private boolean stylesheetLoaded = false;
  100. private boolean force = false;
  101. private FileUtils fileUtils;
  102. /**
  103. * Creates a new XSLTProcess Task.
  104. **/
  105. public XSLTProcess() {
  106. fileUtils = FileUtils.newFileUtils();
  107. } //-- XSLTProcess
  108. /**
  109. * Executes the task.
  110. */
  111. public void execute() throws BuildException {
  112. DirectoryScanner scanner;
  113. String[] list;
  114. String[] dirs;
  115. if (xslFile == null) {
  116. throw new BuildException("no stylesheet specified", location);
  117. }
  118. if (baseDir == null) {
  119. baseDir = project.resolveFile(".");
  120. }
  121. liaison = getLiaison();
  122. log("Using "+liaison.getClass().toString(), Project.MSG_VERBOSE);
  123. File stylesheet = project.resolveFile(xslFile);
  124. if (!stylesheet.exists()) {
  125. stylesheet = fileUtils.resolveFile(baseDir, xslFile);
  126. /*
  127. * shouldn't throw out deprecation warnings before we know,
  128. * the wrong version has been used.
  129. */
  130. if (stylesheet.exists()) {
  131. log("DEPRECATED - the style attribute should be relative to the project\'s");
  132. log(" basedir, not the tasks\'s basedir.");
  133. }
  134. }
  135. // if we have an in file and out then process them
  136. if (inFile != null && outFile != null) {
  137. process(inFile, outFile, stylesheet);
  138. return;
  139. }
  140. /*
  141. * if we get here, in and out have not been specified, we are
  142. * in batch processing mode.
  143. */
  144. //-- make sure Source directory exists...
  145. if (destDir == null ) {
  146. String msg = "destdir attributes must be set!";
  147. throw new BuildException(msg);
  148. }
  149. scanner = getDirectoryScanner(baseDir);
  150. log("Transforming into "+destDir, Project.MSG_INFO);
  151. // Process all the files marked for styling
  152. list = scanner.getIncludedFiles();
  153. for (int i = 0;i < list.length; ++i) {
  154. process( baseDir, list[i], destDir, stylesheet );
  155. }
  156. // Process all the directoried marked for styling
  157. dirs = scanner.getIncludedDirectories();
  158. for (int j = 0;j < dirs.length;++j){
  159. list=new File(baseDir,dirs[j]).list();
  160. for (int i = 0;i < list.length;++i)
  161. process( baseDir, list[i], destDir, stylesheet );
  162. }
  163. } //-- execute
  164. /**
  165. * Set whether to check dependencies, or always generate.
  166. **/
  167. public void setForce(boolean force) {
  168. this.force = force;
  169. } //-- setForce
  170. /**
  171. * Set the base directory.
  172. **/
  173. public void setBasedir(File dir) {
  174. baseDir = dir;
  175. } //-- setSourceDir
  176. /**
  177. * Set the destination directory into which the XSL result
  178. * files should be copied to
  179. * @param dirName the name of the destination directory
  180. **/
  181. public void setDestdir(File dir) {
  182. destDir = dir;
  183. } //-- setDestDir
  184. /**
  185. * Set the desired file extension to be used for the target
  186. * @param name the extension to use
  187. **/
  188. public void setExtension(String name) {
  189. targetExtension = name;
  190. } //-- setDestDir
  191. /**
  192. * Sets the file to use for styling relative to the base directory
  193. * of this task.
  194. */
  195. public void setStyle(String xslFile) {
  196. this.xslFile = xslFile;
  197. }
  198. /**
  199. * Set the classpath to load the Processor through (attribute).
  200. */
  201. public void setClasspath(Path classpath) {
  202. createClasspath().append(classpath);
  203. }
  204. /**
  205. * Set the classpath to load the Processor through (nested element).
  206. */
  207. public Path createClasspath() {
  208. if (classpath == null) {
  209. classpath = new Path(project);
  210. }
  211. return classpath.createPath();
  212. }
  213. /**
  214. * Set the classpath to load the Processor through via reference
  215. * (attribute).
  216. */
  217. public void setClasspathRef(Reference r) {
  218. createClasspath().setRefid(r);
  219. }
  220. public void setProcessor(String processor) {
  221. this.processor = processor;
  222. }
  223. /**
  224. * Load processor here instead of in setProcessor - this will be
  225. * called from within execute, so we have access to the latest
  226. * classpath.
  227. */
  228. private void resolveProcessor(String proc) throws Exception {
  229. if (proc.equals("trax")) {
  230. final Class clazz =
  231. loadClass("org.apache.tools.ant.taskdefs.optional.TraXLiaison");
  232. liaison = (XSLTLiaison)clazz.newInstance();
  233. } else if (proc.equals("xslp")) {
  234. log("DEPRECATED - xslp processor is deprecated. Use trax or xalan instead.");
  235. final Class clazz =
  236. loadClass("org.apache.tools.ant.taskdefs.optional.XslpLiaison");
  237. liaison = (XSLTLiaison) clazz.newInstance();
  238. } else if (proc.equals("xalan")) {
  239. final Class clazz =
  240. loadClass("org.apache.tools.ant.taskdefs.optional.XalanLiaison");
  241. liaison = (XSLTLiaison)clazz.newInstance();
  242. } else if (proc.equals("adaptx")) {
  243. log("DEPRECATED - adaptx processor is deprecated. Use trax or xalan instead.");
  244. final Class clazz =
  245. loadClass("org.apache.tools.ant.taskdefs.optional.AdaptxLiaison");
  246. liaison = (XSLTLiaison) clazz.newInstance();
  247. } else {
  248. liaison = (XSLTLiaison) loadClass(proc).newInstance();
  249. }
  250. }
  251. /**
  252. * Load named class either via the system classloader or a given
  253. * custom classloader.
  254. */
  255. private Class loadClass(String classname) throws Exception {
  256. if (classpath == null) {
  257. return Class.forName(classname);
  258. } else {
  259. AntClassLoader al = new AntClassLoader(project, classpath);
  260. Class c = al.loadClass(classname);
  261. AntClassLoader.initializeClass(c);
  262. return c;
  263. }
  264. }
  265. /**
  266. * Sets an out file
  267. */
  268. public void setOut(File outFile){
  269. this.outFile = outFile;
  270. }
  271. /**
  272. * Sets an input xml file to be styled
  273. */
  274. public void setIn(File inFile){
  275. this.inFile = inFile;
  276. }
  277. /**
  278. * Processes the given input XML file and stores the result
  279. * in the given resultFile.
  280. **/
  281. private void process(File baseDir, String xmlFile, File destDir,
  282. File stylesheet)
  283. throws BuildException {
  284. String fileExt=targetExtension;
  285. File outFile=null;
  286. File inFile=null;
  287. try {
  288. long styleSheetLastModified = stylesheet.lastModified();
  289. inFile = new File(baseDir,xmlFile);
  290. int dotPos = xmlFile.lastIndexOf('.');
  291. if(dotPos>0){
  292. outFile = new File(destDir,xmlFile.substring(0,xmlFile.lastIndexOf('.'))+fileExt);
  293. }else{
  294. outFile = new File(destDir,xmlFile+fileExt);
  295. }
  296. if (force ||
  297. inFile.lastModified() > outFile.lastModified() ||
  298. styleSheetLastModified > outFile.lastModified()) {
  299. ensureDirectoryFor( outFile );
  300. log("Transforming into "+destDir);
  301. configureLiaison(stylesheet);
  302. liaison.transform(inFile, outFile);
  303. }
  304. }
  305. catch (Exception ex) {
  306. // If failed to process document, must delete target document,
  307. // or it will not attempt to process it the second time
  308. log("Failed to process " + inFile, Project.MSG_INFO);
  309. if (outFile != null) {
  310. outFile.delete();
  311. }
  312. throw new BuildException(ex);
  313. }
  314. } //-- processXML
  315. private void process(File inFile, File outFile, File stylesheet) throws BuildException {
  316. try{
  317. long styleSheetLastModified = stylesheet.lastModified();
  318. log("In file "+inFile+" time: " + inFile.lastModified() , Project.MSG_DEBUG);
  319. log("Out file "+outFile+" time: " + outFile.lastModified() , Project.MSG_DEBUG);
  320. log("Style file "+xslFile+" time: " + styleSheetLastModified , Project.MSG_DEBUG);
  321. if (force ||
  322. inFile.lastModified() > outFile.lastModified() ||
  323. styleSheetLastModified > outFile.lastModified()) {
  324. ensureDirectoryFor( outFile );
  325. log("Processing " + inFile + " to " + outFile, Project.MSG_INFO);
  326. configureLiaison(stylesheet);
  327. liaison.transform(inFile, outFile);
  328. }
  329. }catch (Exception ex) {
  330. log("Failed to process " + inFile, Project.MSG_INFO);
  331. if(outFile!=null)outFile.delete();
  332. throw new BuildException(ex);
  333. }
  334. }
  335. private void ensureDirectoryFor( File targetFile ) throws BuildException {
  336. File directory = new File( targetFile.getParent() );
  337. if (!directory.exists()) {
  338. if (!directory.mkdirs()) {
  339. throw new BuildException("Unable to create directory: "
  340. + directory.getAbsolutePath() );
  341. }
  342. }
  343. }
  344. protected XSLTLiaison getLiaison() {
  345. // if processor wasn't specified, see if TraX is available. If not,
  346. // default it to xslp or xalan, depending on which is in the classpath
  347. if (liaison == null) {
  348. if (processor != null) {
  349. try {
  350. resolveProcessor(processor);
  351. } catch (Exception e) {
  352. throw new BuildException(e);
  353. }
  354. } else {
  355. try {
  356. resolveProcessor("trax");
  357. } catch (Throwable e1) {
  358. try {
  359. resolveProcessor("xalan");
  360. } catch (Throwable e2) {
  361. try {
  362. resolveProcessor("adaptx");
  363. } catch (Throwable e3) {
  364. try {
  365. resolveProcessor("xslp");
  366. } catch (Throwable e4) {
  367. e4.printStackTrace();
  368. e3.printStackTrace();
  369. e2.printStackTrace();
  370. throw new BuildException(e1);
  371. }
  372. }
  373. }
  374. }
  375. }
  376. }
  377. return liaison;
  378. }
  379. public Param createParam() {
  380. Param p = new Param();
  381. params.addElement(p);
  382. return p;
  383. }
  384. public class Param {
  385. private String name=null;
  386. private String expression=null;
  387. public void setName(String name){
  388. this.name = name;
  389. }
  390. public void setExpression(String expression){
  391. this.expression = expression;
  392. }
  393. public String getName() throws BuildException{
  394. if(name==null)throw new BuildException("Name attribute is missing.");
  395. return name;
  396. }
  397. public String getExpression() throws BuildException{
  398. if(expression==null)throw new BuildException("Expression attribute is missing.");
  399. return expression;
  400. }
  401. }
  402. /**
  403. * Loads the stylesheet and set xsl:param parameters.
  404. */
  405. protected void configureLiaison(File stylesheet) throws BuildException {
  406. if (stylesheetLoaded) {
  407. return;
  408. }
  409. stylesheetLoaded = true;
  410. try {
  411. log( "Loading stylesheet " + stylesheet, Project.MSG_INFO);
  412. liaison.setStylesheet( stylesheet );
  413. for(Enumeration e = params.elements();e.hasMoreElements();) {
  414. Param p = (Param)e.nextElement();
  415. liaison.addParam( p.getName(), p.getExpression() );
  416. }
  417. } catch (Exception ex) {
  418. log("Failed to read stylesheet " + stylesheet, Project.MSG_INFO);
  419. throw new BuildException(ex);
  420. }
  421. }
  422. } //-- XSLTProcess