XCat.java 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  1. /* XCat.java --
  2. Copyright (C) 2001 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package gnu.xml.util;
  32. import gnu.java.lang.CPStringBuilder;
  33. import java.io.ByteArrayOutputStream;
  34. import java.io.IOException;
  35. import java.net.URL;
  36. import java.util.Enumeration;
  37. import java.util.Hashtable;
  38. import java.util.StringTokenizer;
  39. import java.util.Stack;
  40. import java.util.Vector;
  41. import org.xml.sax.Attributes;
  42. import org.xml.sax.ErrorHandler;
  43. import org.xml.sax.InputSource;
  44. import org.xml.sax.Locator;
  45. import org.xml.sax.SAXException;
  46. import org.xml.sax.SAXNotRecognizedException;
  47. import org.xml.sax.SAXParseException;
  48. import org.xml.sax.XMLReader;
  49. import org.xml.sax.ext.DefaultHandler2;
  50. import org.xml.sax.ext.EntityResolver2;
  51. import org.xml.sax.helpers.XMLReaderFactory;
  52. /**
  53. * Packages <a href=
  54. "http://www.oasis-open.org/committees/entity/spec-2001-08-06.html"
  55. >OASIS XML Catalogs</a>,
  56. * primarily for entity resolution by parsers.
  57. * That specification defines an XML syntax for mappings between
  58. * identifiers declared in DTDs (particularly PUBLIC identifiers) and
  59. * locations. SAX has always supported such mappings, but conventions for
  60. * an XML file syntax to maintain them have previously been lacking.
  61. *
  62. * <p> This has three main operational modes. The primary intended mode is
  63. * to create a resolver, then preloading it with one or more site-standard
  64. * catalogs before using it with one or more SAX parsers: <pre>
  65. * XCat catalog = new XCat ();
  66. * catalog.setErrorHandler (diagnosticErrorHandler);
  67. * catalog.loadCatalog ("file:/local/catalogs/catalog.cat");
  68. * catalog.loadCatalog ("http://shared/catalog.cat");
  69. * ...
  70. * catalog.disableLoading ();
  71. * parser1.setEntityResolver (catalog);
  72. * parser2.setEntityResolver (catalog);
  73. * ...</pre>
  74. *
  75. * <p>A second mode is to arrange that your application uses instances of
  76. * this class as its entity resolver, and automatically loads catalogs
  77. * referenced by <em>&lt;?oasis-xml-catalog...?&gt;</em> processing
  78. * instructions found before the DTD in documents it parses.
  79. * It would then discard the resolver after each parse.
  80. *
  81. * <p> A third mode applies catalogs in contexts other than entity
  82. * resolution for parsers.
  83. * The {@link #resolveURI resolveURI()} method supports resolving URIs
  84. * stored in XML application data, rather than inside DTDs.
  85. * Catalogs would be loaded as shown above, and the catalog could
  86. * be used concurrently for parser entity resolution and for
  87. * application URI resolution.
  88. * </p>
  89. *
  90. * <center><hr width='70%'></center>
  91. *
  92. * <p>Errors in catalogs implicitly loaded (during resolution) are ignored
  93. * beyond being reported through any <em>ErrorHandler</em> assigned using
  94. * {@link #setErrorHandler setErrorHandler()}. SAX exceptions
  95. * thrown from such a handler won't abort resolution, although throwing a
  96. * <em>RuntimeException</em> or <em>Error</em> will normally abort both
  97. * resolution and parsing. Useful diagnostic information is available to
  98. * any <em>ErrorHandler</em> used to report problems, or from any exception
  99. * thrown from an explicit {@link #loadCatalog loadCatalog()} invocation.
  100. * Applications can use that information as troubleshooting aids.
  101. *
  102. * <p>While this class requires <em>SAX2 Extensions 1.1</em> classes in
  103. * its class path, basic functionality does not require using a SAX2
  104. * parser that supports the extended entity resolution functionality.
  105. * See the original SAX1
  106. * {@link #resolveEntity(java.lang.String,java.lang.String) resolveEntity()}
  107. * method for a list of restrictions which apply when it is used with
  108. * older SAX parsers.
  109. *
  110. * @see EntityResolver2
  111. *
  112. * @author David Brownell
  113. */
  114. public class XCat implements EntityResolver2
  115. {
  116. private Catalog catalogs [];
  117. private boolean usingPublic = true;
  118. private boolean loadingPermitted = true;
  119. private boolean unified = true;
  120. private String parserClass;
  121. private ErrorHandler errorHandler;
  122. // private EntityResolver next; // chain to next if we fail...
  123. //
  124. // NOTE: This is a straightforward implementation, and if
  125. // there are lots of "nextCatalog" or "delegate*" entries
  126. // in use, two tweaks would be worth considering:
  127. //
  128. // - Centralize some sort of cache (key by URI) for individual
  129. // resolvers. That'd avoid multiple copies of a given catalog.
  130. //
  131. // - Have resolution track what catalogs (+modes) have been
  132. // searched. This would support loop detection.
  133. //
  134. /**
  135. * Initializes without preloading a catalog.
  136. * This API is convenient when you may want to arrange that catalogs
  137. * are automatically loaded when explicitly referenced in documents,
  138. * using the <em>oasis-xml-catalog</em> processing instruction.
  139. * In such cases you won't usually be able to preload catalogs.
  140. */
  141. public XCat () { }
  142. /**
  143. * Initializes, and preloads a catalog using the default SAX parser.
  144. * This API is convenient when you operate with one or more standard
  145. * catalogs.
  146. *
  147. * <p> This just delegates to {@link #loadCatalog loadCatalog()};
  148. * see it for exception information.
  149. *
  150. * @param uri absolute URI for the catalog file.
  151. */
  152. public XCat (String uri)
  153. throws SAXException, IOException
  154. { loadCatalog (uri); }
  155. /**
  156. * Loads an OASIS XML Catalog.
  157. * It is appended to the list of currently active catalogs, or
  158. * reloaded if a catalog with the same URI was already loaded.
  159. * Callers have control over what parser is used, how catalog parsing
  160. * errors are reported, and whether URIs will be resolved consistently.
  161. *
  162. * <p> The OASIS specification says that errors detected when loading
  163. * catalogs "must recover by ignoring the catalog entry file that
  164. * failed, and proceeding." In this API, that action can be the
  165. * responsibility of applications, when they explicitly load any
  166. * catalog using this method.
  167. *
  168. * <p>Note that catalogs referenced by this one will not be loaded
  169. * at this time. Catalogs referenced through <em>nextCatalog</em>
  170. * or <em>delegate*</em> elements are normally loaded only if needed.
  171. *
  172. * @see #setErrorHandler
  173. * @see #setParserClass
  174. * @see #setUnified
  175. *
  176. * @param uri absolute URI for the catalog file.
  177. *
  178. * @exception IOException As thrown by the parser, typically to
  179. * indicate problems reading data from that URI.
  180. * @exception SAXException As thrown by the parser, typically to
  181. * indicate problems parsing data from that URI. It may also
  182. * be thrown if the parser doesn't support necessary handlers.
  183. * @exception IllegalStateException When attempting to load a
  184. * catalog after loading has been {@link #disableLoading disabled},
  185. * such as after any entity or URI lookup has been performed.
  186. */
  187. public synchronized void loadCatalog (String uri)
  188. throws SAXException, IOException
  189. {
  190. Catalog catalog;
  191. int index = -1;
  192. if (!loadingPermitted)
  193. throw new IllegalStateException ();
  194. uri = normalizeURI (uri);
  195. if (catalogs != null) {
  196. // maybe just reload
  197. for (index = 0; index < catalogs.length; index++)
  198. if (uri.equals (catalogs [index].catalogURI))
  199. break;
  200. }
  201. catalog = loadCatalog (parserClass, errorHandler, uri, unified);
  202. // add to list of catalogs
  203. if (catalogs == null) {
  204. index = 0;
  205. catalogs = new Catalog [1];
  206. } else if (index == catalogs.length) {
  207. Catalog tmp [];
  208. tmp = new Catalog [index + 1];
  209. System.arraycopy (catalogs, 0, tmp, 0, index);
  210. catalogs = tmp;
  211. }
  212. catalogs [index] = catalog;
  213. }
  214. /**
  215. * "New Style" external entity resolution for parsers.
  216. * Calls to this method prevent explicit loading of additional catalogs
  217. * using {@link #loadCatalog loadCatalog()}.
  218. *
  219. * <p>This supports the full core catalog functionality for locating
  220. * (and relocating) parsed entities that have been declared in a
  221. * document's DTD.
  222. *
  223. * @param name Entity name, such as "dudley", "%nell", or "[dtd]".
  224. * @param publicId Either a normalized public ID, or null.
  225. * @param baseURI Absolute base URI associated with systemId.
  226. * @param systemId URI found in entity declaration (may be
  227. * relative to baseURI).
  228. *
  229. * @return Input source for accessing the external entity, or null
  230. * if no mapping was found. The input source may have opened
  231. * the stream, and will have a fully resolved URI.
  232. *
  233. * @see #getExternalSubset
  234. */
  235. public InputSource resolveEntity (
  236. String name, // UNUSED ... systemId is always non-null
  237. String publicId,
  238. String baseURI, // UNUSED ... it just lets sysId be relative
  239. String systemId
  240. ) throws SAXException, IOException
  241. {
  242. if (loadingPermitted)
  243. disableLoading ();
  244. try {
  245. // steps as found in OASIS XML catalog spec 7.1.2
  246. // steps 1, 8 involve looping over the list of catalogs
  247. for (int i = 0; i < catalogs.length; i++) {
  248. InputSource retval;
  249. retval = catalogs [i].resolve (usingPublic, publicId, systemId);
  250. if (retval != null)
  251. return retval;
  252. }
  253. } catch (DoneDelegation x) {
  254. // done!
  255. }
  256. // step 9 involves returning "no match"
  257. return null;
  258. }
  259. /**
  260. * "New Style" parser callback to add an external subset.
  261. * For documents that don't include an external subset, this may
  262. * return one according to <em>doctype</em> catalog entries.
  263. * (This functionality is not a core part of the OASIS XML Catalog
  264. * specification, though it's presented in an appendix.)
  265. * If no such entry is defined, this returns null to indicate that
  266. * this document will not be modified to include such a subset.
  267. * Calls to this method prevent explicit loading of additional catalogs
  268. * using {@link #loadCatalog loadCatalog()}.
  269. *
  270. * <p><em>Warning:</em> That catalog functionality can be dangerous.
  271. * It can provide definitions of general entities, and thereby mask
  272. * certain well formedess errors.
  273. *
  274. * @param name Name of the document element, either as declared in
  275. * a DOCTYPE declaration or as observed in the text.
  276. * @param baseURI Document's base URI (absolute).
  277. *
  278. * @return Input source for accessing the external subset, or null
  279. * if no mapping was found. The input source may have opened
  280. * the stream, and will have a fully resolved URI.
  281. */
  282. public InputSource getExternalSubset (String name, String baseURI)
  283. throws SAXException, IOException
  284. {
  285. if (loadingPermitted)
  286. disableLoading ();
  287. try {
  288. for (int i = 0; i < catalogs.length; i++) {
  289. InputSource retval = catalogs [i].getExternalSubset (name);
  290. if (retval != null)
  291. return retval;
  292. }
  293. } catch (DoneDelegation x) {
  294. // done!
  295. }
  296. return null;
  297. }
  298. /**
  299. * "Old Style" external entity resolution for parsers.
  300. * This API provides only core functionality.
  301. * Calls to this method prevent explicit loading of additional catalogs
  302. * using {@link #loadCatalog loadCatalog()}.
  303. *
  304. * <p>The functional limitations of this interface include:</p><ul>
  305. *
  306. * <li>Since system IDs will be absolutized before the resolver
  307. * sees them, matching against relative URIs won't work.
  308. * This may affect <em>system</em>, <em>rewriteSystem</em>,
  309. * and <em>delegateSystem</em> catalog entries.
  310. *
  311. * <li>Because of that absolutization, documents declaring entities
  312. * with system IDs using URI schemes that the JVM does not recognize
  313. * may be unparsable. URI schemes such as <em>file:/</em>,
  314. * <em>http://</em>, <em>https://</em>, and <em>ftp://</em>
  315. * will usually work reliably.
  316. *
  317. * <li>Because missing external subsets can't be provided, the
  318. * <em>doctype</em> catalog entries will be ignored.
  319. * (The {@link #getExternalSubset getExternalSubset()} method is
  320. * a "New Style" resolution option.)
  321. *
  322. * </ul>
  323. *
  324. * <p>Applications can tell whether this limited functionality will be
  325. * used: if the feature flag associated with the {@link EntityResolver2}
  326. * interface is not <em>true</em>, the limitations apply. Applications
  327. * can't usually know whether a given document and catalog will trigger
  328. * those limitations. The issue can only be bypassed by operational
  329. * procedures such as not using catalogs or documents which involve
  330. * those features.
  331. *
  332. * @param publicId Either a normalized public ID, or null
  333. * @param systemId Always an absolute URI.
  334. *
  335. * @return Input source for accessing the external entity, or null
  336. * if no mapping was found. The input source may have opened
  337. * the stream, and will have a fully resolved URI.
  338. */
  339. final public InputSource resolveEntity (String publicId, String systemId)
  340. throws SAXException, IOException
  341. {
  342. return resolveEntity (null, publicId, null, systemId);
  343. }
  344. /**
  345. * Resolves a URI reference that's not defined to the DTD.
  346. * This is intended for use with URIs found in document text, such as
  347. * <em>xml-stylesheet</em> processing instructions and in attribute
  348. * values, where they are not recognized as URIs by XML parsers.
  349. * Calls to this method prevent explicit loading of additional catalogs
  350. * using {@link #loadCatalog loadCatalog()}.
  351. *
  352. * <p>This functionality is supported by the OASIS XML Catalog
  353. * specification, but will never be invoked by an XML parser.
  354. * It corresponds closely to functionality for mapping system
  355. * identifiers for entities declared in DTDs; closely enough that
  356. * this implementation's default behavior is that they be
  357. * identical, to minimize potential confusion.
  358. *
  359. * <p>This method could be useful when implementing the
  360. * {@link javax.xml.transform.URIResolver} interface, wrapping the
  361. * input source in a {@link javax.xml.transform.sax.SAXSource}.
  362. *
  363. * @see #isUnified
  364. * @see #setUnified
  365. *
  366. * @param baseURI The relevant base URI as specified by the XML Base
  367. * specification. This recognizes <em>xml:base</em> attributes
  368. * as overriding the actual (physical) base URI.
  369. * @param uri Either an absolute URI, or one relative to baseURI
  370. *
  371. * @return Input source for accessing the mapped URI, or null
  372. * if no mapping was found. The input source may have opened
  373. * the stream, and will have a fully resolved URI.
  374. */
  375. public InputSource resolveURI (String baseURI, String uri)
  376. throws SAXException, IOException
  377. {
  378. if (loadingPermitted)
  379. disableLoading ();
  380. // NOTE: baseURI isn't used here, but caller MUST have it,
  381. // and heuristics _might_ use it in the future ... plus,
  382. // it's symmetric with resolveEntity ().
  383. // steps 1, 6 involve looping
  384. try {
  385. for (int i = 0; i < catalogs.length; i++) {
  386. InputSource tmp = catalogs [i].resolveURI (uri);
  387. if (tmp != null)
  388. return tmp;
  389. }
  390. } catch (DoneDelegation x) {
  391. // done
  392. }
  393. // step 7 reports no match
  394. return null;
  395. }
  396. /**
  397. * Records that catalog loading is no longer permitted.
  398. * Loading is automatically disabled when lookups are performed,
  399. * and should be manually disabled when <em>startDTD()</em> (or
  400. * any other DTD declaration callback) is invoked, or at the latest
  401. * when the document root element is seen.
  402. */
  403. public synchronized void disableLoading ()
  404. {
  405. // NOTE: this method and loadCatalog() are synchronized
  406. // so that it's impossible to load (top level) catalogs
  407. // after lookups start. Likewise, deferred loading is also
  408. // synchronized (for "next" and delegated catalogs) to
  409. // ensure that parsers can share resolvers.
  410. loadingPermitted = false;
  411. }
  412. /**
  413. * Returns the error handler used to report catalog errors.
  414. * Null is returned if the parser's default error handling
  415. * will be used.
  416. *
  417. * @see #setErrorHandler
  418. */
  419. public ErrorHandler getErrorHandler ()
  420. { return errorHandler; }
  421. /**
  422. * Assigns the error handler used to report catalog errors.
  423. * These errors may come either from the SAX2 parser or
  424. * from the catalog parsing code driven by the parser.
  425. *
  426. * <p> If you're sharing the resolver between parsers, don't
  427. * change this once lookups have begun.
  428. *
  429. * @see #getErrorHandler
  430. *
  431. * @param parser The error handler, or null saying to use the default
  432. * (no diagnostics, and only fatal errors terminate loading).
  433. */
  434. public void setErrorHandler (ErrorHandler handler)
  435. { errorHandler = handler; }
  436. /**
  437. * Returns the name of the SAX2 parser class used to parse catalogs.
  438. * Null is returned if the system default is used.
  439. * @see #setParserClass
  440. */
  441. public String getParserClass ()
  442. { return parserClass; }
  443. /**
  444. * Names the SAX2 parser class used to parse catalogs.
  445. *
  446. * <p> If you're sharing the resolver between parsers, don't change
  447. * this once lookups have begun.
  448. *
  449. * <p> Note that in order to properly support the <em>xml:base</em>
  450. * attribute and relative URI resolution, the SAX parser used to parse
  451. * the catalog must provide a {@link Locator} and support the optional
  452. * declaration and lexical handlers.
  453. *
  454. * @see #getParserClass
  455. *
  456. * @param parser The parser class name, or null saying to use the
  457. * system default SAX2 parser.
  458. */
  459. public void setParserClass (String parser)
  460. { parserClass = parser; }
  461. /**
  462. * Returns true (the default) if all methods resolve
  463. * a given URI in the same way.
  464. * Returns false if calls resolving URIs as entities (such as
  465. * {@link #resolveEntity resolveEntity()}) use different catalog entries
  466. * than those resolving them as URIs ({@link #resolveURI resolveURI()}),
  467. * which will generally produce different results.
  468. *
  469. * <p>The OASIS XML Catalog specification defines two related schemes
  470. * to map URIs "as URIs" or "as system IDs".
  471. * URIs use <em>uri</em>, <em>rewriteURI</em>, and <em>delegateURI</em>
  472. * elements. System IDs do the same things with <em>systemId</em>,
  473. * <em>rewriteSystemId</em>, and <em>delegateSystemId</em>.
  474. * It's confusing and error prone to maintain two parallel copies of
  475. * such data. Accordingly, this class makes that behavior optional.
  476. * The <em>unified</em> interpretation of URI mappings is preferred,
  477. * since it prevents surprises where one URI gets mapped to different
  478. * contents depending on whether the reference happens to have come
  479. * from a DTD (or not).
  480. *
  481. * @see #setUnified
  482. */
  483. public boolean isUnified ()
  484. { return unified; }
  485. /**
  486. * Assigns the value of the flag returned by {@link #isUnified}.
  487. * Set it to false to be strictly conformant with the OASIS XML Catalog
  488. * specification. Set it to true to make all mappings for a given URI
  489. * give the same result, regardless of the reason for the mapping.
  490. *
  491. * <p>Don't change this once you've loaded the first catalog.
  492. *
  493. * @param value new flag setting
  494. */
  495. public void setUnified (boolean value)
  496. { unified = value; }
  497. /**
  498. * Returns true (the default) if a catalog's public identifier
  499. * mappings will be used.
  500. * When false is returned, such mappings are ignored except when
  501. * system IDs are discarded, such as for
  502. * entities using the <em>urn:publicid:</em> URI scheme in their
  503. * system identifiers. (See RFC 3151 for information about that
  504. * URI scheme. Using it in system identifiers may not work well
  505. * with many SAX parsers unless the <em>resolve-dtd-uris</em>
  506. * feature flag is set to false.)
  507. * @see #setUsingPublic
  508. */
  509. public boolean isUsingPublic ()
  510. { return usingPublic; }
  511. /**
  512. * Specifies which catalog search mode is used.
  513. * By default, public identifier mappings are able to override system
  514. * identifiers when both are available.
  515. * Applications may choose to ignore public
  516. * identifier mappings in such cases, so that system identifiers
  517. * declared in DTDs will only be overridden by an explicit catalog
  518. * match for that system ID.
  519. *
  520. * <p> If you're sharing the resolver between parsers, don't
  521. * change this once lookups have begun.
  522. * @see #isUsingPublic
  523. *
  524. * @param value true to always use public identifier mappings,
  525. * false to only use them for system ids using the <em>urn:publicid:</em>
  526. * URI scheme.
  527. */
  528. public void setUsingPublic (boolean value)
  529. { usingPublic = value; }
  530. // hmm, what's this do? :)
  531. private static Catalog loadCatalog (
  532. String parserClass,
  533. ErrorHandler eh,
  534. String uri,
  535. boolean unified
  536. ) throws SAXException, IOException
  537. {
  538. XMLReader parser;
  539. Loader loader;
  540. boolean doesIntern = false;
  541. if (parserClass == null)
  542. parser = XMLReaderFactory.createXMLReader ();
  543. else
  544. parser = XMLReaderFactory.createXMLReader (parserClass);
  545. if (eh != null)
  546. parser.setErrorHandler (eh);
  547. // resolve-dtd-entities is at default value (unrecognized == true)
  548. try {
  549. doesIntern = parser.getFeature (
  550. "http://xml.org/sax/features/string-interning");
  551. } catch (SAXNotRecognizedException e) { }
  552. loader = new Loader (doesIntern, eh, unified);
  553. loader.cat.parserClass = parserClass;
  554. loader.cat.catalogURI = uri;
  555. parser.setContentHandler (loader);
  556. parser.setProperty (
  557. "http://xml.org/sax/properties/declaration-handler",
  558. loader);
  559. parser.setProperty (
  560. "http://xml.org/sax/properties/lexical-handler",
  561. loader);
  562. parser.parse (uri);
  563. return loader.cat;
  564. }
  565. // perform one or both the normalizations for public ids
  566. private static String normalizePublicId (boolean full, String publicId)
  567. {
  568. if (publicId.startsWith ("urn:publicid:")) {
  569. CPStringBuilder buf = new CPStringBuilder ();
  570. char chars [] = publicId.toCharArray ();
  571. boolean hasbug = false;
  572. for (int i = 13; i < chars.length; i++) {
  573. switch (chars [i]) {
  574. case '+': buf.append (' '); continue;
  575. case ':': buf.append ("//"); continue;
  576. case ';': buf.append ("::"); continue;
  577. case '%':
  578. // FIXME unhex that char! meanwhile, warn and fallthrough ...
  579. hasbug = true;
  580. default: buf.append (chars [i]); continue;
  581. }
  582. }
  583. publicId = buf.toString ();
  584. if (hasbug)
  585. System.err.println ("nyet unhexing public id: " + publicId);
  586. full = true;
  587. }
  588. // SAX parsers do everything except that URN mapping, but
  589. // we can't trust other sources to normalize correctly
  590. if (full) {
  591. StringTokenizer tokens;
  592. String token;
  593. tokens = new StringTokenizer (publicId, " \r\n");
  594. publicId = null;
  595. while (tokens.hasMoreTokens ()) {
  596. if (publicId == null)
  597. publicId = tokens.nextToken ();
  598. else
  599. publicId += " " + tokens.nextToken ();
  600. }
  601. }
  602. return publicId;
  603. }
  604. private static boolean isUriExcluded (int c)
  605. { return c <= 0x20 || c >= 0x7f || "\"<>^`{|}".indexOf (c) != -1; }
  606. private static int hexNibble (int c)
  607. {
  608. if (c < 10)
  609. return c + '0';
  610. return ('a' - 10) + c;
  611. }
  612. // handles URIs with "excluded" characters
  613. private static String normalizeURI (String systemId)
  614. {
  615. int length = systemId.length ();
  616. for (int i = 0; i < length; i++) {
  617. char c = systemId.charAt (i);
  618. // escape non-ASCII plus "excluded" characters
  619. if (isUriExcluded (c)) {
  620. byte buf [];
  621. ByteArrayOutputStream out;
  622. int b;
  623. // a JVM that doesn't know UTF8 and 8859_1 is unusable!
  624. try {
  625. buf = systemId.getBytes ("UTF8");
  626. out = new ByteArrayOutputStream (buf.length + 10);
  627. for (i = 0; i < buf.length; i++) {
  628. b = buf [i] & 0x0ff;
  629. if (isUriExcluded (b)) {
  630. out.write ((int) '%');
  631. out.write (hexNibble (b >> 4));
  632. out.write (hexNibble (b & 0x0f));
  633. } else
  634. out.write (b);
  635. }
  636. return out.toString ("8859_1");
  637. } catch (IOException e) {
  638. throw new RuntimeException (
  639. "can't normalize URI: " + e.getMessage ());
  640. }
  641. }
  642. }
  643. return systemId;
  644. }
  645. // thrown to mark authoritative end of a search
  646. private static class DoneDelegation extends SAXException
  647. {
  648. DoneDelegation () { }
  649. }
  650. /**
  651. * Represents a OASIS XML Catalog, and encapsulates much of
  652. * the catalog functionality.
  653. */
  654. private static class Catalog
  655. {
  656. // loading infrastructure
  657. String catalogURI;
  658. ErrorHandler eh;
  659. boolean unified;
  660. String parserClass;
  661. // catalog data
  662. boolean hasPreference;
  663. boolean usingPublic;
  664. Hashtable publicIds;
  665. Hashtable publicDelegations;
  666. Hashtable systemIds;
  667. Hashtable systemRewrites;
  668. Hashtable systemDelegations;
  669. Hashtable uris;
  670. Hashtable uriRewrites;
  671. Hashtable uriDelegations;
  672. Hashtable doctypes;
  673. Vector next;
  674. // nonpublic!
  675. Catalog () { }
  676. // steps as found in OASIS XML catalog spec 7.1.2
  677. private InputSource locatePublicId (String publicId)
  678. throws SAXException, IOException
  679. {
  680. // 5. return (first) 'public' entry
  681. if (publicIds != null) {
  682. String retval = (String) publicIds.get (publicId);
  683. if (retval != null) {
  684. // IF the URI is accessible ...
  685. return new InputSource (retval);
  686. }
  687. }
  688. // 6. return delegatePublic catalog match [complex]
  689. if (publicDelegations != null)
  690. return checkDelegations (publicDelegations, publicId,
  691. publicId, null);
  692. return null;
  693. }
  694. // steps as found in OASIS XML catalog spec 7.1.2 or 7.2.2
  695. private InputSource mapURI (
  696. String uri,
  697. Hashtable ids,
  698. Hashtable rewrites,
  699. Hashtable delegations
  700. ) throws SAXException, IOException
  701. {
  702. // 7.1.2: 2. return (first) 'system' entry
  703. // 7.2.2: 2. return (first) 'uri' entry
  704. if (ids != null) {
  705. String retval = (String) ids.get (uri);
  706. if (retval != null) {
  707. // IF the URI is accessible ...
  708. return new InputSource (retval);
  709. }
  710. }
  711. // 7.1.2: 3. return 'rewriteSystem' entries
  712. // 7.2.2: 3. return 'rewriteURI' entries
  713. if (rewrites != null) {
  714. String prefix = null;
  715. String replace = null;
  716. int prefixLen = -1;
  717. for (Enumeration e = rewrites.keys ();
  718. e.hasMoreElements ();
  719. /* NOP */) {
  720. String temp = (String) e.nextElement ();
  721. int len = -1;
  722. if (!uri.startsWith (temp))
  723. continue;
  724. if (prefix != null
  725. && (len = temp.length ()) < prefixLen)
  726. continue;
  727. prefix = temp;
  728. prefixLen = len;
  729. replace = (String) rewrites.get (temp);
  730. }
  731. if (prefix != null) {
  732. CPStringBuilder buf = new CPStringBuilder (replace);
  733. buf.append (uri.substring (prefixLen));
  734. // IF the URI is accessible ...
  735. return new InputSource (buf.toString ());
  736. }
  737. }
  738. // 7.1.2: 4. return 'delegateSystem' catalog match [complex]
  739. // 7.2.2: 4. return 'delegateURI' catalog match [complex]
  740. if (delegations != null)
  741. return checkDelegations (delegations, uri, null, uri);
  742. return null;
  743. }
  744. /**
  745. * Returns a URI for an external entity.
  746. */
  747. public InputSource resolve (
  748. boolean usingPublic,
  749. String publicId,
  750. String systemId
  751. ) throws SAXException, IOException
  752. {
  753. boolean preferSystem;
  754. InputSource retval;
  755. if (hasPreference)
  756. preferSystem = !this.usingPublic;
  757. else
  758. preferSystem = !usingPublic;
  759. if (publicId != null)
  760. publicId = normalizePublicId (false, publicId);
  761. // behavior here matches section 7.1.1 of the oasis spec
  762. if (systemId != null) {
  763. if (systemId.startsWith ("urn:publicid:")) {
  764. String temp = normalizePublicId (true, systemId);
  765. if (publicId == null) {
  766. publicId = temp;
  767. systemId = null;
  768. } else if (!publicId.equals (temp)) {
  769. // error; ok to recover by:
  770. systemId = null;
  771. }
  772. } else
  773. systemId = normalizeURI (systemId);
  774. }
  775. if (systemId == null && publicId == null)
  776. return null;
  777. if (systemId != null) {
  778. retval = mapURI (systemId, systemIds, systemRewrites,
  779. systemDelegations);
  780. if (retval != null) {
  781. retval.setPublicId (publicId);
  782. return retval;
  783. }
  784. }
  785. if (publicId != null
  786. && !(systemId != null && preferSystem)) {
  787. retval = locatePublicId (publicId);
  788. if (retval != null) {
  789. retval.setPublicId (publicId);
  790. return retval;
  791. }
  792. }
  793. // 7. apply nextCatalog entries
  794. if (next != null) {
  795. int length = next.size ();
  796. for (int i = 0; i < length; i++) {
  797. Catalog n = getNext (i);
  798. retval = n.resolve (usingPublic, publicId, systemId);
  799. if (retval != null)
  800. return retval;
  801. }
  802. }
  803. return null;
  804. }
  805. /**
  806. * Maps one URI into another, for resources that are not defined
  807. * using XML external entity or notation syntax.
  808. */
  809. public InputSource resolveURI (String uri)
  810. throws SAXException, IOException
  811. {
  812. if (uri.startsWith ("urn:publicid:"))
  813. return resolve (true, normalizePublicId (true, uri), null);
  814. InputSource retval;
  815. uri = normalizeURI (uri);
  816. // 7.2.2 steps 2-4
  817. retval = mapURI (uri, uris, uriRewrites, uriDelegations);
  818. if (retval != null)
  819. return retval;
  820. // 7.2.2 step 5. apply nextCatalog entries
  821. if (next != null) {
  822. int length = next.size ();
  823. for (int i = 0; i < length; i++) {
  824. Catalog n = getNext (i);
  825. retval = n.resolveURI (uri);
  826. if (retval != null)
  827. return retval;
  828. }
  829. }
  830. return null;
  831. }
  832. /**
  833. * Finds the external subset associated with a given root element.
  834. */
  835. public InputSource getExternalSubset (String name)
  836. throws SAXException, IOException
  837. {
  838. if (doctypes != null) {
  839. String value = (String) doctypes.get (name);
  840. if (value != null) {
  841. // IF the URI is accessible ...
  842. return new InputSource (value);
  843. }
  844. }
  845. if (next != null) {
  846. int length = next.size ();
  847. for (int i = 0; i < length; i++) {
  848. Catalog n = getNext (i);
  849. if (n == null)
  850. continue;
  851. InputSource retval = n.getExternalSubset (name);
  852. if (retval != null)
  853. return retval;
  854. }
  855. }
  856. return null;
  857. }
  858. private synchronized Catalog getNext (int i)
  859. throws SAXException, IOException
  860. {
  861. Object obj;
  862. if (next == null || i < 0 || i >= next.size ())
  863. return null;
  864. obj = next.elementAt (i);
  865. if (obj instanceof Catalog)
  866. return (Catalog) obj;
  867. // ok, we deferred reading that catalog till now.
  868. // load and cache it.
  869. Catalog cat = null;
  870. try {
  871. cat = loadCatalog (parserClass, eh, (String) obj, unified);
  872. next.setElementAt (cat, i);
  873. } catch (SAXException e) {
  874. // must fail quietly, says the OASIS spec
  875. } catch (IOException e) {
  876. // same applies here
  877. }
  878. return cat;
  879. }
  880. private InputSource checkDelegations (
  881. Hashtable delegations,
  882. String id,
  883. String publicId, // only one of public/system
  884. String systemId // will be non-null...
  885. ) throws SAXException, IOException
  886. {
  887. Vector matches = null;
  888. int length = 0;
  889. // first, see if any prefixes match.
  890. for (Enumeration e = delegations.keys ();
  891. e.hasMoreElements ();
  892. /* NOP */) {
  893. String prefix = (String) e.nextElement ();
  894. if (!id.startsWith (prefix))
  895. continue;
  896. if (matches == null)
  897. matches = new Vector ();
  898. // maintain in longer->shorter sorted order
  899. // NOTE: assumes not many matches will fire!
  900. int index;
  901. for (index = 0; index < length; index++) {
  902. String temp = (String) matches.elementAt (index);
  903. if (prefix.length () > temp.length ()) {
  904. matches.insertElementAt (prefix, index);
  905. break;
  906. }
  907. }
  908. if (index == length)
  909. matches.addElement (prefix);
  910. length++;
  911. }
  912. if (matches == null)
  913. return null;
  914. // now we know the list of catalogs to replace our "top level"
  915. // list ... we use it here, rather than somehow going back and
  916. // restarting, since this helps avoid reading most catalogs.
  917. // this assumes stackspace won't be a problem.
  918. for (int i = 0; i < length; i++) {
  919. Catalog catalog = null;
  920. InputSource result;
  921. // get this catalog. we may not have read it yet.
  922. synchronized (delegations) {
  923. Object prefix = matches.elementAt (i);
  924. Object cat = delegations.get (prefix);
  925. if (cat instanceof Catalog)
  926. catalog = (Catalog) cat;
  927. else {
  928. try {
  929. // load and cache that catalog
  930. catalog = loadCatalog (parserClass, eh,
  931. (String) cat, unified);
  932. delegations.put (prefix, catalog);
  933. } catch (SAXException e) {
  934. // must ignore, says the OASIS spec
  935. } catch (IOException e) {
  936. // same applies here
  937. }
  938. }
  939. }
  940. // ignore failed loads, and proceed
  941. if (catalog == null)
  942. continue;
  943. // we have a catalog ... resolve!
  944. // usingPublic value can't matter, there's no choice
  945. result = catalog.resolve (true, publicId, systemId);
  946. if (result != null)
  947. return result;
  948. }
  949. // if there were no successes, the entire
  950. // lookup failed (all the way to top level)
  951. throw new DoneDelegation ();
  952. }
  953. }
  954. /** This is the namespace URI used for OASIS XML Catalogs. */
  955. private static final String catalogNamespace =
  956. "urn:oasis:names:tc:entity:xmlns:xml:catalog";
  957. /**
  958. * Loads/unmarshals one catalog.
  959. */
  960. private static class Loader extends DefaultHandler2
  961. {
  962. private boolean preInterned;
  963. private ErrorHandler handler;
  964. private boolean unified;
  965. private int ignoreDepth;
  966. private Locator locator;
  967. private boolean started;
  968. private Hashtable externals;
  969. private Stack bases;
  970. Catalog cat = new Catalog ();
  971. /**
  972. * Constructor.
  973. * @param flag true iff the parser already interns strings.
  974. * @param eh Errors and warnings are delegated to this.
  975. * @param unified true keeps one table for URI mappings;
  976. * false matches OASIS spec, storing mappings
  977. * for URIs and SYSTEM ids in parallel tables.
  978. */
  979. Loader (boolean flag, ErrorHandler eh, boolean unified)
  980. {
  981. preInterned = flag;
  982. handler = eh;
  983. this.unified = unified;
  984. cat.unified = unified;
  985. cat.eh = eh;
  986. }
  987. // strips out fragments
  988. private String nofrag (String uri)
  989. throws SAXException
  990. {
  991. if (uri.indexOf ('#') != -1) {
  992. warn ("URI with fragment: " + uri);
  993. uri = uri.substring (0, uri.indexOf ('#'));
  994. }
  995. return uri;
  996. }
  997. // absolutizes relative URIs
  998. private String absolutize (String uri)
  999. throws SAXException
  1000. {
  1001. // avoid creating URLs if they're already absolutized,
  1002. // or if the URI is already using a known scheme
  1003. if (uri.startsWith ("file:/")
  1004. || uri.startsWith ("http:/")
  1005. || uri.startsWith ("https:/")
  1006. || uri.startsWith ("ftp:/")
  1007. || uri.startsWith ("urn:")
  1008. )
  1009. return uri;
  1010. // otherwise, let's hope the JDK handles this URI scheme.
  1011. try {
  1012. URL base = (URL) bases.peek ();
  1013. return new URL (base, uri).toString ();
  1014. } catch (Exception e) {
  1015. fatal ("can't absolutize URI: " + uri);
  1016. return null;
  1017. }
  1018. }
  1019. // recoverable error
  1020. private void error (String message)
  1021. throws SAXException
  1022. {
  1023. if (handler == null)
  1024. return;
  1025. handler.error (new SAXParseException (message, locator));
  1026. }
  1027. // nonrecoverable error
  1028. private void fatal (String message)
  1029. throws SAXException
  1030. {
  1031. SAXParseException spe;
  1032. spe = new SAXParseException (message, locator);
  1033. if (handler != null)
  1034. handler.fatalError (spe);
  1035. throw spe;
  1036. }
  1037. // low severity problem
  1038. private void warn (String message)
  1039. throws SAXException
  1040. {
  1041. if (handler == null)
  1042. return;
  1043. handler.warning (new SAXParseException (message, locator));
  1044. }
  1045. // callbacks:
  1046. public void setDocumentLocator (Locator l)
  1047. { locator = l; }
  1048. public void startDocument ()
  1049. throws SAXException
  1050. {
  1051. if (locator == null)
  1052. error ("no locator!");
  1053. bases = new Stack ();
  1054. String uri = locator.getSystemId ();
  1055. try {
  1056. bases.push (new URL (uri));
  1057. } catch (IOException e) {
  1058. fatal ("bad document base URI: " + uri);
  1059. }
  1060. }
  1061. public void endDocument ()
  1062. throws SAXException
  1063. {
  1064. try {
  1065. if (!started)
  1066. error ("not a catalog!");
  1067. } finally {
  1068. locator = null;
  1069. handler = null;
  1070. externals = null;
  1071. bases = null;
  1072. }
  1073. }
  1074. // XML Base support for external entities.
  1075. // NOTE: expects parser is in default "resolve-dtd-uris" mode.
  1076. public void externalEntityDecl (String name, String pub, String sys)
  1077. throws SAXException
  1078. {
  1079. if (externals == null)
  1080. externals = new Hashtable ();
  1081. if (externals.get (name) == null)
  1082. externals.put (name, pub);
  1083. }
  1084. public void startEntity (String name)
  1085. throws SAXException
  1086. {
  1087. if (externals == null)
  1088. return;
  1089. String uri = (String) externals.get (name);
  1090. // NOTE: breaks if an EntityResolver substitutes these URIs.
  1091. // If toplevel loader supports one, must intercept calls...
  1092. if (uri != null) {
  1093. try {
  1094. bases.push (new URL (uri));
  1095. } catch (IOException e) {
  1096. fatal ("entity '" + name + "', bad URI: " + uri);
  1097. }
  1098. }
  1099. }
  1100. public void endEntity (String name)
  1101. {
  1102. if (externals == null)
  1103. return;
  1104. String value = (String) externals.get (name);
  1105. if (value != null)
  1106. bases.pop ();
  1107. }
  1108. /**
  1109. * Processes catalog elements, saving their data.
  1110. */
  1111. public void startElement (String namespace, String local,
  1112. String qName, Attributes atts)
  1113. throws SAXException
  1114. {
  1115. // must ignore non-catalog elements, and their contents
  1116. if (ignoreDepth != 0 || !catalogNamespace.equals (namespace)) {
  1117. ignoreDepth++;
  1118. return;
  1119. }
  1120. // basic sanity checks
  1121. if (!preInterned)
  1122. local = local.intern ();
  1123. if (!started) {
  1124. started = true;
  1125. if ("catalog" != local)
  1126. fatal ("root element not 'catalog': " + local);
  1127. }
  1128. // Handle any xml:base attribute
  1129. String xmlbase = atts.getValue ("xml:base");
  1130. if (xmlbase != null) {
  1131. URL base = (URL) bases.peek ();
  1132. try {
  1133. base = new URL (base, xmlbase);
  1134. } catch (IOException e) {
  1135. fatal ("can't resolve xml:base attribute: " + xmlbase);
  1136. }
  1137. bases.push (base);
  1138. } else
  1139. bases.push (bases.peek ());
  1140. // fetch multi-element attributes, apply standard tweaks
  1141. // values (uri, catalog, rewritePrefix) get normalized too,
  1142. // as a precaution and since we may compare the values
  1143. String catalog = atts.getValue ("catalog");
  1144. if (catalog != null)
  1145. catalog = normalizeURI (absolutize (catalog));
  1146. String rewritePrefix = atts.getValue ("rewritePrefix");
  1147. if (rewritePrefix != null)
  1148. rewritePrefix = normalizeURI (absolutize (rewritePrefix));
  1149. String systemIdStartString;
  1150. systemIdStartString = atts.getValue ("systemIdStartString");
  1151. if (systemIdStartString != null) {
  1152. systemIdStartString = normalizeURI (systemIdStartString);
  1153. // unmatchable <rewriteSystemId>, <delegateSystemId> elements
  1154. if (systemIdStartString.startsWith ("urn:publicid:")) {
  1155. error ("systemIdStartString is really a publicId!!");
  1156. return;
  1157. }
  1158. }
  1159. String uri = atts.getValue ("uri");
  1160. if (uri != null)
  1161. uri = normalizeURI (absolutize (uri));
  1162. String uriStartString;
  1163. uriStartString = atts.getValue ("uriStartString");
  1164. if (uriStartString != null) {
  1165. uriStartString = normalizeURI (uriStartString);
  1166. // unmatchable <rewriteURI>, <delegateURI> elements
  1167. if (uriStartString.startsWith ("urn:publicid:")) {
  1168. error ("uriStartString is really a publicId!!");
  1169. return;
  1170. }
  1171. }
  1172. // strictly speaking "group" and "catalog" shouldn't nest
  1173. // ... arbitrary restriction, no evident motivation
  1174. // FIXME stack "prefer" settings (two elements only!) and use
  1175. // them to populate different public mapping/delegation tables
  1176. if ("catalog" == local || "group" == local) {
  1177. String prefer = atts.getValue ("prefer");
  1178. if (prefer != null && !"public".equals (prefer)) {
  1179. if (!"system".equals (prefer)) {
  1180. error ("in <" + local + " ... prefer='...'>, "
  1181. + "assuming 'public'");
  1182. prefer = "public";
  1183. }
  1184. }
  1185. if (prefer != null) {
  1186. if ("catalog" == local) {
  1187. cat.hasPreference = true;
  1188. cat.usingPublic = "public".equals (prefer);
  1189. } else {
  1190. if (!cat.hasPreference || cat.usingPublic
  1191. != "public".equals (prefer)) {
  1192. fatal ("<group prefer=...> case not handled");
  1193. }
  1194. }
  1195. } else if ("group" == local && cat.hasPreference) {
  1196. fatal ("<group prefer=...> case not handled");
  1197. }
  1198. //
  1199. // PUBLIC ids: cleanly set up for id substitution
  1200. //
  1201. } else if ("public" == local) {
  1202. String publicId = atts.getValue ("publicId");
  1203. String value = null;
  1204. if (publicId == null || uri == null) {
  1205. error ("expecting <public publicId=... uri=.../>");
  1206. return;
  1207. }
  1208. publicId = normalizePublicId (true, publicId);
  1209. uri = nofrag (uri);
  1210. if (cat.publicIds == null)
  1211. cat.publicIds = new Hashtable ();
  1212. else
  1213. value = (String) cat.publicIds.get (publicId);
  1214. if (value != null) {
  1215. if (!value.equals (uri))
  1216. warn ("ignoring <public...> entry for " + publicId);
  1217. } else
  1218. cat.publicIds.put (publicId, uri);
  1219. } else if ("delegatePublic" == local) {
  1220. String publicIdStartString;
  1221. Object value = null;
  1222. publicIdStartString = atts.getValue ("publicIdStartString");
  1223. if (publicIdStartString == null || catalog == null) {
  1224. error ("expecting <delegatePublic "
  1225. + "publicIdStartString=... catalog=.../>");
  1226. return;
  1227. }
  1228. publicIdStartString = normalizePublicId (true,
  1229. publicIdStartString);
  1230. if (cat.publicDelegations == null)
  1231. cat.publicDelegations = new Hashtable ();
  1232. else
  1233. value = cat.publicDelegations.get (publicIdStartString);
  1234. if (value != null) {
  1235. if (!value.equals (catalog))
  1236. warn ("ignoring <delegatePublic...> entry for "
  1237. + uriStartString);
  1238. } else
  1239. cat.publicDelegations.put (publicIdStartString, catalog);
  1240. //
  1241. // SYSTEM ids: need substitution due to operational issues
  1242. //
  1243. } else if ("system" == local) {
  1244. String systemId = atts.getValue ("systemId");
  1245. String value = null;
  1246. if (systemId == null || uri == null) {
  1247. error ("expecting <system systemId=... uri=.../>");
  1248. return;
  1249. }
  1250. systemId = normalizeURI (systemId);
  1251. uri = nofrag (uri);
  1252. if (systemId.startsWith ("urn:publicid:")) {
  1253. error ("systemId is really a publicId!!");
  1254. return;
  1255. }
  1256. if (cat.systemIds == null) {
  1257. cat.systemIds = new Hashtable ();
  1258. if (unified)
  1259. cat.uris = cat.systemIds;
  1260. } else
  1261. value = (String) cat.systemIds.get (systemId);
  1262. if (value != null) {
  1263. if (!value.equals (uri))
  1264. warn ("ignoring <system...> entry for " + systemId);
  1265. } else
  1266. cat.systemIds.put (systemId, uri);
  1267. } else if ("rewriteSystem" == local) {
  1268. String value = null;
  1269. if (systemIdStartString == null || rewritePrefix == null
  1270. || systemIdStartString.length () == 0
  1271. || rewritePrefix.length () == 0
  1272. ) {
  1273. error ("expecting <rewriteSystem "
  1274. + "systemIdStartString=... rewritePrefix=.../>");
  1275. return;
  1276. }
  1277. if (cat.systemRewrites == null) {
  1278. cat.systemRewrites = new Hashtable ();
  1279. if (unified)
  1280. cat.uriRewrites = cat.systemRewrites;
  1281. } else
  1282. value = (String) cat.systemRewrites.get (
  1283. systemIdStartString);
  1284. if (value != null) {
  1285. if (!value.equals (rewritePrefix))
  1286. warn ("ignoring <rewriteSystem...> entry for "
  1287. + systemIdStartString);
  1288. } else
  1289. cat.systemRewrites.put (systemIdStartString,
  1290. rewritePrefix);
  1291. } else if ("delegateSystem" == local) {
  1292. Object value = null;
  1293. if (systemIdStartString == null || catalog == null) {
  1294. error ("expecting <delegateSystem "
  1295. + "systemIdStartString=... catalog=.../>");
  1296. return;
  1297. }
  1298. if (cat.systemDelegations == null) {
  1299. cat.systemDelegations = new Hashtable ();
  1300. if (unified)
  1301. cat.uriDelegations = cat.systemDelegations;
  1302. } else
  1303. value = cat.systemDelegations.get (systemIdStartString);
  1304. if (value != null) {
  1305. if (!value.equals (catalog))
  1306. warn ("ignoring <delegateSystem...> entry for "
  1307. + uriStartString);
  1308. } else
  1309. cat.systemDelegations.put (systemIdStartString, catalog);
  1310. //
  1311. // URI: just like "system" ID support, except that
  1312. // fragment IDs are disallowed in "system" elements.
  1313. //
  1314. } else if ("uri" == local) {
  1315. String name = atts.getValue ("name");
  1316. String value = null;
  1317. if (name == null || uri == null) {
  1318. error ("expecting <uri name=... uri=.../>");
  1319. return;
  1320. }
  1321. if (name.startsWith ("urn:publicid:")) {
  1322. error ("name is really a publicId!!");
  1323. return;
  1324. }
  1325. name = normalizeURI (name);
  1326. if (cat.uris == null) {
  1327. cat.uris = new Hashtable ();
  1328. if (unified)
  1329. cat.systemIds = cat.uris;
  1330. } else
  1331. value = (String) cat.uris.get (name);
  1332. if (value != null) {
  1333. if (!value.equals (uri))
  1334. warn ("ignoring <uri...> entry for " + name);
  1335. } else
  1336. cat.uris.put (name, uri);
  1337. } else if ("rewriteURI" == local) {
  1338. String value = null;
  1339. if (uriStartString == null || rewritePrefix == null
  1340. || uriStartString.length () == 0
  1341. || rewritePrefix.length () == 0
  1342. ) {
  1343. error ("expecting <rewriteURI "
  1344. + "uriStartString=... rewritePrefix=.../>");
  1345. return;
  1346. }
  1347. if (cat.uriRewrites == null) {
  1348. cat.uriRewrites = new Hashtable ();
  1349. if (unified)
  1350. cat.systemRewrites = cat.uriRewrites;
  1351. } else
  1352. value = (String) cat.uriRewrites.get (uriStartString);
  1353. if (value != null) {
  1354. if (!value.equals (rewritePrefix))
  1355. warn ("ignoring <rewriteURI...> entry for "
  1356. + uriStartString);
  1357. } else
  1358. cat.uriRewrites.put (uriStartString, rewritePrefix);
  1359. } else if ("delegateURI" == local) {
  1360. Object value = null;
  1361. if (uriStartString == null || catalog == null) {
  1362. error ("expecting <delegateURI "
  1363. + "uriStartString=... catalog=.../>");
  1364. return;
  1365. }
  1366. if (cat.uriDelegations == null) {
  1367. cat.uriDelegations = new Hashtable ();
  1368. if (unified)
  1369. cat.systemDelegations = cat.uriDelegations;
  1370. } else
  1371. value = cat.uriDelegations.get (uriStartString);
  1372. if (value != null) {
  1373. if (!value.equals (catalog))
  1374. warn ("ignoring <delegateURI...> entry for "
  1375. + uriStartString);
  1376. } else
  1377. cat.uriDelegations.put (uriStartString, catalog);
  1378. //
  1379. // NON-DELEGATING approach to modularity
  1380. //
  1381. } else if ("nextCatalog" == local) {
  1382. if (catalog == null) {
  1383. error ("expecting <nextCatalog catalog=.../>");
  1384. return;
  1385. }
  1386. if (cat.next == null)
  1387. cat.next = new Vector ();
  1388. cat.next.addElement (catalog);
  1389. //
  1390. // EXTENSIONS from appendix E
  1391. //
  1392. } else if ("doctype" == local) {
  1393. String name = atts.getValue ("name");
  1394. String value = null;
  1395. if (name == null || uri == null) {
  1396. error ("expecting <doctype name=... uri=.../>");
  1397. return;
  1398. }
  1399. name = normalizeURI (name);
  1400. if (cat.doctypes == null)
  1401. cat.doctypes = new Hashtable ();
  1402. else
  1403. value = (String) cat.doctypes.get (name);
  1404. if (value != null) {
  1405. if (!value.equals (uri))
  1406. warn ("ignoring <doctype...> entry for "
  1407. + uriStartString);
  1408. } else
  1409. cat.doctypes.put (name, uri);
  1410. //
  1411. // RESERVED ... ignore (like reserved attributes) but warn
  1412. //
  1413. } else {
  1414. warn ("ignoring unknown catalog element: " + local);
  1415. ignoreDepth++;
  1416. }
  1417. }
  1418. public void endElement (String uri, String local, String qName)
  1419. throws SAXException
  1420. {
  1421. if (ignoreDepth != 0)
  1422. ignoreDepth--;
  1423. else
  1424. bases.pop ();
  1425. }
  1426. }
  1427. }