Desktop tool for browsing account info from EVE-Online
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SAXOutputter.java 50KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439
  1. /*--
  2. $Id: SAXOutputter.java,v 1.40 2007/11/10 05:29:01 jhunter Exp $
  3. Copyright (C) 2000-2007 Jason Hunter & Brett McLaughlin.
  4. All rights reserved.
  5. Redistribution and use in source and binary forms, with or without
  6. modification, are permitted provided that the following conditions
  7. are met:
  8. 1. Redistributions of source code must retain the above copyright
  9. notice, this list of conditions, and the following disclaimer.
  10. 2. Redistributions in binary form must reproduce the above copyright
  11. notice, this list of conditions, and the disclaimer that follows
  12. these conditions in the documentation and/or other materials
  13. provided with the distribution.
  14. 3. The name "JDOM" must not be used to endorse or promote products
  15. derived from this software without prior written permission. For
  16. written permission, please contact <request_AT_jdom_DOT_org>.
  17. 4. Products derived from this software may not be called "JDOM", nor
  18. may "JDOM" appear in their name, without prior written permission
  19. from the JDOM Project Management <request_AT_jdom_DOT_org>.
  20. In addition, we request (but do not require) that you include in the
  21. end-user documentation provided with the redistribution and/or in the
  22. software itself an acknowledgement equivalent to the following:
  23. "This product includes software developed by the
  24. JDOM Project (http://www.jdom.org/)."
  25. Alternatively, the acknowledgment may be graphical using the logos
  26. available at http://www.jdom.org/images/logos.
  27. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  28. WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  29. OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  30. DISCLAIMED. IN NO EVENT SHALL THE JDOM AUTHORS OR THE PROJECT
  31. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  32. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  33. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  34. USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  35. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  36. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  37. OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  38. SUCH DAMAGE.
  39. This software consists of voluntary contributions made by many
  40. individuals on behalf of the JDOM Project and was originally
  41. created by Jason Hunter <jhunter_AT_jdom_DOT_org> and
  42. Brett McLaughlin <brett_AT_jdom_DOT_org>. For more information
  43. on the JDOM Project, please see <http://www.jdom.org/>.
  44. */
  45. package org.jdom.output;
  46. import java.io.*;
  47. import java.lang.reflect.*;
  48. import java.util.*;
  49. import org.jdom.*;
  50. import org.xml.sax.*;
  51. import org.xml.sax.ext.*;
  52. import org.xml.sax.helpers.*;
  53. /**
  54. * Outputs a JDOM document as a stream of SAX2 events.
  55. * <p>
  56. * Most ContentHandler callbacks are supported. Both
  57. * <code>ignorableWhitespace()</code> and <code>skippedEntity()</code> have not
  58. * been implemented. The <code>{@link JDOMLocator}</code> class returned by
  59. * <code>{@link #getLocator}</code> exposes the current node being operated
  60. * upon.
  61. * <p>
  62. * At this time, it is not possible to access notations and unparsed entity
  63. * references in a DTD from JDOM. Therefore, <code>DTDHandler</code> callbacks
  64. * have not been implemented yet.
  65. * <p>
  66. * The <code>ErrorHandler</code> callbacks have not been implemented, since
  67. * these are supposed to be invoked when the document is parsed and at this
  68. * point the document exists in memory and is known to have no errors. </p>
  69. *
  70. * @version $Revision: 1.40 $, $Date: 2007/11/10 05:29:01 $
  71. * @author Brett McLaughlin
  72. * @author Jason Hunter
  73. * @author Fred Trimble
  74. * @author Bradley S. Huffman
  75. */
  76. public class SAXOutputter {
  77. private static final String CVS_ID =
  78. "@(#) $RCSfile: SAXOutputter.java,v $ $Revision: 1.40 $ $Date: 2007/11/10 05:29:01 $ $Name: jdom_1_1 $";
  79. /** Shortcut for SAX namespaces core feature */
  80. private static final String NAMESPACES_SAX_FEATURE =
  81. "http://xml.org/sax/features/namespaces";
  82. /** Shortcut for SAX namespace-prefixes core feature */
  83. private static final String NS_PREFIXES_SAX_FEATURE =
  84. "http://xml.org/sax/features/namespace-prefixes";
  85. /** Shortcut for SAX validation core feature */
  86. private static final String VALIDATION_SAX_FEATURE =
  87. "http://xml.org/sax/features/validation";
  88. /** Shortcut for SAX-ext. lexical handler property */
  89. private static final String LEXICAL_HANDLER_SAX_PROPERTY =
  90. "http://xml.org/sax/properties/lexical-handler";
  91. /** Shortcut for SAX-ext. declaration handler property */
  92. private static final String DECL_HANDLER_SAX_PROPERTY =
  93. "http://xml.org/sax/properties/declaration-handler";
  94. /**
  95. * Shortcut for SAX-ext. lexical handler alternate property.
  96. * Although this property URI is not the one defined by the SAX
  97. * "standard", some parsers use it instead of the official one.
  98. */
  99. private static final String LEXICAL_HANDLER_ALT_PROPERTY =
  100. "http://xml.org/sax/handlers/LexicalHandler";
  101. /** Shortcut for SAX-ext. declaration handler alternate property */
  102. private static final String DECL_HANDLER_ALT_PROPERTY =
  103. "http://xml.org/sax/handlers/DeclHandler";
  104. /**
  105. * Array to map JDOM attribute type (as entry index) to SAX
  106. * attribute type names.
  107. */
  108. private static final String[] attrTypeToNameMap = new String[] {
  109. "CDATA", // Attribute.UNDEFINED_ATTRIBUTE, as per SAX 2.0 spec.
  110. "CDATA", // Attribute.CDATA_TYPE
  111. "ID", // Attribute.ID_TYPE
  112. "IDREF", // Attribute.IDREF_TYPE
  113. "IDREFS", // Attribute.IDREFS_TYPE
  114. "ENTITY", // Attribute.ENTITY_TYPE
  115. "ENTITIES", // Attribute.ENTITIES_TYPE
  116. "NMTOKEN", // Attribute.NMTOKEN_TYPE
  117. "NMTOKENS", // Attribute.NMTOKENS_TYPE
  118. "NOTATION", // Attribute.NOTATION_TYPE
  119. "NMTOKEN", // Attribute.ENUMERATED_TYPE, as per SAX 2.0 spec.
  120. };
  121. /** registered <code>ContentHandler</code> */
  122. private ContentHandler contentHandler;
  123. /** registered <code>ErrorHandler</code> */
  124. private ErrorHandler errorHandler;
  125. /** registered <code>DTDHandler</code> */
  126. private DTDHandler dtdHandler;
  127. /** registered <code>EntityResolver</code> */
  128. private EntityResolver entityResolver;
  129. /** registered <code>LexicalHandler</code> */
  130. private LexicalHandler lexicalHandler;
  131. /** registered <code>DeclHandler</code> */
  132. private DeclHandler declHandler;
  133. /**
  134. * Whether to report attribute namespace declarations as xmlns attributes.
  135. * Defaults to <code>false</code> as per SAX specifications.
  136. *
  137. * @see <a href="http://www.megginson.com/SAX/Java/namespaces.html">
  138. * SAX namespace specifications</a>
  139. */
  140. private boolean declareNamespaces = false;
  141. /**
  142. * Whether to report DTD events to DeclHandlers and LexicalHandlers.
  143. * Defaults to <code>true</code>.
  144. */
  145. private boolean reportDtdEvents = true;
  146. /**
  147. * A SAX Locator that points at the JDOM node currently being
  148. * outputted.
  149. */
  150. private JDOMLocator locator = null;
  151. /**
  152. * This will create a <code>SAXOutputter</code> without any
  153. * registered handler. The application is then responsible for
  154. * registering them using the <code>setXxxHandler()</code> methods.
  155. */
  156. public SAXOutputter() {
  157. }
  158. /**
  159. * This will create a <code>SAXOutputter</code> with the
  160. * specified <code>ContentHandler</code>.
  161. *
  162. * @param contentHandler contains <code>ContentHandler</code>
  163. * callback methods
  164. */
  165. public SAXOutputter(ContentHandler contentHandler) {
  166. this(contentHandler, null, null, null, null);
  167. }
  168. /**
  169. * This will create a <code>SAXOutputter</code> with the
  170. * specified SAX2 handlers. At this time, only <code>ContentHandler</code>
  171. * and <code>EntityResolver</code> are supported.
  172. *
  173. * @param contentHandler contains <code>ContentHandler</code>
  174. * callback methods
  175. * @param errorHandler contains <code>ErrorHandler</code> callback methods
  176. * @param dtdHandler contains <code>DTDHandler</code> callback methods
  177. * @param entityResolver contains <code>EntityResolver</code>
  178. * callback methods
  179. */
  180. public SAXOutputter(ContentHandler contentHandler,
  181. ErrorHandler errorHandler,
  182. DTDHandler dtdHandler,
  183. EntityResolver entityResolver) {
  184. this(contentHandler, errorHandler, dtdHandler, entityResolver, null);
  185. }
  186. /**
  187. * This will create a <code>SAXOutputter</code> with the
  188. * specified SAX2 handlers. At this time, only <code>ContentHandler</code>
  189. * and <code>EntityResolver</code> are supported.
  190. *
  191. * @param contentHandler contains <code>ContentHandler</code>
  192. * callback methods
  193. * @param errorHandler contains <code>ErrorHandler</code> callback methods
  194. * @param dtdHandler contains <code>DTDHandler</code> callback methods
  195. * @param entityResolver contains <code>EntityResolver</code>
  196. * callback methods
  197. * @param lexicalHandler contains <code>LexicalHandler</code> callbacks.
  198. */
  199. public SAXOutputter(ContentHandler contentHandler,
  200. ErrorHandler errorHandler,
  201. DTDHandler dtdHandler,
  202. EntityResolver entityResolver,
  203. LexicalHandler lexicalHandler) {
  204. this.contentHandler = contentHandler;
  205. this.errorHandler = errorHandler;
  206. this.dtdHandler = dtdHandler;
  207. this.entityResolver = entityResolver;
  208. this.lexicalHandler = lexicalHandler;
  209. }
  210. /**
  211. * This will set the <code>ContentHandler</code>.
  212. *
  213. * @param contentHandler contains <code>ContentHandler</code>
  214. * callback methods.
  215. */
  216. public void setContentHandler(ContentHandler contentHandler) {
  217. this.contentHandler = contentHandler;
  218. }
  219. /**
  220. * Returns the registered <code>ContentHandler</code>.
  221. *
  222. * @return the current <code>ContentHandler</code> or
  223. * <code>null</code> if none was registered.
  224. */
  225. public ContentHandler getContentHandler() {
  226. return this.contentHandler;
  227. }
  228. /**
  229. * This will set the <code>ErrorHandler</code>.
  230. *
  231. * @param errorHandler contains <code>ErrorHandler</code> callback methods.
  232. */
  233. public void setErrorHandler(ErrorHandler errorHandler) {
  234. this.errorHandler = errorHandler;
  235. }
  236. /**
  237. * Return the registered <code>ErrorHandler</code>.
  238. *
  239. * @return the current <code>ErrorHandler</code> or
  240. * <code>null</code> if none was registered.
  241. */
  242. public ErrorHandler getErrorHandler() {
  243. return this.errorHandler;
  244. }
  245. /**
  246. * This will set the <code>DTDHandler</code>.
  247. *
  248. * @param dtdHandler contains <code>DTDHandler</code> callback methods.
  249. */
  250. public void setDTDHandler(DTDHandler dtdHandler) {
  251. this.dtdHandler = dtdHandler;
  252. }
  253. /**
  254. * Return the registered <code>DTDHandler</code>.
  255. *
  256. * @return the current <code>DTDHandler</code> or
  257. * <code>null</code> if none was registered.
  258. */
  259. public DTDHandler getDTDHandler() {
  260. return this.dtdHandler;
  261. }
  262. /**
  263. * This will set the <code>EntityResolver</code>.
  264. *
  265. * @param entityResolver contains EntityResolver callback methods.
  266. */
  267. public void setEntityResolver(EntityResolver entityResolver) {
  268. this.entityResolver = entityResolver;
  269. }
  270. /**
  271. * Return the registered <code>EntityResolver</code>.
  272. *
  273. * @return the current <code>EntityResolver</code> or
  274. * <code>null</code> if none was registered.
  275. */
  276. public EntityResolver getEntityResolver() {
  277. return this.entityResolver;
  278. }
  279. /**
  280. * This will set the <code>LexicalHandler</code>.
  281. *
  282. * @param lexicalHandler contains lexical callback methods.
  283. */
  284. public void setLexicalHandler(LexicalHandler lexicalHandler) {
  285. this.lexicalHandler = lexicalHandler;
  286. }
  287. /**
  288. * Return the registered <code>LexicalHandler</code>.
  289. *
  290. * @return the current <code>LexicalHandler</code> or
  291. * <code>null</code> if none was registered.
  292. */
  293. public LexicalHandler getLexicalHandler() {
  294. return this.lexicalHandler;
  295. }
  296. /**
  297. * This will set the <code>DeclHandler</code>.
  298. *
  299. * @param declHandler contains declaration callback methods.
  300. */
  301. public void setDeclHandler(DeclHandler declHandler) {
  302. this.declHandler = declHandler;
  303. }
  304. /**
  305. * Return the registered <code>DeclHandler</code>.
  306. *
  307. * @return the current <code>DeclHandler</code> or
  308. * <code>null</code> if none was registered.
  309. */
  310. public DeclHandler getDeclHandler() {
  311. return this.declHandler;
  312. }
  313. /**
  314. * Returns whether attribute namespace declarations shall be reported as
  315. * "xmlns" attributes.
  316. *
  317. * @return whether attribute namespace declarations shall be reported as
  318. * "xmlns" attributes.
  319. */
  320. public boolean getReportNamespaceDeclarations() {
  321. return declareNamespaces;
  322. }
  323. /**
  324. * This will define whether attribute namespace declarations shall be
  325. * reported as "xmlns" attributes. This flag defaults to <code>false</code>
  326. * and behaves as the "namespace-prefixes" SAX core feature.
  327. *
  328. * @param declareNamespaces whether attribute namespace declarations
  329. * shall be reported as "xmlns" attributes.
  330. */
  331. public void setReportNamespaceDeclarations(boolean declareNamespaces) {
  332. this.declareNamespaces = declareNamespaces;
  333. }
  334. /**
  335. * Returns whether DTD events will be reported.
  336. *
  337. * @return whether DTD events will be reported
  338. */
  339. public boolean getReportDTDEvents() {
  340. return reportDtdEvents;
  341. }
  342. /**
  343. * This will define whether to report DTD events to SAX DeclHandlers
  344. * and LexicalHandlers if these handlers are registered and the
  345. * document to output includes a DocType declaration.
  346. *
  347. * @param reportDtdEvents whether to notify DTD events.
  348. */
  349. public void setReportDTDEvents(boolean reportDtdEvents) {
  350. this.reportDtdEvents = reportDtdEvents;
  351. }
  352. /**
  353. * This will set the state of a SAX feature.
  354. * <p>
  355. * All XMLReaders are required to support setting to true and to false.
  356. * </p>
  357. * <p>
  358. * SAXOutputter currently supports the following SAX core features:
  359. * <dl>
  360. * <dt><code>http://xml.org/sax/features/namespaces</code></dt>
  361. * <dd><strong>description:</strong> <code>true</code> indicates
  362. * namespace URIs and unprefixed local names for element and
  363. * attribute names will be available</dd>
  364. * <dd><strong>access:</strong> read/write, but always
  365. * <code>true</code>!</dd>
  366. * <dt><code>http://xml.org/sax/features/namespace-prefixes</code></dt>
  367. * <dd><strong>description:</strong> <code>true</code> indicates
  368. * XML 1.0 names (with prefixes) and attributes (including xmlns*
  369. * attributes) will be available</dd>
  370. * <dd><strong>access:</strong> read/write</dd>
  371. * <dt><code>http://xml.org/sax/features/validation</code></dt>
  372. * <dd><strong>description:</strong> controls whether SAXOutputter
  373. * is reporting DTD-related events; if <code>true</code>, the
  374. * DocType internal subset will be parsed to fire DTD events</dd>
  375. * <dd><strong>access:</strong> read/write, defaults to
  376. * <code>true</code></dd>
  377. * </dl>
  378. * </p>
  379. *
  380. * @param name <code>String</code> the feature name, which is a
  381. * fully-qualified URI.
  382. * @param value <code>boolean</code> the requested state of the
  383. * feature (true or false).
  384. *
  385. * @throws SAXNotRecognizedException when SAXOutputter does not
  386. * recognize the feature name.
  387. * @throws SAXNotSupportedException when SAXOutputter recognizes
  388. * the feature name but cannot set the requested value.
  389. */
  390. public void setFeature(String name, boolean value)
  391. throws SAXNotRecognizedException, SAXNotSupportedException {
  392. if (NS_PREFIXES_SAX_FEATURE.equals(name)) {
  393. // Namespace prefix declarations.
  394. this.setReportNamespaceDeclarations(value);
  395. }
  396. else {
  397. if (NAMESPACES_SAX_FEATURE.equals(name)) {
  398. if (value != true) {
  399. // Namespaces feature always supported by SAXOutputter.
  400. throw new SAXNotSupportedException(name);
  401. }
  402. // Else: true is OK!
  403. }
  404. else {
  405. if (VALIDATION_SAX_FEATURE.equals(name)) {
  406. // Report DTD events.
  407. this.setReportDTDEvents(value);
  408. }
  409. else {
  410. // Not a supported feature.
  411. throw new SAXNotRecognizedException(name);
  412. }
  413. }
  414. }
  415. }
  416. /**
  417. * This will look up the value of a SAX feature.
  418. *
  419. * @param name <code>String</code> the feature name, which is a
  420. * fully-qualified URI.
  421. * @return <code>boolean</code> the current state of the feature
  422. * (true or false).
  423. *
  424. * @throws SAXNotRecognizedException when SAXOutputter does not
  425. * recognize the feature name.
  426. * @throws SAXNotSupportedException when SAXOutputter recognizes
  427. * the feature name but determine its value at this time.
  428. */
  429. public boolean getFeature(String name)
  430. throws SAXNotRecognizedException, SAXNotSupportedException {
  431. if (NS_PREFIXES_SAX_FEATURE.equals(name)) {
  432. // Namespace prefix declarations.
  433. return (this.declareNamespaces);
  434. }
  435. else {
  436. if (NAMESPACES_SAX_FEATURE.equals(name)) {
  437. // Namespaces feature always supported by SAXOutputter.
  438. return (true);
  439. }
  440. else {
  441. if (VALIDATION_SAX_FEATURE.equals(name)) {
  442. // Report DTD events.
  443. return (this.reportDtdEvents);
  444. }
  445. else {
  446. // Not a supported feature.
  447. throw new SAXNotRecognizedException(name);
  448. }
  449. }
  450. }
  451. }
  452. /**
  453. * This will set the value of a SAX property.
  454. * This method is also the standard mechanism for setting extended
  455. * handlers.
  456. * <p>
  457. * SAXOutputter currently supports the following SAX properties:
  458. * <dl>
  459. * <dt><code>http://xml.org/sax/properties/lexical-handler</code></dt>
  460. * <dd><strong>data type:</strong>
  461. * <code>org.xml.sax.ext.LexicalHandler</code></dd>
  462. * <dd><strong>description:</strong> An optional extension handler for
  463. * lexical events like comments.</dd>
  464. * <dd><strong>access:</strong> read/write</dd>
  465. * <dt><code>http://xml.org/sax/properties/declaration-handler</code></dt>
  466. * <dd><strong>data type:</strong>
  467. * <code>org.xml.sax.ext.DeclHandler</code></dd>
  468. * <dd><strong>description:</strong> An optional extension handler for
  469. * DTD-related events other than notations and unparsed entities.</dd>
  470. * <dd><strong>access:</strong> read/write</dd>
  471. * </dl>
  472. * </p>
  473. *
  474. * @param name <code>String</code> the property name, which is a
  475. * fully-qualified URI.
  476. * @param value <code>Object</code> the requested value for the property.
  477. *
  478. * @throws SAXNotRecognizedException when SAXOutputter does not recognize
  479. * the property name.
  480. * @throws SAXNotSupportedException when SAXOutputter recognizes the
  481. * property name but cannot set the requested value.
  482. */
  483. public void setProperty(String name, Object value)
  484. throws SAXNotRecognizedException, SAXNotSupportedException {
  485. if ((LEXICAL_HANDLER_SAX_PROPERTY.equals(name)) ||
  486. (LEXICAL_HANDLER_ALT_PROPERTY.equals(name))) {
  487. this.setLexicalHandler((LexicalHandler)value);
  488. }
  489. else {
  490. if ((DECL_HANDLER_SAX_PROPERTY.equals(name)) ||
  491. (DECL_HANDLER_ALT_PROPERTY.equals(name))) {
  492. this.setDeclHandler((DeclHandler)value);
  493. }
  494. else {
  495. throw new SAXNotRecognizedException(name);
  496. }
  497. }
  498. }
  499. /**
  500. * This will look up the value of a SAX property.
  501. *
  502. * @param name <code>String</code> the property name, which is a
  503. * fully-qualified URI.
  504. * @return <code>Object</code> the current value of the property.
  505. *
  506. * @throws SAXNotRecognizedException when SAXOutputter does not recognize
  507. * the property name.
  508. * @throws SAXNotSupportedException when SAXOutputter recognizes the
  509. * property name but cannot determine its value at this time.
  510. */
  511. public Object getProperty(String name)
  512. throws SAXNotRecognizedException, SAXNotSupportedException {
  513. if ((LEXICAL_HANDLER_SAX_PROPERTY.equals(name)) ||
  514. (LEXICAL_HANDLER_ALT_PROPERTY.equals(name))) {
  515. return this.getLexicalHandler();
  516. }
  517. else {
  518. if ((DECL_HANDLER_SAX_PROPERTY.equals(name)) ||
  519. (DECL_HANDLER_ALT_PROPERTY.equals(name))) {
  520. return this.getDeclHandler();
  521. }
  522. else {
  523. throw new SAXNotRecognizedException(name);
  524. }
  525. }
  526. }
  527. /**
  528. * This will output the <code>JDOM Document</code>, firing off the
  529. * SAX events that have been registered.
  530. *
  531. * @param document <code>JDOM Document</code> to output.
  532. *
  533. * @throws JDOMException if any error occurred.
  534. */
  535. public void output(Document document) throws JDOMException {
  536. if (document == null) {
  537. return;
  538. }
  539. // contentHandler.setDocumentLocator()
  540. documentLocator(document);
  541. // contentHandler.startDocument()
  542. startDocument();
  543. // Fire DTD events
  544. if (this.reportDtdEvents) {
  545. dtdEvents(document);
  546. }
  547. // Handle root element, as well as any root level
  548. // processing instructions and comments
  549. Iterator i = document.getContent().iterator();
  550. while (i.hasNext()) {
  551. Object obj = i.next();
  552. // update locator
  553. locator.setNode(obj);
  554. if (obj instanceof Element) {
  555. // process root element and its content
  556. element(document.getRootElement(), new NamespaceStack());
  557. }
  558. else if (obj instanceof ProcessingInstruction) {
  559. // contentHandler.processingInstruction()
  560. processingInstruction((ProcessingInstruction) obj);
  561. }
  562. else if (obj instanceof Comment) {
  563. // lexicalHandler.comment()
  564. comment(((Comment) obj).getText());
  565. }
  566. }
  567. // contentHandler.endDocument()
  568. endDocument();
  569. }
  570. /**
  571. * This will output a list of JDOM nodes as a document, firing
  572. * off the SAX events that have been registered.
  573. * <p>
  574. * <strong>Warning</strong>: This method may output ill-formed XML
  575. * documents if the list contains top-level objects that are not
  576. * legal at the document level (e.g. Text or CDATA nodes, multiple
  577. * Element nodes, etc.). Thus, it should only be used to output
  578. * document portions towards ContentHandlers capable of accepting
  579. * such ill-formed documents (such as XSLT processors).</p>
  580. *
  581. * @param nodes <code>List</code> of JDOM nodes to output.
  582. *
  583. * @throws JDOMException if any error occurred.
  584. *
  585. * @see #output(org.jdom.Document)
  586. */
  587. public void output(List nodes) throws JDOMException {
  588. if ((nodes == null) || (nodes.size() == 0)) {
  589. return;
  590. }
  591. // contentHandler.setDocumentLocator()
  592. documentLocator(null);
  593. // contentHandler.startDocument()
  594. startDocument();
  595. // Process node list.
  596. elementContent(nodes, new NamespaceStack());
  597. // contentHandler.endDocument()
  598. endDocument();
  599. }
  600. /**
  601. * This will output a single JDOM element as a document, firing
  602. * off the SAX events that have been registered.
  603. *
  604. * @param node the <code>Element</code> node to output.
  605. *
  606. * @throws JDOMException if any error occurred.
  607. */
  608. public void output(Element node) throws JDOMException {
  609. if (node == null) {
  610. return;
  611. }
  612. // contentHandler.setDocumentLocator()
  613. documentLocator(null);
  614. // contentHandler.startDocument()
  615. startDocument();
  616. // Output node.
  617. elementContent(node, new NamespaceStack());
  618. // contentHandler.endDocument()
  619. endDocument();
  620. }
  621. /**
  622. * This will output a list of JDOM nodes as a fragment of an XML
  623. * document, firing off the SAX events that have been registered.
  624. * <p>
  625. * <strong>Warning</strong>: This method does not call the
  626. * {@link ContentHandler#setDocumentLocator},
  627. * {@link ContentHandler#startDocument} and
  628. * {@link ContentHandler#endDocument} callbacks on the
  629. * {@link #setContentHandler ContentHandler}. The user shall
  630. * invoke these methods directly prior/after outputting the
  631. * document fragments.</p>
  632. *
  633. * @param nodes <code>List</code> of JDOM nodes to output.
  634. *
  635. * @throws JDOMException if any error occurred.
  636. *
  637. * @see #outputFragment(org.jdom.Content)
  638. */
  639. public void outputFragment(List nodes) throws JDOMException {
  640. if ((nodes == null) || (nodes.size() == 0)) {
  641. return;
  642. }
  643. // Output node list as a document fragment.
  644. elementContent(nodes, new NamespaceStack());
  645. }
  646. /**
  647. * This will output a single JDOM nodes as a fragment of an XML
  648. * document, firing off the SAX events that have been registered.
  649. * <p>
  650. * <strong>Warning</strong>: This method does not call the
  651. * {@link ContentHandler#setDocumentLocator},
  652. * {@link ContentHandler#startDocument} and
  653. * {@link ContentHandler#endDocument} callbacks on the
  654. * {@link #setContentHandler ContentHandler}. The user shall
  655. * invoke these methods directly prior/after outputting the
  656. * document fragments.</p>
  657. *
  658. * @param node the <code>Content</code> node to output.
  659. *
  660. * @throws JDOMException if any error occurred.
  661. *
  662. * @see #outputFragment(java.util.List)
  663. */
  664. public void outputFragment(Content node) throws JDOMException {
  665. if (node == null) {
  666. return;
  667. }
  668. // Output single node as a document fragment.
  669. elementContent(node, new NamespaceStack());
  670. }
  671. /**
  672. * This parses a DTD declaration to fire the related events towards
  673. * the registered handlers.
  674. *
  675. * @param document <code>JDOM Document</code> the DocType is to
  676. * process.
  677. */
  678. private void dtdEvents(Document document) throws JDOMException {
  679. DocType docType = document.getDocType();
  680. // Fire DTD-related events only if handlers have been registered.
  681. if ((docType != null) &&
  682. ((dtdHandler != null) || (declHandler != null))) {
  683. // Build a dummy XML document that only references the DTD...
  684. String dtdDoc = new XMLOutputter().outputString(docType);
  685. try {
  686. // And parse it to fire DTD events.
  687. createDTDParser().parse(new InputSource(
  688. new StringReader(dtdDoc)));
  689. // We should never reach this point as the document is
  690. // ill-formed; it does not have any root element.
  691. }
  692. catch (SAXParseException e) {
  693. // Expected exception: There's no root element in document.
  694. }
  695. catch (SAXException e) {
  696. throw new JDOMException("DTD parsing error", e);
  697. }
  698. catch (IOException e) {
  699. throw new JDOMException("DTD parsing error", e);
  700. }
  701. }
  702. }
  703. /**
  704. * <p>
  705. * This method tells you the line of the XML file being parsed.
  706. * For an in-memory document, it's meaningless. The location
  707. * is only valid for the current parsing lifecycle, but
  708. * the document has already been parsed. Therefore, it returns
  709. * -1 for both line and column numbers.
  710. * </p>
  711. *
  712. * @param document JDOM <code>Document</code>.
  713. */
  714. private void documentLocator(Document document) {
  715. locator = new JDOMLocator();
  716. String publicID = null;
  717. String systemID = null;
  718. if (document != null) {
  719. DocType docType = document.getDocType();
  720. if (docType != null) {
  721. publicID = docType.getPublicID();
  722. systemID = docType.getSystemID();
  723. }
  724. }
  725. locator.setPublicId(publicID);
  726. locator.setSystemId(systemID);
  727. locator.setLineNumber(-1);
  728. locator.setColumnNumber(-1);
  729. contentHandler.setDocumentLocator(locator);
  730. }
  731. /**
  732. * <p>
  733. * This method is always the second method of all callbacks in
  734. * all handlers to be invoked (setDocumentLocator is always first).
  735. * </p>
  736. */
  737. private void startDocument() throws JDOMException {
  738. try {
  739. contentHandler.startDocument();
  740. }
  741. catch (SAXException se) {
  742. throw new JDOMException("Exception in startDocument", se);
  743. }
  744. }
  745. /**
  746. * <p>
  747. * Always the last method of all callbacks in all handlers
  748. * to be invoked.
  749. * </p>
  750. */
  751. private void endDocument() throws JDOMException {
  752. try {
  753. contentHandler.endDocument();
  754. // reset locator
  755. locator = null;
  756. }
  757. catch (SAXException se) {
  758. throw new JDOMException("Exception in endDocument", se);
  759. }
  760. }
  761. /**
  762. * <p>
  763. * This will invoke the <code>ContentHandler.processingInstruction</code>
  764. * callback when a processing instruction is encountered.
  765. * </p>
  766. *
  767. * @param pi <code>ProcessingInstruction</code> containing target and data.
  768. */
  769. private void processingInstruction(ProcessingInstruction pi)
  770. throws JDOMException {
  771. if (pi != null) {
  772. String target = pi.getTarget();
  773. String data = pi.getData();
  774. try {
  775. contentHandler.processingInstruction(target, data);
  776. }
  777. catch (SAXException se) {
  778. throw new JDOMException(
  779. "Exception in processingInstruction", se);
  780. }
  781. }
  782. }
  783. /**
  784. * <p>
  785. * This will recursively invoke all of the callbacks for a particular
  786. * element.
  787. * </p>
  788. *
  789. * @param element <code>Element</code> used in callbacks.
  790. * @param namespaces <code>List</code> stack of Namespaces in scope.
  791. */
  792. private void element(Element element, NamespaceStack namespaces)
  793. throws JDOMException {
  794. // used to check endPrefixMapping
  795. int previouslyDeclaredNamespaces = namespaces.size();
  796. // contentHandler.startPrefixMapping()
  797. Attributes nsAtts = startPrefixMapping(element, namespaces);
  798. // contentHandler.startElement()
  799. startElement(element, nsAtts);
  800. // handle content in the element
  801. elementContent(element.getContent(), namespaces);
  802. // update locator
  803. if (locator != null) {
  804. locator.setNode(element);
  805. }
  806. // contentHandler.endElement()
  807. endElement(element);
  808. // contentHandler.endPrefixMapping()
  809. endPrefixMapping(namespaces, previouslyDeclaredNamespaces);
  810. }
  811. /**
  812. * <p>
  813. * This will invoke the <code>ContentHandler.startPrefixMapping</code>
  814. * callback
  815. * when a new namespace is encountered in the <code>Document</code>.
  816. * </p>
  817. *
  818. * @param element <code>Element</code> used in callbacks.
  819. * @param namespaces <code>List</code> stack of Namespaces in scope.
  820. *
  821. * @return <code>Attributes</code> declaring the namespaces local to
  822. * <code>element</code> or <code>null</code>.
  823. */
  824. private Attributes startPrefixMapping(Element element,
  825. NamespaceStack namespaces)
  826. throws JDOMException {
  827. AttributesImpl nsAtts = null; // The namespaces as xmlns attributes
  828. Namespace ns = element.getNamespace();
  829. if (ns != Namespace.XML_NAMESPACE) {
  830. String prefix = ns.getPrefix();
  831. String uri = namespaces.getURI(prefix);
  832. if (!ns.getURI().equals(uri)) {
  833. namespaces.push(ns);
  834. nsAtts = this.addNsAttribute(nsAtts, ns);
  835. try {
  836. contentHandler.startPrefixMapping(prefix, ns.getURI());
  837. }
  838. catch (SAXException se) {
  839. throw new JDOMException(
  840. "Exception in startPrefixMapping", se);
  841. }
  842. }
  843. }
  844. // Fire additional namespace declarations
  845. List additionalNamespaces = element.getAdditionalNamespaces();
  846. if (additionalNamespaces != null) {
  847. Iterator itr = additionalNamespaces.iterator();
  848. while (itr.hasNext()) {
  849. ns = (Namespace)itr.next();
  850. String prefix = ns.getPrefix();
  851. String uri = namespaces.getURI(prefix);
  852. if (!ns.getURI().equals(uri)) {
  853. namespaces.push(ns);
  854. nsAtts = this.addNsAttribute(nsAtts, ns);
  855. try {
  856. contentHandler.startPrefixMapping(prefix, ns.getURI());
  857. }
  858. catch (SAXException se) {
  859. throw new JDOMException(
  860. "Exception in startPrefixMapping", se);
  861. }
  862. }
  863. }
  864. }
  865. return nsAtts;
  866. }
  867. /**
  868. * <p>
  869. * This will invoke the <code>endPrefixMapping</code> callback in the
  870. * <code>ContentHandler</code> when a namespace is goes out of scope
  871. * in the <code>Document</code>.
  872. * </p>
  873. *
  874. * @param namespaces <code>List</code> stack of Namespaces in scope.
  875. * @param previouslyDeclaredNamespaces number of previously declared
  876. * namespaces
  877. */
  878. private void endPrefixMapping(NamespaceStack namespaces,
  879. int previouslyDeclaredNamespaces)
  880. throws JDOMException {
  881. while (namespaces.size() > previouslyDeclaredNamespaces) {
  882. String prefix = namespaces.pop();
  883. try {
  884. contentHandler.endPrefixMapping(prefix);
  885. }
  886. catch (SAXException se) {
  887. throw new JDOMException("Exception in endPrefixMapping", se);
  888. }
  889. }
  890. }
  891. /**
  892. * <p>
  893. * This will invoke the <code>startElement</code> callback
  894. * in the <code>ContentHandler</code>.
  895. * </p>
  896. *
  897. * @param element <code>Element</code> used in callbacks.
  898. * @param nsAtts <code>List</code> of namespaces to declare with
  899. * the element or <code>null</code>.
  900. */
  901. private void startElement(Element element, Attributes nsAtts)
  902. throws JDOMException {
  903. String namespaceURI = element.getNamespaceURI();
  904. String localName = element.getName();
  905. String rawName = element.getQualifiedName();
  906. // Allocate attribute list.
  907. AttributesImpl atts = (nsAtts != null)?
  908. new AttributesImpl(nsAtts): new AttributesImpl();
  909. List attributes = element.getAttributes();
  910. Iterator i = attributes.iterator();
  911. while (i.hasNext()) {
  912. Attribute a = (Attribute) i.next();
  913. atts.addAttribute(a.getNamespaceURI(),
  914. a.getName(),
  915. a.getQualifiedName(),
  916. getAttributeTypeName(a.getAttributeType()),
  917. a.getValue());
  918. }
  919. try {
  920. contentHandler.startElement(namespaceURI, localName, rawName, atts);
  921. }
  922. catch (SAXException se) {
  923. throw new JDOMException("Exception in startElement", se);
  924. }
  925. }
  926. /**
  927. * <p>
  928. * This will invoke the <code>endElement</code> callback
  929. * in the <code>ContentHandler</code>.
  930. * </p>
  931. *
  932. * @param element <code>Element</code> used in callbacks.
  933. */
  934. private void endElement(Element element) throws JDOMException {
  935. String namespaceURI = element.getNamespaceURI();
  936. String localName = element.getName();
  937. String rawName = element.getQualifiedName();
  938. try {
  939. contentHandler.endElement(namespaceURI, localName, rawName);
  940. }
  941. catch (SAXException se) {
  942. throw new JDOMException("Exception in endElement", se);
  943. }
  944. }
  945. /**
  946. * <p>
  947. * This will invoke the callbacks for the content of an element.
  948. * </p>
  949. *
  950. * @param content element content as a <code>List</code> of nodes.
  951. * @param namespaces <code>List</code> stack of Namespaces in scope.
  952. */
  953. private void elementContent(List content, NamespaceStack namespaces)
  954. throws JDOMException {
  955. for (Iterator i=content.iterator(); i.hasNext(); ) {
  956. Object obj = i.next();
  957. if (obj instanceof Content) {
  958. this.elementContent((Content)obj, namespaces);
  959. }
  960. else {
  961. // Not a valid element child. This could happen with
  962. // application-provided lists which may contain non
  963. // JDOM objects.
  964. handleError(new JDOMException(
  965. "Invalid element content: " + obj));
  966. }
  967. }
  968. }
  969. /**
  970. * <p>
  971. * This will invoke the callbacks for the content of an element.
  972. * </p>
  973. *
  974. * @param node a <code>Content</code> node.
  975. * @param namespaces <code>List</code> stack of Namespaces in scope.
  976. */
  977. private void elementContent(Content node, NamespaceStack namespaces)
  978. throws JDOMException {
  979. // update locator
  980. if (locator != null) {
  981. locator.setNode(node);
  982. }
  983. if (node instanceof Element) {
  984. element((Element) node, namespaces);
  985. }
  986. else if (node instanceof CDATA) {
  987. cdata(((CDATA) node).getText());
  988. }
  989. else if (node instanceof Text) {
  990. // contentHandler.characters()
  991. characters(((Text) node).getText());
  992. }
  993. else if (node instanceof ProcessingInstruction) {
  994. // contentHandler.processingInstruction()
  995. processingInstruction((ProcessingInstruction) node);
  996. }
  997. else if (node instanceof Comment) {
  998. // lexicalHandler.comment()
  999. comment(((Comment) node).getText());
  1000. }
  1001. else if (node instanceof EntityRef) {
  1002. // contentHandler.skippedEntity()
  1003. entityRef((EntityRef) node);
  1004. }
  1005. else {
  1006. // Not a valid element child. This could happen with
  1007. // application-provided lists which may contain non
  1008. // JDOM objects.
  1009. handleError(new JDOMException("Invalid element content: " + node));
  1010. }
  1011. }
  1012. /**
  1013. * <p>
  1014. * This will be called for each chunk of CDATA section encountered.
  1015. * </p>
  1016. *
  1017. * @param cdataText all text in the CDATA section, including whitespace.
  1018. */
  1019. private void cdata(String cdataText) throws JDOMException {
  1020. try {
  1021. if (lexicalHandler != null) {
  1022. lexicalHandler.startCDATA();
  1023. characters(cdataText);
  1024. lexicalHandler.endCDATA();
  1025. }
  1026. else {
  1027. characters(cdataText);
  1028. }
  1029. }
  1030. catch (SAXException se) {
  1031. throw new JDOMException("Exception in CDATA", se);
  1032. }
  1033. }
  1034. /**
  1035. * <p>
  1036. * This will be called for each chunk of character data encountered.
  1037. * </p>
  1038. *
  1039. * @param elementText all text in an element, including whitespace.
  1040. */
  1041. private void characters(String elementText) throws JDOMException {
  1042. char[] c = elementText.toCharArray();
  1043. try {
  1044. contentHandler.characters(c, 0, c.length);
  1045. }
  1046. catch (SAXException se) {
  1047. throw new JDOMException("Exception in characters", se);
  1048. }
  1049. }
  1050. /**
  1051. * <p>
  1052. * This will be called for each chunk of comment data encontered.
  1053. * </p>
  1054. *
  1055. * @param commentText all text in a comment, including whitespace.
  1056. */
  1057. private void comment(String commentText) throws JDOMException {
  1058. if (lexicalHandler != null) {
  1059. char[] c = commentText.toCharArray();
  1060. try {
  1061. lexicalHandler.comment(c, 0, c.length);
  1062. } catch (SAXException se) {
  1063. throw new JDOMException("Exception in comment", se);
  1064. }
  1065. }
  1066. }
  1067. /**
  1068. * <p>
  1069. * This will invoke the <code>ContentHandler.skippedEntity</code>
  1070. * callback when an entity reference is encountered.
  1071. * </p>
  1072. *
  1073. * @param entity <code>EntityRef</code>.
  1074. */
  1075. private void entityRef(EntityRef entity) throws JDOMException {
  1076. if (entity != null) {
  1077. try {
  1078. // No need to worry about appending a '%' character as
  1079. // we do not support parameter entities
  1080. contentHandler.skippedEntity(entity.getName());
  1081. }
  1082. catch (SAXException se) {
  1083. throw new JDOMException("Exception in entityRef", se);
  1084. }
  1085. }
  1086. }
  1087. /**
  1088. * <p>
  1089. * Appends a namespace declaration in the form of a xmlns attribute to
  1090. * an attribute list, crerating this latter if needed.
  1091. * </p>
  1092. *
  1093. * @param atts <code>AttributeImpl</code> where to add the attribute.
  1094. * @param ns <code>Namespace</code> the namespace to declare.
  1095. *
  1096. * @return <code>AttributeImpl</code> the updated attribute list.
  1097. */
  1098. private AttributesImpl addNsAttribute(AttributesImpl atts, Namespace ns) {
  1099. if (this.declareNamespaces) {
  1100. if (atts == null) {
  1101. atts = new AttributesImpl();
  1102. }
  1103. String prefix = ns.getPrefix();
  1104. if (prefix.equals("")) {
  1105. atts.addAttribute("", // namespace
  1106. "", // local name
  1107. "xmlns", // qualified name
  1108. "CDATA", // type
  1109. ns.getURI()); // value
  1110. }
  1111. else {
  1112. atts.addAttribute("", // namespace
  1113. "", // local name
  1114. "xmlns:" + ns.getPrefix(), // qualified name
  1115. "CDATA", // type
  1116. ns.getURI()); // value
  1117. }
  1118. }
  1119. return atts;
  1120. }
  1121. /**
  1122. * <p>
  1123. * Returns the SAX 2.0 attribute type string from the type of
  1124. * a JDOM Attribute.
  1125. * </p>
  1126. *
  1127. * @param type <code>int</code> the type of the JDOM attribute.
  1128. *
  1129. * @return <code>String</code> the SAX 2.0 attribute type string.
  1130. *
  1131. * @see org.jdom.Attribute#getAttributeType
  1132. * @see org.xml.sax.Attributes#getType
  1133. */
  1134. private static String getAttributeTypeName(int type) {
  1135. if ((type < 0) || (type >= attrTypeToNameMap.length)) {
  1136. type = Attribute.UNDECLARED_TYPE;
  1137. }
  1138. return attrTypeToNameMap[type];
  1139. }
  1140. /**
  1141. * <p>
  1142. * Notifies the registered {@link ErrorHandler SAX error handler}
  1143. * (if any) of an input processing error. The error handler can
  1144. * choose to absorb the error and let the processing continue.
  1145. * </p>
  1146. *
  1147. * @param exception <code>JDOMException</code> containing the
  1148. * error information; will be wrapped in a
  1149. * {@link SAXParseException} when reported to
  1150. * the SAX error handler.
  1151. *
  1152. * @throws JDOMException if no error handler has been registered
  1153. * or if the error handler fired a
  1154. * {@link SAXException}.
  1155. */
  1156. private void handleError(JDOMException exception) throws JDOMException {
  1157. if (errorHandler != null) {
  1158. try {
  1159. errorHandler.error(new SAXParseException(
  1160. exception.getMessage(), null, exception));
  1161. }
  1162. catch (SAXException se) {
  1163. if (se.getException() instanceof JDOMException) {
  1164. throw (JDOMException)(se.getException());
  1165. }
  1166. else {
  1167. throw new JDOMException(se.getMessage(), se);
  1168. }
  1169. }
  1170. }
  1171. else {
  1172. throw exception;
  1173. }
  1174. }
  1175. /**
  1176. * <p>
  1177. * Creates a SAX XMLReader.
  1178. * </p>
  1179. *
  1180. * @return <code>XMLReader</code> a SAX2 parser.
  1181. *
  1182. * @throws Exception if no parser can be created.
  1183. */
  1184. protected XMLReader createParser() throws Exception {
  1185. XMLReader parser = null;
  1186. // Try using JAXP...
  1187. // Note we need JAXP 1.1, and if JAXP 1.0 is all that's
  1188. // available then the getXMLReader call fails and we skip
  1189. // to the hard coded default parser
  1190. try {
  1191. Class factoryClass =
  1192. Class.forName("javax.xml.parsers.SAXParserFactory");
  1193. // factory = SAXParserFactory.newInstance();
  1194. Method newParserInstance =
  1195. factoryClass.getMethod("newInstance", null);
  1196. Object factory = newParserInstance.invoke(null, null);
  1197. // jaxpParser = factory.newSAXParser();
  1198. Method newSAXParser = factoryClass.getMethod("newSAXParser", null);
  1199. Object jaxpParser = newSAXParser.invoke(factory, null);
  1200. // parser = jaxpParser.getXMLReader();
  1201. Class parserClass = jaxpParser.getClass();
  1202. Method getXMLReader =
  1203. parserClass.getMethod("getXMLReader", null);
  1204. parser = (XMLReader)getXMLReader.invoke(jaxpParser, null);
  1205. } catch (ClassNotFoundException e) {
  1206. //e.printStackTrace();
  1207. } catch (InvocationTargetException e) {
  1208. //e.printStackTrace();
  1209. } catch (NoSuchMethodException e) {
  1210. //e.printStackTrace();
  1211. } catch (IllegalAccessException e) {
  1212. //e.printStackTrace();
  1213. }
  1214. // Check to see if we got a parser yet, if not, try to use a
  1215. // hard coded default
  1216. if (parser == null) {
  1217. parser = XMLReaderFactory.createXMLReader(
  1218. "org.apache.xerces.parsers.SAXParser");
  1219. }
  1220. return parser;
  1221. }
  1222. /**
  1223. * <p>
  1224. * This will create a SAX XMLReader capable of parsing a DTD and
  1225. * configure it so that the DTD parsing events are routed to the
  1226. * handlers registered onto this SAXOutputter.
  1227. * </p>
  1228. *
  1229. * @return <code>XMLReader</code> a SAX2 parser.
  1230. *
  1231. * @throws JDOMException if no parser can be created.
  1232. */
  1233. private XMLReader createDTDParser() throws JDOMException {
  1234. XMLReader parser = null;
  1235. // Get a parser instance
  1236. try
  1237. {
  1238. parser = createParser();
  1239. }
  1240. catch (Exception ex1) {
  1241. throw new JDOMException("Error in SAX parser allocation", ex1);
  1242. }
  1243. // Register handlers
  1244. if (this.getDTDHandler() != null) {
  1245. parser.setDTDHandler(this.getDTDHandler());
  1246. }
  1247. if (this.getEntityResolver() != null) {
  1248. parser.setEntityResolver(this.getEntityResolver());
  1249. }
  1250. if (this.getLexicalHandler() != null) {
  1251. try {
  1252. parser.setProperty(LEXICAL_HANDLER_SAX_PROPERTY,
  1253. this.getLexicalHandler());
  1254. }
  1255. catch (SAXException ex1) {
  1256. try {
  1257. parser.setProperty(LEXICAL_HANDLER_ALT_PROPERTY,
  1258. this.getLexicalHandler());
  1259. } catch (SAXException ex2) {
  1260. // Forget it!
  1261. }
  1262. }
  1263. }
  1264. if (this.getDeclHandler() != null) {
  1265. try {
  1266. parser.setProperty(DECL_HANDLER_SAX_PROPERTY,
  1267. this.getDeclHandler());
  1268. }
  1269. catch (SAXException ex1) {
  1270. try {
  1271. parser.setProperty(DECL_HANDLER_ALT_PROPERTY,
  1272. this.getDeclHandler());
  1273. } catch (SAXException ex2) {
  1274. // Forget it!
  1275. }
  1276. }
  1277. }
  1278. // Absorb errors as much as possible, per Laurent
  1279. parser.setErrorHandler(new DefaultHandler());
  1280. return parser;
  1281. }
  1282. /**
  1283. * Returns a JDOMLocator object referencing the node currently
  1284. * being processed by this outputter. The returned object is a
  1285. * snapshot of the location information and can thus safely be
  1286. * memorized for later use.
  1287. * <p>
  1288. * This method allows direct access to the location information
  1289. * maintained by SAXOutputter without requiring to implement
  1290. * <code>XMLFilter</code>. (In SAX, locators are only available
  1291. * though the <code>ContentHandler</code> interface).</p>
  1292. * <p>
  1293. * Note that location information is only available while
  1294. * SAXOutputter is outputting nodes. Hence this method should
  1295. * only be used by objects taking part in the output processing
  1296. * such as <code>ErrorHandler</code>s.
  1297. *
  1298. * @return a JDOMLocator object referencing the node currently
  1299. * being processed or <code>null</code> if no output
  1300. * operation is being performed.
  1301. */
  1302. public JDOMLocator getLocator() {
  1303. return (locator != null)? new JDOMLocator(locator): null;
  1304. }
  1305. }