1. /*
  2. * Copyright 2002-2004 The Apache Software Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. */
  17. package org.apache.tools.ant.types;
  18. import java.lang.reflect.Method;
  19. import java.io.File;
  20. import java.io.FileInputStream;
  21. import java.io.IOException;
  22. import java.io.InputStream;
  23. import java.net.MalformedURLException;
  24. import java.net.URL;
  25. import java.util.Enumeration;
  26. import java.util.Stack;
  27. import java.util.Vector;
  28. import javax.xml.parsers.ParserConfigurationException;
  29. import javax.xml.parsers.SAXParserFactory;
  30. import javax.xml.transform.Source;
  31. import javax.xml.transform.TransformerException;
  32. import javax.xml.transform.URIResolver;
  33. import javax.xml.transform.sax.SAXSource;
  34. import org.apache.tools.ant.AntClassLoader;
  35. import org.apache.tools.ant.BuildException;
  36. import org.apache.tools.ant.Project;
  37. import org.apache.tools.ant.util.FileUtils;
  38. import org.apache.tools.ant.util.JAXPUtils;
  39. import org.xml.sax.EntityResolver;
  40. import org.xml.sax.InputSource;
  41. import org.xml.sax.SAXException;
  42. import org.xml.sax.XMLReader;
  43. /**
  44. * <p>This data type provides a catalog of resource locations (such as
  45. * DTDs and XML entities), based on the <a
  46. * href="http://oasis-open.org/committees/entity/spec-2001-08-06.html">
  47. * OASIS "Open Catalog" standard</a>. The catalog entries are used
  48. * both for Entity resolution and URI resolution, in accordance with
  49. * the {@link org.xml.sax.EntityResolver EntityResolver} and {@link
  50. * javax.xml.transform.URIResolver URIResolver} interfaces as defined
  51. * in the <a href="http://java.sun.com/xml/jaxp">Java API for XML
  52. * Processing Specification</a>.</p>
  53. *
  54. * <p>Resource locations can be specified either in-line or in
  55. * external catalog file(s), or both. In order to use an external
  56. * catalog file, the xml-commons resolver library ("resolver.jar")
  57. * must be in your classpath. External catalog files may be either <a
  58. * href="http://oasis-open.org/committees/entity/background/9401.html">
  59. * plain text format</a> or <a
  60. * href="http://www.oasis-open.org/committees/entity/spec-2001-08-06.html">
  61. * XML format</a>. If the xml-commons resolver library is not found
  62. * in the classpath, external catalog files, specified in
  63. * <code><catalogpath></code> paths, will be ignored and a warning will
  64. * be logged. In this case, however, processing of inline entries will proceed
  65. * normally.</p>
  66. *
  67. * <p>Currently, only <code><dtd></code> and
  68. * <code><entity></code> elements may be specified inline; these
  69. * correspond to OASIS catalog entry types <code>PUBLIC</code> and
  70. * <code>URI</code> respectively.</p>
  71. *
  72. * <p>The following is a usage example:</p>
  73. *
  74. * <code>
  75. * <xmlcatalog><br>
  76. *   <dtd publicId="" location="/path/to/file.jar" /><br>
  77. *   <dtd publicId="" location="/path/to/file2.jar" /><br>
  78. *   <entity publicId="" location="/path/to/file3.jar" /><br>
  79. *   <entity publicId="" location="/path/to/file4.jar" /><br>
  80. *   <catalogpath><br>
  81. *     <pathelement location="/etc/sgml/catalog"/><br>
  82. *   </catalogpath><br>
  83. *   <catalogfiles dir="/opt/catalogs/" includes="**\catalog.xml" /><br>
  84. * </xmlcatalog><br>
  85. * </code>
  86. * <p>
  87. * Tasks wishing to use <code><xmlcatalog></code> must provide a method called
  88. * <code>createXMLCatalog</code> which returns an instance of
  89. * <code>XMLCatalog</code>. Nested DTD and entity definitions are handled by
  90. * the XMLCatalog object and must be labeled <code>dtd</code> and
  91. * <code>entity</code> respectively.</p>
  92. *
  93. * <p>The following is a description of the resolution algorithm:
  94. * entities/URIs/dtds are looked up in each of the following contexts,
  95. * stopping when a valid and readable resource is found:
  96. * <ol>
  97. * <li>In the local filesystem</li>
  98. * <li>In the classpath</li>
  99. * <li>Using the Apache xml-commons resolver (if it is available)</li>
  100. * <li>In URL-space</li>
  101. * </ol>
  102. * </p>
  103. *
  104. * <p>See {@link
  105. * org.apache.tools.ant.taskdefs.optional.XMLValidateTask
  106. * XMLValidateTask} for an example of a task that has integrated
  107. * support for XMLCatalogs.</p>
  108. *
  109. * <p>Possible future extension could provide for additional OASIS
  110. * entry types to be specified inline.</p>
  111. *
  112. */
  113. public class XMLCatalog extends DataType
  114. implements Cloneable, EntityResolver, URIResolver {
  115. /** helper for some File.toURL connversions */
  116. private static FileUtils fileUtils = FileUtils.newFileUtils();
  117. //-- Fields ----------------------------------------------------------------
  118. /** Holds dtd/entity objects until needed. */
  119. private Vector elements = new Vector();
  120. /**
  121. * Classpath in which to attempt to resolve resources.
  122. */
  123. private Path classpath;
  124. /**
  125. * Path listing external catalog files to search when resolving entities
  126. */
  127. private Path catalogPath;
  128. /**
  129. * The name of the bridge to the Apache xml-commons resolver
  130. * class, used to determine whether resolver.jar is present in the
  131. * classpath.
  132. */
  133. public static final String APACHE_RESOLVER
  134. = "org.apache.tools.ant.types.resolver.ApacheCatalogResolver";
  135. /**
  136. * Resolver base class
  137. */
  138. public static final String CATALOG_RESOLVER
  139. = "org.apache.xml.resolver.tools.CatalogResolver";
  140. //-- Methods ---------------------------------------------------------------
  141. /**
  142. * Default constructor
  143. */
  144. public XMLCatalog() {
  145. setChecked(false);
  146. }
  147. /**
  148. * Returns the elements of the catalog - ResourceLocation objects.
  149. *
  150. * @return the elements of the catalog - ResourceLocation objects
  151. */
  152. private Vector getElements() {
  153. return getRef().elements;
  154. }
  155. /**
  156. * Returns the classpath in which to attempt to resolve resources.
  157. *
  158. * @return the classpath
  159. */
  160. private Path getClasspath() {
  161. return getRef().classpath;
  162. }
  163. /**
  164. * Set the list of ResourceLocation objects in the catalog.
  165. * Not allowed if this catalog is itself a reference to another catalog --
  166. * that is, a catalog cannot both refer to another <em>and</em> contain
  167. * elements or other attributes.
  168. *
  169. * @param aVector the new list of ResourceLocations
  170. * to use in the catalog.
  171. */
  172. private void setElements(Vector aVector) {
  173. if (isReference()) {
  174. throw noChildrenAllowed();
  175. }
  176. elements = aVector;
  177. }
  178. /**
  179. * Allows nested classpath elements. Not allowed if this catalog
  180. * is itself a reference to another catalog -- that is, a catalog
  181. * cannot both refer to another <em>and</em> contain elements or
  182. * other attributes.
  183. *
  184. * @return a Path instance to be configured.
  185. */
  186. public Path createClasspath() {
  187. if (isReference()) {
  188. throw noChildrenAllowed();
  189. }
  190. if (this.classpath == null) {
  191. this.classpath = new Path(getProject());
  192. }
  193. setChecked(false);
  194. return this.classpath.createPath();
  195. }
  196. /**
  197. * Allows simple classpath string. Not allowed if this catalog is
  198. * itself a reference to another catalog -- that is, a catalog
  199. * cannot both refer to another <em>and</em> contain elements or
  200. * other attributes.
  201. *
  202. * @param classpath the classpath to use to look up entities.
  203. */
  204. public void setClasspath(Path classpath) {
  205. if (isReference()) {
  206. throw tooManyAttributes();
  207. }
  208. if (this.classpath == null) {
  209. this.classpath = classpath;
  210. } else {
  211. this.classpath.append(classpath);
  212. }
  213. setChecked(false);
  214. }
  215. /**
  216. * Allows classpath reference. Not allowed if this catalog is
  217. * itself a reference to another catalog -- that is, a catalog
  218. * cannot both refer to another <em>and</em> contain elements or
  219. * other attributes.
  220. *
  221. * @param r an Ant reference containing a classpath.
  222. */
  223. public void setClasspathRef(Reference r) {
  224. if (isReference()) {
  225. throw tooManyAttributes();
  226. }
  227. createClasspath().setRefid(r);
  228. setChecked(false);
  229. }
  230. /** Creates a nested <code><catalogpath></code> element.
  231. * Not allowed if this catalog is itself a reference to another
  232. * catalog -- that is, a catalog cannot both refer to another
  233. * <em>and</em> contain elements or other attributes.
  234. *
  235. * @return a path to be configured as the catalog path.
  236. * @exception BuildException
  237. * if this is a reference and no nested elements are allowed.
  238. */
  239. public Path createCatalogPath() {
  240. if (isReference()) {
  241. throw noChildrenAllowed();
  242. }
  243. if (this.catalogPath == null) {
  244. this.catalogPath = new Path(getProject());
  245. }
  246. setChecked(false);
  247. return this.catalogPath.createPath();
  248. }
  249. /**
  250. * Allows catalogpath reference. Not allowed if this catalog is
  251. * itself a reference to another catalog -- that is, a catalog
  252. * cannot both refer to another <em>and</em> contain elements or
  253. * other attributes.
  254. *
  255. * @param r an Ant reference containing a classpath to be used as
  256. * the catalog path.
  257. */
  258. public void setCatalogPathRef(Reference r) {
  259. if (isReference()) {
  260. throw tooManyAttributes();
  261. }
  262. createCatalogPath().setRefid(r);
  263. setChecked(false);
  264. }
  265. /**
  266. * Returns the catalog path in which to attempt to resolve DTDs.
  267. *
  268. * @return the catalog path
  269. */
  270. public Path getCatalogPath() {
  271. return getRef().catalogPath;
  272. }
  273. /**
  274. * Creates the nested <code><dtd></code> element. Not
  275. * allowed if this catalog is itself a reference to another
  276. * catalog -- that is, a catalog cannot both refer to another
  277. * <em>and</em> contain elements or other attributes.
  278. *
  279. * @param dtd the information about the PUBLIC resource mapping to
  280. * be added to the catalog
  281. * @exception BuildException if this is a reference and no nested
  282. * elements are allowed.
  283. */
  284. public void addDTD(ResourceLocation dtd) throws BuildException {
  285. if (isReference()) {
  286. throw noChildrenAllowed();
  287. }
  288. getElements().addElement(dtd);
  289. setChecked(false);
  290. }
  291. /**
  292. * Creates the nested <code><entity></code> element. Not
  293. * allowed if this catalog is itself a reference to another
  294. * catalog -- that is, a catalog cannot both refer to another
  295. * <em>and</em> contain elements or other attributes.
  296. *
  297. * @param entity the information about the URI resource mapping to be
  298. * added to the catalog.
  299. * @exception BuildException if this is a reference and no nested
  300. * elements are allowed.
  301. */
  302. public void addEntity(ResourceLocation entity) throws BuildException {
  303. addDTD(entity);
  304. }
  305. /**
  306. * Loads a nested <code><xmlcatalog></code> into our
  307. * definition. Not allowed if this catalog is itself a reference
  308. * to another catalog -- that is, a catalog cannot both refer to
  309. * another <em>and</em> contain elements or other attributes.
  310. *
  311. * @param catalog Nested XMLCatalog
  312. */
  313. public void addConfiguredXMLCatalog(XMLCatalog catalog) {
  314. if (isReference()) {
  315. throw noChildrenAllowed();
  316. }
  317. // Add all nested elements to our catalog
  318. Vector newElements = catalog.getElements();
  319. Vector ourElements = getElements();
  320. Enumeration e = newElements.elements();
  321. while (e.hasMoreElements()) {
  322. ourElements.addElement(e.nextElement());
  323. }
  324. // Append the classpath of the nested catalog
  325. Path nestedClasspath = catalog.getClasspath();
  326. createClasspath().append(nestedClasspath);
  327. // Append the catalog path of the nested catalog
  328. Path nestedCatalogPath = catalog.getCatalogPath();
  329. createCatalogPath().append(nestedCatalogPath);
  330. setChecked(false);
  331. }
  332. /**
  333. * Makes this instance in effect a reference to another XMLCatalog
  334. * instance.
  335. *
  336. * <p>You must not set another attribute or nest elements inside
  337. * this element if you make it a reference. That is, a catalog
  338. * cannot both refer to another <em>and</em> contain elements or
  339. * attributes.</p>
  340. *
  341. * @param r the reference to which this catalog instance is associated
  342. * @exception BuildException if this instance already has been configured.
  343. */
  344. public void setRefid(Reference r) throws BuildException {
  345. if (!elements.isEmpty()) {
  346. throw tooManyAttributes();
  347. }
  348. super.setRefid(r);
  349. }
  350. /**
  351. * Implements the EntityResolver.resolveEntity() interface method.
  352. *
  353. * @see org.xml.sax.EntityResolver#resolveEntity
  354. */
  355. public InputSource resolveEntity(String publicId, String systemId)
  356. throws SAXException, IOException {
  357. if (isReference()) {
  358. return getRef().resolveEntity(publicId, systemId);
  359. }
  360. if (!isChecked()) {
  361. // make sure we don't have a circular reference here
  362. Stack stk = new Stack();
  363. stk.push(this);
  364. dieOnCircularReference(stk, getProject());
  365. }
  366. log("resolveEntity: '" + publicId + "': '" + systemId + "'",
  367. Project.MSG_DEBUG);
  368. InputSource inputSource =
  369. getCatalogResolver().resolveEntity(publicId, systemId);
  370. if (inputSource == null) {
  371. log("No matching catalog entry found, parser will use: '"
  372. + systemId + "'", Project.MSG_DEBUG);
  373. }
  374. return inputSource;
  375. }
  376. /**
  377. * Implements the URIResolver.resolve() interface method.
  378. *
  379. * @see javax.xml.transform.URIResolver#resolve
  380. */
  381. public Source resolve(String href, String base)
  382. throws TransformerException {
  383. if (isReference()) {
  384. return getRef().resolve(href, base);
  385. }
  386. if (!isChecked()) {
  387. // make sure we don't have a circular reference here
  388. Stack stk = new Stack();
  389. stk.push(this);
  390. dieOnCircularReference(stk, getProject());
  391. }
  392. SAXSource source = null;
  393. String uri = removeFragment(href);
  394. log("resolve: '" + uri + "' with base: '" + base + "'", Project.MSG_DEBUG);
  395. source = (SAXSource) getCatalogResolver().resolve(uri, base);
  396. if (source == null) {
  397. log("No matching catalog entry found, parser will use: '"
  398. + href + "'", Project.MSG_DEBUG);
  399. //
  400. // Cannot return a null source, because we have to call
  401. // setEntityResolver (see setEntityResolver javadoc comment)
  402. //
  403. source = new SAXSource();
  404. URL baseURL = null;
  405. try {
  406. if (base == null) {
  407. baseURL = fileUtils.getFileURL(getProject().getBaseDir());
  408. } else {
  409. baseURL = new URL(base);
  410. }
  411. URL url = (uri.length() == 0 ? baseURL : new URL(baseURL, uri));
  412. source.setInputSource(new InputSource(url.toString()));
  413. } catch (MalformedURLException ex) {
  414. // At this point we are probably in failure mode, but
  415. // try to use the bare URI as a last gasp
  416. source.setInputSource(new InputSource(uri));
  417. }
  418. }
  419. setEntityResolver(source);
  420. return source;
  421. }
  422. /**
  423. * @since Ant 1.6
  424. */
  425. private XMLCatalog getRef() {
  426. if (!isReference()) {
  427. return this;
  428. }
  429. return (XMLCatalog) getCheckedRef(XMLCatalog.class, "xmlcatalog");
  430. }
  431. /**
  432. * The instance of the CatalogResolver strategy to use.
  433. */
  434. private CatalogResolver catalogResolver = null;
  435. /**
  436. * Factory method for creating the appropriate CatalogResolver
  437. * strategy implementation.
  438. * <p> Until we query the classpath, we don't know whether the Apache
  439. * resolver (Norm Walsh's library from xml-commons) is available or not.
  440. * This method determines whether the library is available and creates the
  441. * appropriate implementation of CatalogResolver based on the answer.</p>
  442. * <p>This is an application of the Gang of Four Strategy Pattern
  443. * combined with Template Method.</p>
  444. */
  445. private CatalogResolver getCatalogResolver() {
  446. if (catalogResolver == null) {
  447. AntClassLoader loader = null;
  448. loader = getProject().createClassLoader(Path.systemClasspath);
  449. try {
  450. Class clazz = Class.forName(APACHE_RESOLVER, true, loader);
  451. // The Apache resolver is present - Need to check if it can
  452. // be seen by the catalog resolver class. Start by getting
  453. // the actual loader
  454. ClassLoader apacheResolverLoader = clazz.getClassLoader();
  455. // load the base class through this loader.
  456. Class baseResolverClass
  457. = Class.forName(CATALOG_RESOLVER, true, apacheResolverLoader);
  458. // and find its actual loader
  459. ClassLoader baseResolverLoader
  460. = baseResolverClass.getClassLoader();
  461. // We have the loader which is being used to load the
  462. // CatalogResolver. Can it see the ApacheResolver? The
  463. // base resolver will only be able to create the ApacheResolver
  464. // if it can see it - doesn't use the context loader.
  465. clazz = Class.forName(APACHE_RESOLVER, true, baseResolverLoader);
  466. Object obj = clazz.newInstance();
  467. //
  468. // Success! The xml-commons resolver library is
  469. // available, so use it.
  470. //
  471. catalogResolver = new ExternalResolver(clazz, obj);
  472. } catch (Throwable ex) {
  473. //
  474. // The xml-commons resolver library is not
  475. // available, so we can't use it.
  476. //
  477. catalogResolver = new InternalResolver();
  478. if (getCatalogPath() != null
  479. && getCatalogPath().list().length != 0) {
  480. log("Warning: catalogpath listing external catalogs"
  481. + " will be ignored", Project.MSG_WARN);
  482. }
  483. log("Failed to load Apache resolver: " + ex, Project.MSG_DEBUG);
  484. }
  485. }
  486. return catalogResolver;
  487. }
  488. /**
  489. * <p>This is called from the URIResolver to set an EntityResolver
  490. * on the SAX parser to be used for new XML documents that are
  491. * encountered as a result of the document() function, xsl:import,
  492. * or xsl:include. This is done because the XSLT processor calls
  493. * out to the SAXParserFactory itself to create a new SAXParser to
  494. * parse the new document. The new parser does not automatically
  495. * inherit the EntityResolver of the original (although arguably
  496. * it should). See below:</p>
  497. *
  498. * <tt>"If an application wants to set the ErrorHandler or
  499. * EntityResolver for an XMLReader used during a transformation,
  500. * it should use a URIResolver to return the SAXSource which
  501. * provides (with getXMLReader) a reference to the XMLReader"</tt>
  502. *
  503. * <p>...quoted from page 118 of the Java API for XML
  504. * Processing 1.1 specification</p>
  505. *
  506. */
  507. private void setEntityResolver(SAXSource source) throws TransformerException {
  508. XMLReader reader = source.getXMLReader();
  509. if (reader == null) {
  510. SAXParserFactory spFactory = SAXParserFactory.newInstance();
  511. spFactory.setNamespaceAware(true);
  512. try {
  513. reader = spFactory.newSAXParser().getXMLReader();
  514. } catch (ParserConfigurationException ex) {
  515. throw new TransformerException(ex);
  516. } catch (SAXException ex) {
  517. throw new TransformerException(ex);
  518. }
  519. }
  520. reader.setEntityResolver(this);
  521. source.setXMLReader(reader);
  522. }
  523. /**
  524. * Find a ResourceLocation instance for the given publicId.
  525. *
  526. * @param publicId the publicId of the Resource for which local information
  527. * is required.
  528. * @return a ResourceLocation instance with information on the local location
  529. * of the Resource or null if no such information is available.
  530. */
  531. private ResourceLocation findMatchingEntry(String publicId) {
  532. Enumeration e = getElements().elements();
  533. ResourceLocation element = null;
  534. while (e.hasMoreElements()) {
  535. Object o = e.nextElement();
  536. if (o instanceof ResourceLocation) {
  537. element = (ResourceLocation) o;
  538. if (element.getPublicId().equals(publicId)) {
  539. return element;
  540. }
  541. }
  542. }
  543. return null;
  544. }
  545. /**
  546. * Utility method to remove trailing fragment from a URI.
  547. * For example,
  548. * <code>http://java.sun.com/index.html#chapter1</code>
  549. * would return <code>http://java.sun.com/index.html</code>.
  550. *
  551. * @param uri The URI to process. It may or may not contain a
  552. * fragment.
  553. * @return The URI sans fragment.
  554. */
  555. private String removeFragment(String uri) {
  556. String result = uri;
  557. int hashPos = uri.indexOf("#");
  558. if (hashPos >= 0) {
  559. result = uri.substring(0, hashPos);
  560. }
  561. return result;
  562. }
  563. /**
  564. * Utility method to lookup a ResourceLocation in the filesystem.
  565. *
  566. * @return An InputSource for reading the file, or <code>null</code>
  567. * if the file does not exist or is not readable.
  568. */
  569. private InputSource filesystemLookup(ResourceLocation matchingEntry) {
  570. String uri = matchingEntry.getLocation();
  571. // the following line seems to be necessary on Windows under JDK 1.2
  572. uri = uri.replace(File.separatorChar, '/');
  573. URL baseURL = null;
  574. //
  575. // The ResourceLocation may specify a relative path for its
  576. // location attribute. This is resolved using the appropriate
  577. // base.
  578. //
  579. if (matchingEntry.getBase() != null) {
  580. baseURL = matchingEntry.getBase();
  581. } else {
  582. try {
  583. baseURL = fileUtils.getFileURL(getProject().getBaseDir());
  584. } catch (MalformedURLException ex) {
  585. throw new BuildException("Project basedir cannot be converted to a URL");
  586. }
  587. }
  588. InputSource source = null;
  589. URL url = null;
  590. try {
  591. url = new URL(baseURL, uri);
  592. } catch (MalformedURLException ex) {
  593. // this processing is useful under Windows when the location of the DTD has been given as an absolute path
  594. // see Bugzilla Report 23913
  595. File testFile = new File(uri);
  596. if (testFile.exists() && testFile.canRead()) {
  597. log("uri : '"
  598. + uri + "' matches a readable file", Project.MSG_DEBUG);
  599. try {
  600. url = fileUtils.getFileURL(testFile);
  601. } catch (MalformedURLException ex1) {
  602. throw new BuildException("could not find an URL for :" + testFile.getAbsolutePath());
  603. }
  604. } else {
  605. log("uri : '"
  606. + uri + "' does not match a readable file", Project.MSG_DEBUG);
  607. }
  608. }
  609. if (url != null) {
  610. String fileName = url.getFile();
  611. if (fileName != null) {
  612. log("fileName " + fileName, Project.MSG_DEBUG);
  613. File resFile = new File(fileName);
  614. if (resFile.exists() && resFile.canRead()) {
  615. try {
  616. source = new InputSource(new FileInputStream(resFile));
  617. String sysid = JAXPUtils.getSystemId(resFile);
  618. source.setSystemId(sysid);
  619. log("catalog entry matched a readable file: '"
  620. + sysid + "'", Project.MSG_DEBUG);
  621. } catch (IOException ex) {
  622. // ignore
  623. }
  624. }
  625. }
  626. }
  627. return source;
  628. }
  629. /**
  630. * Utility method to lookup a ResourceLocation in the classpath.
  631. *
  632. * @return An InputSource for reading the resource, or <code>null</code>
  633. * if the resource does not exist in the classpath or is not readable.
  634. */
  635. private InputSource classpathLookup(ResourceLocation matchingEntry) {
  636. InputSource source = null;
  637. AntClassLoader loader = null;
  638. Path cp = classpath;
  639. if (cp != null) {
  640. cp = classpath.concatSystemClasspath("ignore");
  641. } else {
  642. cp = (new Path(getProject())).concatSystemClasspath("last");
  643. }
  644. loader = getProject().createClassLoader(cp);
  645. //
  646. // for classpath lookup we ignore the base directory
  647. //
  648. InputStream is
  649. = loader.getResourceAsStream(matchingEntry.getLocation());
  650. if (is != null) {
  651. source = new InputSource(is);
  652. URL entryURL = loader.getResource(matchingEntry.getLocation());
  653. String sysid = entryURL.toExternalForm();
  654. source.setSystemId(sysid);
  655. log("catalog entry matched a resource in the classpath: '"
  656. + sysid + "'", Project.MSG_DEBUG);
  657. }
  658. return source;
  659. }
  660. /**
  661. * Utility method to lookup a ResourceLocation in URL-space.
  662. *
  663. * @return An InputSource for reading the resource, or <code>null</code>
  664. * if the resource does not identify a valid URL or is not readable.
  665. */
  666. private InputSource urlLookup(ResourceLocation matchingEntry) {
  667. String uri = matchingEntry.getLocation();
  668. URL baseURL = null;
  669. //
  670. // The ResourceLocation may specify a relative url for its
  671. // location attribute. This is resolved using the appropriate
  672. // base.
  673. //
  674. if (matchingEntry.getBase() != null) {
  675. baseURL = matchingEntry.getBase();
  676. } else {
  677. try {
  678. baseURL = fileUtils.getFileURL(getProject().getBaseDir());
  679. } catch (MalformedURLException ex) {
  680. throw new BuildException("Project basedir cannot be converted to a URL");
  681. }
  682. }
  683. InputSource source = null;
  684. URL url = null;
  685. try {
  686. url = new URL(baseURL, uri);
  687. } catch (MalformedURLException ex) {
  688. // ignore
  689. }
  690. if (url != null) {
  691. try {
  692. InputStream is = url.openStream();
  693. if (is != null) {
  694. source = new InputSource(is);
  695. String sysid = url.toExternalForm();
  696. source.setSystemId(sysid);
  697. log("catalog entry matched as a URL: '"
  698. + sysid + "'", Project.MSG_DEBUG);
  699. }
  700. } catch (IOException ex) {
  701. // ignore
  702. }
  703. }
  704. return source;
  705. }
  706. /**
  707. * Interface implemented by both the InternalResolver strategy and
  708. * the ExternalResolver strategy.
  709. */
  710. private interface CatalogResolver extends URIResolver, EntityResolver {
  711. InputSource resolveEntity(String publicId, String systemId);
  712. Source resolve(String href, String base) throws TransformerException;
  713. }
  714. /**
  715. * The InternalResolver strategy is used if the Apache resolver
  716. * library (Norm Walsh's library from xml-commons) is not
  717. * available. In this case, external catalog files will be
  718. * ignored.
  719. *
  720. */
  721. private class InternalResolver implements CatalogResolver {
  722. public InternalResolver() {
  723. log("Apache resolver library not found, internal resolver will be used",
  724. Project.MSG_VERBOSE);
  725. }
  726. public InputSource resolveEntity(String publicId,
  727. String systemId) {
  728. InputSource result = null;
  729. ResourceLocation matchingEntry = findMatchingEntry(publicId);
  730. if (matchingEntry != null) {
  731. log("Matching catalog entry found for publicId: '"
  732. + matchingEntry.getPublicId() + "' location: '"
  733. + matchingEntry.getLocation() + "'",
  734. Project.MSG_DEBUG);
  735. result = filesystemLookup(matchingEntry);
  736. if (result == null) {
  737. result = classpathLookup(matchingEntry);
  738. }
  739. if (result == null) {
  740. result = urlLookup(matchingEntry);
  741. }
  742. }
  743. return result;
  744. }
  745. public Source resolve(String href, String base)
  746. throws TransformerException {
  747. SAXSource result = null;
  748. InputSource source = null;
  749. ResourceLocation matchingEntry = findMatchingEntry(href);
  750. if (matchingEntry != null) {
  751. log("Matching catalog entry found for uri: '"
  752. + matchingEntry.getPublicId() + "' location: '"
  753. + matchingEntry.getLocation() + "'",
  754. Project.MSG_DEBUG);
  755. //
  756. // Use the passed in base in preference to the base
  757. // from matchingEntry, which is either null or the
  758. // directory in which the external catalog file from
  759. // which it was obtained is located. We make a copy
  760. // so matchingEntry's original base is untouched.
  761. //
  762. // This is the standard behavior as per my reading of
  763. // the JAXP and XML Catalog specs. CKS 11/7/2002
  764. //
  765. ResourceLocation entryCopy = matchingEntry;
  766. if (base != null) {
  767. try {
  768. URL baseURL = new URL(base);
  769. entryCopy = new ResourceLocation();
  770. entryCopy.setBase(baseURL);
  771. } catch (MalformedURLException ex) {
  772. // ignore
  773. }
  774. }
  775. entryCopy.setPublicId(matchingEntry.getPublicId());
  776. entryCopy.setLocation(matchingEntry.getLocation());
  777. source = filesystemLookup(entryCopy);
  778. if (source == null) {
  779. source = classpathLookup(entryCopy);
  780. }
  781. if (source == null) {
  782. source = urlLookup(entryCopy);
  783. }
  784. if (source != null) {
  785. result = new SAXSource(source);
  786. }
  787. }
  788. return result;
  789. }
  790. }
  791. /**
  792. * The ExternalResolver strategy is used if the Apache resolver
  793. * library (Norm Walsh's library from xml-commons) is available in
  794. * the classpath. The ExternalResolver is a essentially a superset
  795. * of the InternalResolver.
  796. *
  797. */
  798. private class ExternalResolver implements CatalogResolver {
  799. private Method setXMLCatalog = null;
  800. private Method parseCatalog = null;
  801. private Method resolveEntity = null;
  802. private Method resolve = null;
  803. /** The instance of the ApacheCatalogResolver bridge class */
  804. private Object resolverImpl = null;
  805. private boolean externalCatalogsProcessed = false;
  806. public ExternalResolver(Class resolverImplClass,
  807. Object resolverImpl) {
  808. this.resolverImpl = resolverImpl;
  809. //
  810. // Get Method instances for each of the methods we need to
  811. // call on the resolverImpl using reflection. We can't
  812. // call them directly, because they require on the
  813. // xml-commons resolver library which may not be available
  814. // in the classpath.
  815. //
  816. try {
  817. setXMLCatalog =
  818. resolverImplClass.getMethod("setXMLCatalog",
  819. new Class[] {XMLCatalog.class});
  820. parseCatalog =
  821. resolverImplClass.getMethod("parseCatalog",
  822. new Class[] {String.class});
  823. resolveEntity =
  824. resolverImplClass.getMethod("resolveEntity",
  825. new Class[] {String.class, String.class});
  826. resolve =
  827. resolverImplClass.getMethod("resolve",
  828. new Class[] {String.class, String.class});
  829. } catch (NoSuchMethodException ex) {
  830. throw new BuildException(ex);
  831. }
  832. log("Apache resolver library found, xml-commons resolver will be used",
  833. Project.MSG_VERBOSE);
  834. }
  835. public InputSource resolveEntity(String publicId,
  836. String systemId) {
  837. InputSource result = null;
  838. processExternalCatalogs();
  839. ResourceLocation matchingEntry = findMatchingEntry(publicId);
  840. if (matchingEntry != null) {
  841. log("Matching catalog entry found for publicId: '"
  842. + matchingEntry.getPublicId() + "' location: '"
  843. + matchingEntry.getLocation() + "'",
  844. Project.MSG_DEBUG);
  845. result = filesystemLookup(matchingEntry);
  846. if (result == null) {
  847. result = classpathLookup(matchingEntry);
  848. }
  849. if (result == null) {
  850. try {
  851. result =
  852. (InputSource) resolveEntity.invoke(resolverImpl,
  853. new Object[] {publicId, systemId});
  854. } catch (Exception ex) {
  855. throw new BuildException(ex);
  856. }
  857. }
  858. } else {
  859. //
  860. // We didn't match a ResourceLocation, but since we
  861. // only support PUBLIC and URI entry types internally,
  862. // it is still possible that there is another entry in
  863. // an external catalog that will match. We call
  864. // Apache resolver's resolveEntity method to cover
  865. // this possibility.
  866. //
  867. try {
  868. result =
  869. (InputSource) resolveEntity.invoke(resolverImpl,
  870. new Object[] {publicId, systemId});
  871. } catch (Exception ex) {
  872. throw new BuildException(ex);
  873. }
  874. }
  875. return result;
  876. }
  877. public Source resolve(String href, String base)
  878. throws TransformerException {
  879. SAXSource result = null;
  880. InputSource source = null;
  881. processExternalCatalogs();
  882. ResourceLocation matchingEntry = findMatchingEntry(href);
  883. if (matchingEntry != null) {
  884. log("Matching catalog entry found for uri: '"
  885. + matchingEntry.getPublicId() + "' location: '"
  886. + matchingEntry.getLocation() + "'",
  887. Project.MSG_DEBUG);
  888. //
  889. // Use the passed in base in preference to the base
  890. // from matchingEntry, which is either null or the
  891. // directory in which the external catalog file from
  892. // which it was obtained is located. We make a copy
  893. // so matchingEntry's original base is untouched. Of
  894. // course, if there is no base, no need to make a
  895. // copy...
  896. //
  897. // This is the standard behavior as per my reading of
  898. // the JAXP and XML Catalog specs. CKS 11/7/2002
  899. //
  900. ResourceLocation entryCopy = matchingEntry;
  901. if (base != null) {
  902. try {
  903. URL baseURL = new URL(base);
  904. entryCopy = new ResourceLocation();
  905. entryCopy.setBase(baseURL);
  906. } catch (MalformedURLException ex) {
  907. // ignore
  908. }
  909. }
  910. entryCopy.setPublicId(matchingEntry.getPublicId());
  911. entryCopy.setLocation(matchingEntry.getLocation());
  912. source = filesystemLookup(entryCopy);
  913. if (source == null) {
  914. source = classpathLookup(entryCopy);
  915. }
  916. if (source != null) {
  917. result = new SAXSource(source);
  918. } else {
  919. try {
  920. result =
  921. (SAXSource) resolve.invoke(resolverImpl,
  922. new Object[] {href, base});
  923. } catch (Exception ex) {
  924. throw new BuildException(ex);
  925. }
  926. }
  927. } else {
  928. //
  929. // We didn't match a ResourceLocation, but since we
  930. // only support PUBLIC and URI entry types internally,
  931. // it is still possible that there is another entry in
  932. // an external catalog that will match. We call
  933. // Apache resolver's resolveEntity method to cover
  934. // this possibility.
  935. //
  936. try {
  937. result =
  938. (SAXSource) resolve.invoke(resolverImpl,
  939. new Object[] {href, base});
  940. } catch (Exception ex) {
  941. throw new BuildException(ex);
  942. }
  943. }
  944. return result;
  945. }
  946. /**
  947. * Process each external catalog file specified in a
  948. * <code><catalogpath></code>. It will be
  949. * parsed by the resolver library, and the individual elements
  950. * will be added back to us (that is, the controlling
  951. * XMLCatalog instance) via a callback mechanism.
  952. */
  953. private void processExternalCatalogs() {
  954. if (!externalCatalogsProcessed) {
  955. try {
  956. setXMLCatalog.invoke(resolverImpl,
  957. new Object[] {XMLCatalog.this});
  958. } catch (Exception ex) {
  959. throw new BuildException(ex);
  960. }
  961. // Parse each catalog listed in nested <catalogpath> elements
  962. Path catPath = getCatalogPath();
  963. if (catPath != null) {
  964. log("Using catalogpath '" + getCatalogPath() + "'",
  965. Project.MSG_DEBUG);
  966. String[] catPathList = getCatalogPath().list();
  967. for (int i = 0; i < catPathList.length; i++) {
  968. File catFile = new File(catPathList[i]);
  969. log("Parsing " + catFile, Project.MSG_DEBUG);
  970. try {
  971. parseCatalog.invoke(resolverImpl,
  972. new Object[] {catFile.getPath()});
  973. } catch (Exception ex) {
  974. throw new BuildException(ex);
  975. }
  976. }
  977. }
  978. }
  979. externalCatalogsProcessed = true;
  980. }
  981. }
  982. } //-- XMLCatalog