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 55 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package org.apache.tools.ant.taskdefs;
  19. import java.io.File;
  20. import java.util.ArrayList;
  21. import java.util.Collections;
  22. import java.util.EnumMap;
  23. import java.util.Enumeration;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.Vector;
  27. import javax.xml.namespace.QName;
  28. import javax.xml.xpath.XPath;
  29. import javax.xml.xpath.XPathConstants;
  30. import javax.xml.xpath.XPathExpression;
  31. import javax.xml.xpath.XPathExpressionException;
  32. import javax.xml.xpath.XPathFactory;
  33. import javax.xml.xpath.XPathVariableResolver;
  34. import org.apache.tools.ant.AntClassLoader;
  35. import org.apache.tools.ant.BuildException;
  36. import org.apache.tools.ant.DirectoryScanner;
  37. import org.apache.tools.ant.DynamicConfigurator;
  38. import org.apache.tools.ant.Project;
  39. import org.apache.tools.ant.PropertyHelper;
  40. import org.apache.tools.ant.types.CommandlineJava;
  41. import org.apache.tools.ant.types.Environment;
  42. import org.apache.tools.ant.types.Mapper;
  43. import org.apache.tools.ant.types.Path;
  44. import org.apache.tools.ant.types.PropertySet;
  45. import org.apache.tools.ant.types.Reference;
  46. import org.apache.tools.ant.types.Resource;
  47. import org.apache.tools.ant.types.ResourceCollection;
  48. import org.apache.tools.ant.types.XMLCatalog;
  49. import org.apache.tools.ant.types.resources.FileProvider;
  50. import org.apache.tools.ant.types.resources.FileResource;
  51. import org.apache.tools.ant.types.resources.Resources;
  52. import org.apache.tools.ant.types.resources.Union;
  53. import org.apache.tools.ant.util.FileNameMapper;
  54. import org.apache.tools.ant.util.FileUtils;
  55. import org.apache.tools.ant.util.ResourceUtils;
  56. /**
  57. * Processes a set of XML documents via XSLT. This is
  58. * useful for building views of XML based documentation.
  59. *
  60. *
  61. * @since Ant 1.1
  62. *
  63. * @ant.task name="xslt" category="xml"
  64. */
  65. public class XSLTProcess extends MatchingTask implements XSLTLogger {
  66. /** destination directory */
  67. private File destDir = null;
  68. /** where to find the source XML file, default is the project's basedir */
  69. private File baseDir = null;
  70. /** XSL stylesheet as a filename */
  71. private String xslFile = null;
  72. /** XSL stylesheet as a {@link org.apache.tools.ant.types.Resource} */
  73. private Resource xslResource = null;
  74. /** extension of the files produced by XSL processing */
  75. private String targetExtension = ".html";
  76. /** name for XSL parameter containing the filename */
  77. private String fileNameParameter = null;
  78. /** name for XSL parameter containing the file directory */
  79. private String fileDirParameter = null;
  80. /** additional parameters to be passed to the stylesheets */
  81. private final List<Param> params = new ArrayList<Param>();
  82. /** Input XML document to be used */
  83. private File inFile = null;
  84. /** Output file */
  85. private File outFile = null;
  86. /** The name of the XSL processor to use */
  87. private String processor;
  88. /** Classpath to use when trying to load the XSL processor */
  89. private Path classpath = null;
  90. /** The Liaison implementation to use to communicate with the XSL
  91. * processor */
  92. private XSLTLiaison liaison;
  93. /** Flag which indicates if the stylesheet has been loaded into
  94. * the processor */
  95. private boolean stylesheetLoaded = false;
  96. /** force output of target files even if they already exist */
  97. private boolean force = false;
  98. /** XSL output properties to be used */
  99. private final Vector outputProperties = new Vector();
  100. /** for resolving entities such as dtds */
  101. private final XMLCatalog xmlCatalog = new XMLCatalog();
  102. /** Utilities used for file operations */
  103. private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
  104. /**
  105. * Whether to style all files in the included directories as well.
  106. *
  107. * @since Ant 1.5
  108. */
  109. private boolean performDirectoryScan = true;
  110. /**
  111. * factory element for TraX processors only
  112. * @since Ant 1.6
  113. */
  114. private Factory factory = null;
  115. /**
  116. * whether to reuse Transformer if transforming multiple files.
  117. * @since 1.5.2
  118. */
  119. private boolean reuseLoadedStylesheet = true;
  120. /**
  121. * AntClassLoader for the nested &lt;classpath&gt; - if set.
  122. *
  123. * <p>We keep this here in order to reset the context classloader
  124. * in execute. We can't use liaison.getClass().getClassLoader()
  125. * since the actual liaison class may have been loaded by a loader
  126. * higher up (system classloader, for example).</p>
  127. *
  128. * @since Ant 1.6.2
  129. */
  130. private AntClassLoader loader = null;
  131. /**
  132. * Mapper to use when a set of files gets processed.
  133. *
  134. * @since Ant 1.6.2
  135. */
  136. private Mapper mapperElement = null;
  137. /**
  138. * Additional resource collections to process.
  139. *
  140. * @since Ant 1.7
  141. */
  142. private final Union resources = new Union();
  143. /**
  144. * Whether to use the implicit fileset.
  145. *
  146. * @since Ant 1.7
  147. */
  148. private boolean useImplicitFileset = true;
  149. /**
  150. * The default processor is trax
  151. * @since Ant 1.7
  152. */
  153. public static final String PROCESSOR_TRAX = "trax";
  154. /**
  155. * whether to suppress warnings.
  156. *
  157. * @since Ant 1.8.0
  158. */
  159. private boolean suppressWarnings = false;
  160. /**
  161. * whether to fail the build if an error occurs during transformation.
  162. *
  163. * @since Ant 1.8.0
  164. */
  165. private boolean failOnTransformationError = true;
  166. /**
  167. * whether to fail the build if an error occurs.
  168. *
  169. * @since Ant 1.8.0
  170. */
  171. private boolean failOnError = true;
  172. /**
  173. * Whether the build should fail if the nested resource collection
  174. * is empty.
  175. *
  176. * @since Ant 1.8.0
  177. */
  178. private boolean failOnNoResources = true;
  179. /**
  180. * For evaluating template params
  181. *
  182. * @since Ant 1.9.3
  183. */
  184. private XPathFactory xpathFactory;
  185. /**
  186. * For evaluating template params
  187. *
  188. * @since Ant 1.9.3
  189. */
  190. private XPath xpath;
  191. /**
  192. * System properties to set during transformation.
  193. *
  194. * @since Ant 1.8.0
  195. */
  196. private final CommandlineJava.SysProperties sysProperties =
  197. new CommandlineJava.SysProperties();
  198. /**
  199. * Trace configuration for Xalan2.
  200. *
  201. * @since Ant 1.8.0
  202. */
  203. private TraceConfiguration traceConfiguration;
  204. /**
  205. * Creates a new XSLTProcess Task.
  206. */
  207. public XSLTProcess() {
  208. } //-- XSLTProcess
  209. /**
  210. * Whether to style all files in the included directories as well;
  211. * optional, default is true.
  212. *
  213. * @param b true if files in included directories are processed.
  214. * @since Ant 1.5
  215. */
  216. public void setScanIncludedDirectories(final boolean b) {
  217. performDirectoryScan = b;
  218. }
  219. /**
  220. * Controls whether the stylesheet is reloaded for every transform.
  221. *
  222. * <p>Setting this to true may get around a bug in certain
  223. * Xalan-J versions, default is false.</p>
  224. * @param b a <code>boolean</code> value
  225. * @since Ant 1.5.2
  226. */
  227. public void setReloadStylesheet(final boolean b) {
  228. reuseLoadedStylesheet = !b;
  229. }
  230. /**
  231. * Defines the mapper to map source to destination files.
  232. * @param mapper the mapper to use
  233. * @exception BuildException if more than one mapper is defined
  234. * @since Ant 1.6.2
  235. */
  236. public void addMapper(final Mapper mapper) {
  237. if (mapperElement != null) {
  238. handleError("Cannot define more than one mapper");
  239. } else {
  240. mapperElement = mapper;
  241. }
  242. }
  243. /**
  244. * Adds a collection of resources to style in addition to the
  245. * given file or the implicit fileset.
  246. *
  247. * @param rc the collection of resources to style
  248. * @since Ant 1.7
  249. */
  250. public void add(final ResourceCollection rc) {
  251. resources.add(rc);
  252. }
  253. /**
  254. * Add a nested &lt;style&gt; element.
  255. * @param rc the configured Resources object represented as &lt;style&gt;.
  256. * @since Ant 1.7
  257. */
  258. public void addConfiguredStyle(final Resources rc) {
  259. if (rc.size() != 1) {
  260. handleError("The style element must be specified with exactly one"
  261. + " nested resource.");
  262. } else {
  263. setXslResource(rc.iterator().next());
  264. }
  265. }
  266. /**
  267. * API method to set the XSL Resource.
  268. * @param xslResource Resource to set as the stylesheet.
  269. * @since Ant 1.7
  270. */
  271. public void setXslResource(final Resource xslResource) {
  272. this.xslResource = xslResource;
  273. }
  274. /**
  275. * Adds a nested filenamemapper.
  276. * @param fileNameMapper the mapper to add
  277. * @exception BuildException if more than one mapper is defined
  278. * @since Ant 1.7.0
  279. */
  280. public void add(final FileNameMapper fileNameMapper) throws BuildException {
  281. final Mapper mapper = new Mapper(getProject());
  282. mapper.add(fileNameMapper);
  283. addMapper(mapper);
  284. }
  285. /**
  286. * Executes the task.
  287. *
  288. * @exception BuildException if there is an execution problem.
  289. * @todo validate that if either in or out is defined, then both are
  290. */
  291. @Override
  292. public void execute() throws BuildException {
  293. if ("style".equals(getTaskType())) {
  294. log("Warning: the task name <style> is deprecated. Use <xslt> instead.",
  295. Project.MSG_WARN);
  296. }
  297. final File savedBaseDir = baseDir;
  298. DirectoryScanner scanner;
  299. String[] list;
  300. String[] dirs;
  301. final String baseMessage =
  302. "specify the stylesheet either as a filename in style attribute "
  303. + "or as a nested resource";
  304. if (xslResource == null && xslFile == null) {
  305. handleError(baseMessage);
  306. return;
  307. }
  308. if (xslResource != null && xslFile != null) {
  309. handleError(baseMessage + " but not as both");
  310. return;
  311. }
  312. if (inFile != null && !inFile.exists()) {
  313. handleError("input file " + inFile + " does not exist");
  314. return;
  315. }
  316. try {
  317. setupLoader();
  318. if (sysProperties.size() > 0) {
  319. sysProperties.setSystem();
  320. }
  321. Resource styleResource;
  322. if (baseDir == null) {
  323. baseDir = getProject().getBaseDir();
  324. }
  325. liaison = getLiaison();
  326. // check if liaison wants to log errors using us as logger
  327. if (liaison instanceof XSLTLoggerAware) {
  328. ((XSLTLoggerAware) liaison).setLogger(this);
  329. }
  330. log("Using " + liaison.getClass().toString(), Project.MSG_VERBOSE);
  331. if (xslFile != null) {
  332. // If we enter here, it means that the stylesheet is supplied
  333. // via style attribute
  334. File stylesheet = getProject().resolveFile(xslFile);
  335. if (!stylesheet.exists()) {
  336. final File alternative = FILE_UTILS.resolveFile(baseDir, xslFile);
  337. /*
  338. * shouldn't throw out deprecation warnings before we know,
  339. * the wrong version has been used.
  340. */
  341. if (alternative.exists()) {
  342. log("DEPRECATED - the 'style' attribute should be "
  343. + "relative to the project's");
  344. log(" basedir, not the tasks's basedir.");
  345. stylesheet = alternative;
  346. }
  347. }
  348. final FileResource fr = new FileResource();
  349. fr.setProject(getProject());
  350. fr.setFile(stylesheet);
  351. styleResource = fr;
  352. } else {
  353. styleResource = xslResource;
  354. }
  355. if (!styleResource.isExists()) {
  356. handleError("stylesheet " + styleResource + " doesn't exist.");
  357. return;
  358. }
  359. // if we have an in file and out then process them
  360. if (inFile != null && outFile != null) {
  361. process(inFile, outFile, styleResource);
  362. return;
  363. }
  364. /*
  365. * if we get here, in and out have not been specified, we are
  366. * in batch processing mode.
  367. */
  368. //-- make sure destination directory exists...
  369. checkDest();
  370. if (useImplicitFileset) {
  371. scanner = getDirectoryScanner(baseDir);
  372. log("Transforming into " + destDir, Project.MSG_INFO);
  373. // Process all the files marked for styling
  374. list = scanner.getIncludedFiles();
  375. for (int i = 0; i < list.length; ++i) {
  376. process(baseDir, list[i], destDir, styleResource);
  377. }
  378. if (performDirectoryScan) {
  379. // Process all the directories marked for styling
  380. dirs = scanner.getIncludedDirectories();
  381. for (int j = 0; j < dirs.length; ++j) {
  382. list = new File(baseDir, dirs[j]).list();
  383. for (int i = 0; i < list.length; ++i) {
  384. process(baseDir, dirs[j] + File.separator + list[i], destDir,
  385. styleResource);
  386. }
  387. }
  388. }
  389. } else { // only resource collections, there better be some
  390. if (resources.size() == 0) {
  391. if (failOnNoResources) {
  392. handleError("no resources specified");
  393. }
  394. return;
  395. }
  396. }
  397. processResources(styleResource);
  398. } finally {
  399. if (loader != null) {
  400. loader.resetThreadContextLoader();
  401. loader.cleanup();
  402. loader = null;
  403. }
  404. if (sysProperties.size() > 0) {
  405. sysProperties.restoreSystem();
  406. }
  407. liaison = null;
  408. stylesheetLoaded = false;
  409. baseDir = savedBaseDir;
  410. }
  411. }
  412. /**
  413. * Set whether to check dependencies, or always generate;
  414. * optional, default is false.
  415. *
  416. * @param force true if always generate.
  417. */
  418. public void setForce(final boolean force) {
  419. this.force = force;
  420. }
  421. /**
  422. * Set the base directory;
  423. * optional, default is the project's basedir.
  424. *
  425. * @param dir the base directory
  426. **/
  427. public void setBasedir(final File dir) {
  428. baseDir = dir;
  429. }
  430. /**
  431. * Set the destination directory into which the XSL result
  432. * files should be copied to;
  433. * required, unless <tt>in</tt> and <tt>out</tt> are
  434. * specified.
  435. * @param dir the name of the destination directory
  436. **/
  437. public void setDestdir(final File dir) {
  438. destDir = dir;
  439. }
  440. /**
  441. * Set the desired file extension to be used for the target;
  442. * optional, default is html.
  443. * @param name the extension to use
  444. **/
  445. public void setExtension(final String name) {
  446. targetExtension = name;
  447. }
  448. /**
  449. * Name of the stylesheet to use - given either relative
  450. * to the project's basedir or as an absolute path; required.
  451. *
  452. * @param xslFile the stylesheet to use
  453. */
  454. public void setStyle(final String xslFile) {
  455. this.xslFile = xslFile;
  456. }
  457. /**
  458. * Set the optional classpath to the XSL processor
  459. *
  460. * @param classpath the classpath to use when loading the XSL processor
  461. */
  462. public void setClasspath(final Path classpath) {
  463. createClasspath().append(classpath);
  464. }
  465. /**
  466. * Set the optional classpath to the XSL processor
  467. *
  468. * @return a path instance to be configured by the Ant core.
  469. */
  470. public Path createClasspath() {
  471. if (classpath == null) {
  472. classpath = new Path(getProject());
  473. }
  474. return classpath.createPath();
  475. }
  476. /**
  477. * Set the reference to an optional classpath to the XSL processor
  478. *
  479. * @param r the id of the Ant path instance to act as the classpath
  480. * for loading the XSL processor
  481. */
  482. public void setClasspathRef(final Reference r) {
  483. createClasspath().setRefid(r);
  484. }
  485. /**
  486. * Set the name of the XSL processor to use; optional, default trax.
  487. *
  488. * @param processor the name of the XSL processor
  489. */
  490. public void setProcessor(final String processor) {
  491. this.processor = processor;
  492. }
  493. /**
  494. * Whether to use the implicit fileset.
  495. *
  496. * <p>Set this to false if you want explicit control with nested
  497. * resource collections.</p>
  498. * @param useimplicitfileset set to true if you want to use implicit fileset
  499. * @since Ant 1.7
  500. */
  501. public void setUseImplicitFileset(final boolean useimplicitfileset) {
  502. useImplicitFileset = useimplicitfileset;
  503. }
  504. /**
  505. * Add the catalog to our internal catalog
  506. *
  507. * @param xmlCatalog the XMLCatalog instance to use to look up DTDs
  508. */
  509. public void addConfiguredXMLCatalog(final XMLCatalog xmlCatalog) {
  510. this.xmlCatalog.addConfiguredXMLCatalog(xmlCatalog);
  511. }
  512. /**
  513. * Pass the filename of the current processed file as a xsl parameter
  514. * to the transformation. This value sets the name of that xsl parameter.
  515. *
  516. * @param fileNameParameter name of the xsl parameter retrieving the
  517. * current file name
  518. */
  519. public void setFileNameParameter(final String fileNameParameter) {
  520. this.fileNameParameter = fileNameParameter;
  521. }
  522. /**
  523. * Pass the directory name of the current processed file as a xsl parameter
  524. * to the transformation. This value sets the name of that xsl parameter.
  525. *
  526. * @param fileDirParameter name of the xsl parameter retrieving the
  527. * current file directory
  528. */
  529. public void setFileDirParameter(final String fileDirParameter) {
  530. this.fileDirParameter = fileDirParameter;
  531. }
  532. /**
  533. * Whether to suppress warning messages of the processor.
  534. *
  535. * @since Ant 1.8.0
  536. */
  537. public void setSuppressWarnings(final boolean b) {
  538. suppressWarnings = b;
  539. }
  540. /**
  541. * Whether to suppress warning messages of the processor.
  542. *
  543. * @since Ant 1.8.0
  544. */
  545. public boolean getSuppressWarnings() {
  546. return suppressWarnings;
  547. }
  548. /**
  549. * Whether transformation errors should make the build fail.
  550. *
  551. * @since Ant 1.8.0
  552. */
  553. public void setFailOnTransformationError(final boolean b) {
  554. failOnTransformationError = b;
  555. }
  556. /**
  557. * Whether any errors should make the build fail.
  558. *
  559. * @since Ant 1.8.0
  560. */
  561. public void setFailOnError(final boolean b) {
  562. failOnError = b;
  563. }
  564. /**
  565. * Whether the build should fail if the nested resource collection is empty.
  566. *
  567. * @since Ant 1.8.0
  568. */
  569. public void setFailOnNoResources(final boolean b) {
  570. failOnNoResources = b;
  571. }
  572. /**
  573. * A system property to set during transformation.
  574. *
  575. * @since Ant 1.8.0
  576. */
  577. public void addSysproperty(final Environment.Variable sysp) {
  578. sysProperties.addVariable(sysp);
  579. }
  580. /**
  581. * A set of system properties to set during transformation.
  582. *
  583. * @since Ant 1.8.0
  584. */
  585. public void addSyspropertyset(final PropertySet sysp) {
  586. sysProperties.addSyspropertyset(sysp);
  587. }
  588. /**
  589. * Enables Xalan2 traces and uses the given configuration.
  590. *
  591. * <p>Note that this element doesn't have any effect with a
  592. * processor other than trax or if the Transformer is not Xalan2's
  593. * transformer implementation.</p>
  594. *
  595. * @since Ant 1.8.0
  596. */
  597. public TraceConfiguration createTrace() {
  598. if (traceConfiguration != null) {
  599. throw new BuildException("can't have more than one trace"
  600. + " configuration");
  601. }
  602. traceConfiguration = new TraceConfiguration();
  603. return traceConfiguration;
  604. }
  605. /**
  606. * Configuration for Xalan2 traces.
  607. *
  608. * @since Ant 1.8.0
  609. */
  610. public TraceConfiguration getTraceConfiguration() {
  611. return traceConfiguration;
  612. }
  613. /**
  614. * Load processor here instead of in setProcessor - this will be
  615. * called from within execute, so we have access to the latest
  616. * classpath.
  617. *
  618. * @param proc the name of the processor to load.
  619. * @exception Exception if the processor cannot be loaded.
  620. */
  621. private void resolveProcessor(final String proc) throws Exception {
  622. if (proc.equals(PROCESSOR_TRAX)) {
  623. liaison = new org.apache.tools.ant.taskdefs.optional.TraXLiaison();
  624. } else {
  625. //anything else is a classname
  626. final Class clazz = loadClass(proc);
  627. liaison = (XSLTLiaison) clazz.newInstance();
  628. }
  629. }
  630. /**
  631. * Load named class either via the system classloader or a given
  632. * custom classloader.
  633. *
  634. * As a side effect, the loader is set as the thread context classloader
  635. * @param classname the name of the class to load.
  636. * @return the requested class.
  637. * @exception Exception if the class could not be loaded.
  638. */
  639. private Class loadClass(final String classname) throws Exception {
  640. setupLoader();
  641. if (loader == null) {
  642. return Class.forName(classname);
  643. }
  644. return Class.forName(classname, true, loader);
  645. }
  646. /**
  647. * If a custom classpath has been defined but no loader created
  648. * yet, create the classloader and set it as the context
  649. * classloader.
  650. */
  651. private void setupLoader() {
  652. if (classpath != null && loader == null) {
  653. loader = getProject().createClassLoader(classpath);
  654. loader.setThreadContextLoader();
  655. }
  656. }
  657. /**
  658. * Specifies the output name for the styled result from the
  659. * <tt>in</tt> attribute; required if <tt>in</tt> is set
  660. *
  661. * @param outFile the output File instance.
  662. */
  663. public void setOut(final File outFile) {
  664. this.outFile = outFile;
  665. }
  666. /**
  667. * specifies a single XML document to be styled. Should be used
  668. * with the <tt>out</tt> attribute; ; required if <tt>out</tt> is set
  669. *
  670. * @param inFile the input file
  671. */
  672. public void setIn(final File inFile) {
  673. this.inFile = inFile;
  674. }
  675. /**
  676. * Throws a BuildException if the destination directory hasn't
  677. * been specified.
  678. * @since Ant 1.7
  679. */
  680. private void checkDest() {
  681. if (destDir == null) {
  682. handleError("destdir attributes must be set!");
  683. }
  684. }
  685. /**
  686. * Styles all existing resources.
  687. *
  688. * @param stylesheet style sheet to use
  689. * @since Ant 1.7
  690. */
  691. private void processResources(final Resource stylesheet) {
  692. for (final Resource r : resources) {
  693. if (!r.isExists()) {
  694. continue;
  695. }
  696. File base = baseDir;
  697. String name = r.getName();
  698. final FileProvider fp = r.as(FileProvider.class);
  699. if (fp != null) {
  700. final FileResource f = ResourceUtils.asFileResource(fp);
  701. base = f.getBaseDir();
  702. if (base == null) {
  703. name = f.getFile().getAbsolutePath();
  704. }
  705. }
  706. process(base, name, destDir, stylesheet);
  707. }
  708. }
  709. /**
  710. * Processes the given input XML file and stores the result
  711. * in the given resultFile.
  712. *
  713. * @param baseDir the base directory for resolving files.
  714. * @param xmlFile the input file
  715. * @param destDir the destination directory
  716. * @param stylesheet the stylesheet to use.
  717. * @exception BuildException if the processing fails.
  718. */
  719. private void process(final File baseDir, final String xmlFile, final File destDir, final Resource stylesheet)
  720. throws BuildException {
  721. File outF = null;
  722. File inF = null;
  723. try {
  724. final long styleSheetLastModified = stylesheet.getLastModified();
  725. inF = new File(baseDir, xmlFile);
  726. if (inF.isDirectory()) {
  727. log("Skipping " + inF + " it is a directory.", Project.MSG_VERBOSE);
  728. return;
  729. }
  730. FileNameMapper mapper = null;
  731. if (mapperElement != null) {
  732. mapper = mapperElement.getImplementation();
  733. } else {
  734. mapper = new StyleMapper();
  735. }
  736. final String[] outFileName = mapper.mapFileName(xmlFile);
  737. if (outFileName == null || outFileName.length == 0) {
  738. log("Skipping " + inFile + " it cannot get mapped to output.", Project.MSG_VERBOSE);
  739. return;
  740. } else if (outFileName == null || outFileName.length > 1) {
  741. log("Skipping " + inFile + " its mapping is ambiguos.", Project.MSG_VERBOSE);
  742. return;
  743. }
  744. outF = new File(destDir, outFileName[0]);
  745. if (force || inF.lastModified() > outF.lastModified()
  746. || styleSheetLastModified > outF.lastModified()) {
  747. ensureDirectoryFor(outF);
  748. log("Processing " + inF + " to " + outF);
  749. configureLiaison(stylesheet);
  750. setLiaisonDynamicFileParameters(liaison, inF);
  751. liaison.transform(inF, outF);
  752. }
  753. } catch (final Exception ex) {
  754. // If failed to process document, must delete target document,
  755. // or it will not attempt to process it the second time
  756. log("Failed to process " + inFile, Project.MSG_INFO);
  757. if (outF != null) {
  758. outF.delete();
  759. }
  760. handleTransformationError(ex);
  761. }
  762. } //-- processXML
  763. /**
  764. * Process the input file to the output file with the given stylesheet.
  765. *
  766. * @param inFile the input file to process.
  767. * @param outFile the destination file.
  768. * @param stylesheet the stylesheet to use.
  769. * @exception BuildException if the processing fails.
  770. */
  771. private void process(final File inFile, final File outFile, final Resource stylesheet) throws BuildException {
  772. try {
  773. final long styleSheetLastModified = stylesheet.getLastModified();
  774. log("In file " + inFile + " time: " + inFile.lastModified(), Project.MSG_DEBUG);
  775. log("Out file " + outFile + " time: " + outFile.lastModified(), Project.MSG_DEBUG);
  776. log("Style file " + xslFile + " time: " + styleSheetLastModified, Project.MSG_DEBUG);
  777. if (force || inFile.lastModified() >= outFile.lastModified()
  778. || styleSheetLastModified >= outFile.lastModified()) {
  779. ensureDirectoryFor(outFile);
  780. log("Processing " + inFile + " to " + outFile, Project.MSG_INFO);
  781. configureLiaison(stylesheet);
  782. setLiaisonDynamicFileParameters(liaison, inFile);
  783. liaison.transform(inFile, outFile);
  784. } else {
  785. log("Skipping input file " + inFile + " because it is older than output file "
  786. + outFile + " and so is the stylesheet " + stylesheet, Project.MSG_DEBUG);
  787. }
  788. } catch (final Exception ex) {
  789. log("Failed to process " + inFile, Project.MSG_INFO);
  790. if (outFile != null) {
  791. outFile.delete();
  792. }
  793. handleTransformationError(ex);
  794. }
  795. }
  796. /**
  797. * Ensure the directory exists for a given file
  798. *
  799. * @param targetFile the file for which the directories are required.
  800. * @exception BuildException if the directories cannot be created.
  801. */
  802. private void ensureDirectoryFor(final File targetFile) throws BuildException {
  803. final File directory = targetFile.getParentFile();
  804. if (!directory.exists()) {
  805. if (!(directory.mkdirs() || directory.isDirectory())) {
  806. handleError("Unable to create directory: "
  807. + directory.getAbsolutePath());
  808. }
  809. }
  810. }
  811. /**
  812. * Get the factory instance configured for this processor
  813. *
  814. * @return the factory instance in use
  815. */
  816. public Factory getFactory() {
  817. return factory;
  818. }
  819. /**
  820. * Get the XML catalog containing entity definitions
  821. *
  822. * @return the XML catalog for the task.
  823. */
  824. public XMLCatalog getXMLCatalog() {
  825. xmlCatalog.setProject(getProject());
  826. return xmlCatalog;
  827. }
  828. /**
  829. * Get an enumeration on the outputproperties.
  830. * @return the outputproperties
  831. */
  832. public Enumeration getOutputProperties() {
  833. return outputProperties.elements();
  834. }
  835. /**
  836. * Get the Liaison implementation to use in processing.
  837. *
  838. * @return an instance of the XSLTLiaison interface.
  839. */
  840. protected XSLTLiaison getLiaison() {
  841. // if processor wasn't specified, use TraX.
  842. if (liaison == null) {
  843. if (processor != null) {
  844. try {
  845. resolveProcessor(processor);
  846. } catch (final Exception e) {
  847. handleError(e);
  848. }
  849. } else {
  850. try {
  851. resolveProcessor(PROCESSOR_TRAX);
  852. } catch (final Throwable e1) {
  853. e1.printStackTrace();
  854. handleError(e1);
  855. }
  856. }
  857. }
  858. return liaison;
  859. }
  860. /**
  861. * Create an instance of an XSL parameter for configuration by Ant.
  862. *
  863. * @return an instance of the Param class to be configured.
  864. */
  865. public Param createParam() {
  866. final Param p = new Param();
  867. params.add(p);
  868. return p;
  869. }
  870. /**
  871. * The Param inner class used to store XSL parameters
  872. */
  873. public static class Param {
  874. /** The parameter name */
  875. private String name = null;
  876. /** The parameter's value */
  877. private String expression = null;
  878. /**
  879. * Type of the expression.
  880. * @see ParamType
  881. */
  882. private String type;
  883. private Object ifCond;
  884. private Object unlessCond;
  885. private Project project;
  886. /**
  887. * Set the current project
  888. *
  889. * @param project the current project
  890. */
  891. public void setProject(final Project project) {
  892. this.project = project;
  893. }
  894. /**
  895. * Set the parameter name.
  896. *
  897. * @param name the name of the parameter.
  898. */
  899. public void setName(final String name) {
  900. this.name = name;
  901. }
  902. /**
  903. * The parameter value -
  904. * can be a primitive type value or an XPath expression.
  905. * @param expression the parameter's value/expression.
  906. * @see #setType(java.lang.String)
  907. */
  908. public void setExpression(final String expression) {
  909. this.expression = expression;
  910. }
  911. /**
  912. * @see ParamType
  913. * @since Ant 1.9.3
  914. */
  915. public void setType(final String type) {
  916. this.type = type;
  917. }
  918. /**
  919. * Get the parameter name
  920. *
  921. * @return the parameter name
  922. * @exception BuildException if the name is not set.
  923. */
  924. public String getName() throws BuildException {
  925. if (name == null) {
  926. throw new BuildException("Name attribute is missing.");
  927. }
  928. return name;
  929. }
  930. /**
  931. * Get the parameter's value
  932. *
  933. * @return the parameter value
  934. * @exception BuildException if the value is not set.
  935. * @see #getType()
  936. */
  937. public String getExpression() throws BuildException {
  938. if (expression == null) {
  939. throw new BuildException("Expression attribute is missing.");
  940. }
  941. return expression;
  942. }
  943. /**
  944. * @see ParamType
  945. * @since Ant 1.9.3
  946. */
  947. public String getType() {
  948. return type;
  949. }
  950. /**
  951. * Set whether this param should be used. It will be used if
  952. * the expression evaluates to true or the name of a property
  953. * which has been set, otherwise it won't.
  954. * @param ifCond evaluated expression
  955. * @since Ant 1.8.0
  956. */
  957. public void setIf(final Object ifCond) {
  958. this.ifCond = ifCond;
  959. }
  960. /**
  961. * Set whether this param should be used. It will be used if
  962. * the expression evaluates to true or the name of a property
  963. * which has been set, otherwise it won't.
  964. * @param ifProperty evaluated expression
  965. */
  966. public void setIf(final String ifProperty) {
  967. setIf((Object) ifProperty);
  968. }
  969. /**
  970. * Set whether this param should NOT be used. It will not be
  971. * used if the expression evaluates to true or the name of a
  972. * property which has been set, otherwise it will be used.
  973. * @param unlessCond evaluated expression
  974. * @since Ant 1.8.0
  975. */
  976. public void setUnless(final Object unlessCond) {
  977. this.unlessCond = unlessCond;
  978. }
  979. /**
  980. * Set whether this param should NOT be used. It will not be
  981. * used if the expression evaluates to true or the name of a
  982. * property which has been set, otherwise it will be used.
  983. * @param unlessProperty evaluated expression
  984. */
  985. public void setUnless(final String unlessProperty) {
  986. setUnless((Object) unlessProperty);
  987. }
  988. /**
  989. * Ensures that the param passes the conditions placed
  990. * on it with <code>if</code> and <code>unless</code> properties.
  991. * @return true if the task passes the "if" and "unless" parameters
  992. */
  993. public boolean shouldUse() {
  994. final PropertyHelper ph = PropertyHelper.getPropertyHelper(project);
  995. return ph.testIfCondition(ifCond)
  996. && ph.testUnlessCondition(unlessCond);
  997. }
  998. } // Param
  999. /**
  1000. * Enum for types of the parameter expression.
  1001. *
  1002. * <p>The expression can be:</p>
  1003. * <ul>
  1004. * <li>primitive type that will be parsed from the string value e.g.
  1005. * {@linkplain Integer#parseInt(java.lang.String)}</li>
  1006. * <li>XPath expression that will be evaluated (outside of the transformed
  1007. * document - on empty one) and casted to given type. Inside XPath
  1008. * expressions the Ant variables (properties) can be used (as XPath
  1009. * variables - e.g. $variable123). n.b. placeholders in form of
  1010. * ${variable123} will be substituted with their values before evaluating the
  1011. * XPath expression (so it can be used for dynamic XPath function names and
  1012. * other hacks).</li>
  1013. * </ul>
  1014. * <p>The parameter will be then passed to the XSLT template.</p>
  1015. *
  1016. * <p>Default type (if omited) is primitive String. So if the expression is e.g
  1017. * "true" with no type, in XSLT it will be only a text string, not true
  1018. * boolean.</p>
  1019. *
  1020. * @see Param#setType(java.lang.String)
  1021. * @see Param#setExpression(java.lang.String)
  1022. * @since Ant 1.9.3
  1023. */
  1024. public enum ParamType {
  1025. STRING,
  1026. BOOLEAN,
  1027. INT,
  1028. LONG,
  1029. DOUBLE,
  1030. XPATH_STRING,
  1031. XPATH_BOOLEAN,
  1032. XPATH_NUMBER,
  1033. XPATH_NODE,
  1034. XPATH_NODESET;
  1035. public static final Map<ParamType, QName> XPATH_TYPES;
  1036. static {
  1037. final Map<ParamType, QName> m = new EnumMap<ParamType, QName>(ParamType.class);
  1038. m.put(XPATH_STRING, XPathConstants.STRING);
  1039. m.put(XPATH_BOOLEAN, XPathConstants.BOOLEAN);
  1040. m.put(XPATH_NUMBER, XPathConstants.NUMBER);
  1041. m.put(XPATH_NODE, XPathConstants.NODE);
  1042. m.put(XPATH_NODESET, XPathConstants.NODESET);
  1043. XPATH_TYPES = Collections.unmodifiableMap(m);
  1044. }
  1045. }
  1046. /**
  1047. * Create an instance of an output property to be configured.
  1048. * @return the newly created output property.
  1049. * @since Ant 1.5
  1050. */
  1051. public OutputProperty createOutputProperty() {
  1052. final OutputProperty p = new OutputProperty();
  1053. outputProperties.addElement(p);
  1054. return p;
  1055. }
  1056. /**
  1057. * Specify how the result tree should be output as specified
  1058. * in the <a href="http://www.w3.org/TR/xslt#output">
  1059. * specification</a>.
  1060. * @since Ant 1.5
  1061. */
  1062. public static class OutputProperty {
  1063. /** output property name */
  1064. private String name;
  1065. /** output property value */
  1066. private String value;
  1067. /**
  1068. * @return the output property name.
  1069. */
  1070. public String getName() {
  1071. return name;
  1072. }
  1073. /**
  1074. * set the name for this property
  1075. * @param name A non-null String that specifies an
  1076. * output property name, which may be namespace qualified.
  1077. */
  1078. public void setName(final String name) {
  1079. this.name = name;
  1080. }
  1081. /**
  1082. * @return the output property value.
  1083. */
  1084. public String getValue() {
  1085. return value;
  1086. }
  1087. /**
  1088. * set the value for this property
  1089. * @param value The non-null string value of the output property.
  1090. */
  1091. public void setValue(final String value) {
  1092. this.value = value;
  1093. }
  1094. }
  1095. /**
  1096. * Initialize internal instance of XMLCatalog.
  1097. * Initialize XPath for parameter evaluation.
  1098. * @throws BuildException on error
  1099. */
  1100. @Override
  1101. public void init() throws BuildException {
  1102. super.init();
  1103. xmlCatalog.setProject(getProject());
  1104. xpathFactory = XPathFactory.newInstance();
  1105. xpath = xpathFactory.newXPath();
  1106. xpath.setXPathVariableResolver(new XPathVariableResolver() {
  1107. public Object resolveVariable(final QName variableName) {
  1108. return getProject().getProperty(variableName.toString());
  1109. }
  1110. });
  1111. }
  1112. /**
  1113. * Loads the stylesheet and set xsl:param parameters.
  1114. *
  1115. * @param stylesheet the file from which to load the stylesheet.
  1116. * @exception BuildException if the stylesheet cannot be loaded.
  1117. * @deprecated since Ant 1.7
  1118. */
  1119. @Deprecated
  1120. protected void configureLiaison(final File stylesheet) throws BuildException {
  1121. final FileResource fr = new FileResource();
  1122. fr.setProject(getProject());
  1123. fr.setFile(stylesheet);
  1124. configureLiaison(fr);
  1125. }
  1126. /**
  1127. * Loads the stylesheet and set xsl:param parameters.
  1128. *
  1129. * @param stylesheet the resource from which to load the stylesheet.
  1130. * @exception BuildException if the stylesheet cannot be loaded.
  1131. * @since Ant 1.7
  1132. */
  1133. protected void configureLiaison(final Resource stylesheet) throws BuildException {
  1134. if (stylesheetLoaded && reuseLoadedStylesheet) {
  1135. return;
  1136. }
  1137. stylesheetLoaded = true;
  1138. try {
  1139. log("Loading stylesheet " + stylesheet, Project.MSG_INFO);
  1140. // We call liaison.configure() and then liaison.setStylesheet()
  1141. // so that the internal variables of liaison can be set up
  1142. if (liaison instanceof XSLTLiaison2) {
  1143. ((XSLTLiaison2) liaison).configure(this);
  1144. }
  1145. if (liaison instanceof XSLTLiaison3) {
  1146. // If we are here we can set the stylesheet as a
  1147. // resource
  1148. ((XSLTLiaison3) liaison).setStylesheet(stylesheet);
  1149. } else {
  1150. // If we are here we cannot set the stylesheet as
  1151. // a resource, but we can set it as a file. So,
  1152. // we make an attempt to get it as a file
  1153. final FileProvider fp =
  1154. stylesheet.as(FileProvider.class);
  1155. if (fp != null) {
  1156. liaison.setStylesheet(fp.getFile());
  1157. } else {
  1158. handleError(liaison.getClass().toString()
  1159. + " accepts the stylesheet only as a file");
  1160. return;
  1161. }
  1162. }
  1163. for (final Param p : params) {
  1164. if (p.shouldUse()) {
  1165. final Object evaluatedParam = evaluateParam(p);
  1166. if (liaison instanceof XSLTLiaison4) {
  1167. ((XSLTLiaison4)liaison).addParam(p.getName(), evaluatedParam);
  1168. } else {
  1169. if (evaluatedParam == null || evaluatedParam instanceof String) {
  1170. liaison.addParam(p.getName(), (String)evaluatedParam);
  1171. } else {
  1172. log("XSLTLiaison '" + liaison.getClass().getName()
  1173. + "' supports only String parameters. Converting parameter '" + p.getName()
  1174. + "' to its String value '" + evaluatedParam, Project.MSG_WARN);
  1175. liaison.addParam(p.getName(), String.valueOf(evaluatedParam));
  1176. }
  1177. }
  1178. }
  1179. }
  1180. } catch (final Exception ex) {
  1181. log("Failed to transform using stylesheet " + stylesheet, Project.MSG_INFO);
  1182. handleTransformationError(ex);
  1183. }
  1184. }
  1185. /**
  1186. * Evaluates parameter expression according to its type.
  1187. *
  1188. * @param param parameter from Ant build file
  1189. * @return value to be passed to XSLT as parameter
  1190. * @throws IllegalArgumentException if param type is unsupported
  1191. * @throws NumberFormatException if expression of numeric type is not
  1192. * desired numeric type
  1193. * @throws XPathExpressionException if XPath expression can not be compiled
  1194. * @since Ant 1.9.3
  1195. */
  1196. private Object evaluateParam(final Param param) throws XPathExpressionException {
  1197. final String typeName = param.getType();
  1198. final String expression = param.getExpression();
  1199. ParamType type;
  1200. if (typeName == null || "".equals(typeName)) {
  1201. type = ParamType.STRING; // String is default
  1202. } else {
  1203. try {
  1204. type = ParamType.valueOf(typeName);
  1205. } catch (final IllegalArgumentException e) {
  1206. throw new IllegalArgumentException("Invalid XSLT parameter type: " + typeName, e);
  1207. }
  1208. }
  1209. switch (type) {
  1210. case STRING:
  1211. return expression;
  1212. case BOOLEAN:
  1213. return Boolean.parseBoolean(expression);
  1214. case DOUBLE:
  1215. return Double.parseDouble(expression);
  1216. case INT:
  1217. return Integer.parseInt(expression);
  1218. case LONG:
  1219. return Long.parseLong(expression);
  1220. default: // XPath expression
  1221. final QName xpathType = ParamType.XPATH_TYPES.get(type);
  1222. if (xpathType == null) {
  1223. throw new IllegalArgumentException("Invalid XSLT parameter type: " + typeName);
  1224. } else {
  1225. final XPathExpression xpe = xpath.compile(expression);
  1226. // null = evaluate XPath on empty XML document
  1227. return xpe.evaluate((Object) null, xpathType);
  1228. }
  1229. }
  1230. }
  1231. /**
  1232. * Sets file parameter(s) for directory and filename if the attribute
  1233. * 'filenameparameter' or 'filedirparameter' are set in the task.
  1234. *
  1235. * @param liaison to change parameters for
  1236. * @param inFile to get the additional file information from
  1237. * @throws Exception if an exception occurs on filename lookup
  1238. *
  1239. * @since Ant 1.7
  1240. */
  1241. private void setLiaisonDynamicFileParameters(
  1242. final XSLTLiaison liaison, final File inFile) throws Exception {
  1243. if (fileNameParameter != null) {
  1244. liaison.addParam(fileNameParameter, inFile.getName());
  1245. }
  1246. if (fileDirParameter != null) {
  1247. final String fileName = FileUtils.getRelativePath(baseDir, inFile);
  1248. final File file = new File(fileName);
  1249. // Give always a slash as file separator, so the stylesheet could be sure about that
  1250. // Use '.' so a dir+"/"+name would not result in an absolute path
  1251. liaison.addParam(fileDirParameter, file.getParent() != null ? file.getParent().replace(
  1252. '\\', '/') : ".");
  1253. }
  1254. }
  1255. /**
  1256. * Create the factory element to configure a trax liaison.
  1257. * @return the newly created factory element.
  1258. * @throws BuildException if the element is created more than one time.
  1259. */
  1260. public Factory createFactory() throws BuildException {
  1261. if (factory != null) {
  1262. handleError("'factory' element must be unique");
  1263. } else {
  1264. factory = new Factory();
  1265. }
  1266. return factory;
  1267. }
  1268. /**
  1269. * Throws an exception with the given message if failOnError is
  1270. * true, otherwise logs the message using the WARN level.
  1271. *
  1272. * @since Ant 1.8.0
  1273. */
  1274. protected void handleError(final String msg) {
  1275. if (failOnError) {
  1276. throw new BuildException(msg, getLocation());
  1277. }
  1278. log(msg, Project.MSG_WARN);
  1279. }
  1280. /**
  1281. * Throws an exception with the given nested exception if
  1282. * failOnError is true, otherwise logs the message using the WARN
  1283. * level.
  1284. *
  1285. * @since Ant 1.8.0
  1286. */
  1287. protected void handleError(final Throwable ex) {
  1288. if (failOnError) {
  1289. throw new BuildException(ex);
  1290. } else {
  1291. log("Caught an exception: " + ex, Project.MSG_WARN);
  1292. }
  1293. }
  1294. /**
  1295. * Throws an exception with the given nested exception if
  1296. * failOnError and failOnTransformationError are true, otherwise
  1297. * logs the message using the WARN level.
  1298. *
  1299. * @since Ant 1.8.0
  1300. */
  1301. protected void handleTransformationError(final Exception ex) {
  1302. if (failOnError && failOnTransformationError) {
  1303. throw new BuildException(ex);
  1304. } else {
  1305. log("Caught an error during transformation: " + ex,
  1306. Project.MSG_WARN);
  1307. }
  1308. }
  1309. /**
  1310. * The factory element to configure a transformer factory
  1311. * @since Ant 1.6
  1312. */
  1313. public static class Factory {
  1314. /** the factory class name to use for TraXLiaison */
  1315. private String name;
  1316. /**
  1317. * the list of factory attributes to use for TraXLiaison
  1318. */
  1319. private final Vector attributes = new Vector();
  1320. /**
  1321. * @return the name of the factory.
  1322. */
  1323. public String getName() {
  1324. return name;
  1325. }
  1326. /**
  1327. * Set the name of the factory
  1328. * @param name the name of the factory.
  1329. */
  1330. public void setName(final String name) {
  1331. this.name = name;
  1332. }
  1333. /**
  1334. * Create an instance of a factory attribute.
  1335. * @param attr the newly created factory attribute
  1336. */
  1337. public void addAttribute(final Attribute attr) {
  1338. attributes.addElement(attr);
  1339. }
  1340. /**
  1341. * return the attribute elements.
  1342. * @return the enumeration of attributes
  1343. */
  1344. public Enumeration getAttributes() {
  1345. return attributes.elements();
  1346. }
  1347. /**
  1348. * A JAXP factory attribute. This is mostly processor specific, for
  1349. * example for Xalan 2.3+, the following attributes could be set:
  1350. * <ul>
  1351. * <li>http://xml.apache.org/xalan/features/optimize (true|false) </li>
  1352. * <li>http://xml.apache.org/xalan/features/incremental (true|false) </li>
  1353. * </ul>
  1354. */
  1355. public static class Attribute implements DynamicConfigurator {
  1356. /** attribute name, mostly processor specific */
  1357. private String name;
  1358. /** attribute value, often a boolean string */
  1359. private Object value;
  1360. /**
  1361. * @return the attribute name.
  1362. */
  1363. public String getName() {
  1364. return name;
  1365. }
  1366. /**
  1367. * @return the output property value.
  1368. */
  1369. public Object getValue() {
  1370. return value;
  1371. }
  1372. /**
  1373. * Not used.
  1374. * @param name not used
  1375. * @return null
  1376. * @throws BuildException never
  1377. */
  1378. public Object createDynamicElement(final String name) throws BuildException {
  1379. return null;
  1380. }
  1381. /**
  1382. * Set an attribute.
  1383. * Only "name" and "value" are supported as names.
  1384. * @param name the name of the attribute
  1385. * @param value the value of the attribute
  1386. * @throws BuildException on error
  1387. */
  1388. public void setDynamicAttribute(final String name, final String value) throws BuildException {
  1389. // only 'name' and 'value' exist.
  1390. if ("name".equalsIgnoreCase(name)) {
  1391. this.name = value;
  1392. } else if ("value".equalsIgnoreCase(name)) {
  1393. // a value must be of a given type
  1394. // say boolean|integer|string that are mostly used.
  1395. if ("true".equalsIgnoreCase(value)) {
  1396. this.value = Boolean.TRUE;
  1397. } else if ("false".equalsIgnoreCase(value)) {
  1398. this.value = Boolean.FALSE;
  1399. } else {
  1400. try {
  1401. this.value = new Integer(value);
  1402. } catch (final NumberFormatException e) {
  1403. this.value = value;
  1404. }
  1405. }
  1406. } else {
  1407. throw new BuildException("Unsupported attribute: " + name);
  1408. }
  1409. }
  1410. } // -- class Attribute
  1411. } // -- class Factory
  1412. /**
  1413. * Mapper implementation of the "traditional" way &lt;xslt&gt;
  1414. * mapped filenames.
  1415. *
  1416. * <p>If the file has an extension, chop it off. Append whatever
  1417. * the user has specified as extension or ".html".</p>
  1418. *
  1419. * @since Ant 1.6.2
  1420. */
  1421. private class StyleMapper implements FileNameMapper {
  1422. public void setFrom(final String from) {
  1423. }
  1424. public void setTo(final String to) {
  1425. }
  1426. public String[] mapFileName(String xmlFile) {
  1427. final int dotPos = xmlFile.lastIndexOf('.');
  1428. if (dotPos > 0) {
  1429. xmlFile = xmlFile.substring(0, dotPos);
  1430. }
  1431. return new String[] {xmlFile + targetExtension};
  1432. }
  1433. }
  1434. /**
  1435. * Configuration for Xalan2 traces.
  1436. *
  1437. * @since Ant 1.8.0
  1438. */
  1439. public final class TraceConfiguration {
  1440. private boolean elements, extension, generation, selection, templates;
  1441. /**
  1442. * Set to true if the listener is to print events that occur
  1443. * as each node is 'executed' in the stylesheet.
  1444. */
  1445. public void setElements(final boolean b) {
  1446. elements = b;
  1447. }
  1448. /**
  1449. * True if the listener is to print events that occur as each
  1450. * node is 'executed' in the stylesheet.
  1451. */
  1452. public boolean getElements() {
  1453. return elements;
  1454. }
  1455. /**
  1456. * Set to true if the listener is to print information after
  1457. * each extension event.
  1458. */
  1459. public void setExtension(final boolean b) {
  1460. extension = b;
  1461. }
  1462. /**
  1463. * True if the listener is to print information after each
  1464. * extension event.
  1465. */
  1466. public boolean getExtension() {
  1467. return extension;
  1468. }
  1469. /**
  1470. * Set to true if the listener is to print information after
  1471. * each result-tree generation event.
  1472. */
  1473. public void setGeneration(final boolean b) {
  1474. generation = b;
  1475. }
  1476. /**
  1477. * True if the listener is to print information after each
  1478. * result-tree generation event.
  1479. */
  1480. public boolean getGeneration() {
  1481. return generation;
  1482. }
  1483. /**
  1484. * Set to true if the listener is to print information after
  1485. * each selection event.
  1486. */
  1487. public void setSelection(final boolean b) {
  1488. selection = b;
  1489. }
  1490. /**
  1491. * True if the listener is to print information after each
  1492. * selection event.
  1493. */
  1494. public boolean getSelection() {
  1495. return selection;
  1496. }
  1497. /**
  1498. * Set to true if the listener is to print an event whenever a
  1499. * template is invoked.
  1500. */
  1501. public void setTemplates(final boolean b) {
  1502. templates = b;
  1503. }
  1504. /**
  1505. * True if the listener is to print an event whenever a
  1506. * template is invoked.
  1507. */
  1508. public boolean getTemplates() {
  1509. return templates;
  1510. }
  1511. /**
  1512. * The stream to write traces to.
  1513. */
  1514. public java.io.OutputStream getOutputStream() {
  1515. return new LogOutputStream(XSLTProcess.this);
  1516. }
  1517. }
  1518. }