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.

Driver.java 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. /*
  2. * $Id$
  3. * ============================================================================
  4. * The Apache Software License, Version 1.1
  5. * ============================================================================
  6. *
  7. * Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
  8. *
  9. * Redistribution and use in source and binary forms, with or without modifica-
  10. * tion, are permitted provided that the following conditions are met:
  11. *
  12. * 1. Redistributions of source code must retain the above copyright notice,
  13. * this list of conditions and the following disclaimer.
  14. *
  15. * 2. Redistributions in binary form must reproduce the above copyright notice,
  16. * this list of conditions and the following disclaimer in the documentation
  17. * and/or other materials provided with the distribution.
  18. *
  19. * 3. The end-user documentation included with the redistribution, if any, must
  20. * include the following acknowledgment: "This product includes software
  21. * developed by the Apache Software Foundation (http://www.apache.org/)."
  22. * Alternately, this acknowledgment may appear in the software itself, if
  23. * and wherever such third-party acknowledgments normally appear.
  24. *
  25. * 4. The names "FOP" and "Apache Software Foundation" must not be used to
  26. * endorse or promote products derived from this software without prior
  27. * written permission. For written permission, please contact
  28. * apache@apache.org.
  29. *
  30. * 5. Products derived from this software may not be called "Apache", nor may
  31. * "Apache" appear in their name, without prior written permission of the
  32. * Apache Software Foundation.
  33. *
  34. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  35. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  36. * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  37. * APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  38. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
  39. * DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  40. * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  41. * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  42. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  43. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  44. * ============================================================================
  45. *
  46. * This software consists of voluntary contributions made by many individuals
  47. * on behalf of the Apache Software Foundation and was originally created by
  48. * James Tauber <jtauber@jtauber.com>. For more information on the Apache
  49. * Software Foundation, please see <http://www.apache.org/>.
  50. */
  51. package org.apache.fop.apps;
  52. // FOP
  53. import org.apache.fop.fo.ElementMapping;
  54. import org.apache.fop.fo.FOTreeBuilder;
  55. import org.apache.fop.fo.FOUserAgent;
  56. import org.apache.fop.render.Renderer;
  57. import org.apache.fop.tools.DocumentInputSource;
  58. import org.apache.fop.tools.DocumentReader;
  59. // Avalon
  60. import org.apache.avalon.framework.logger.ConsoleLogger;
  61. import org.apache.avalon.framework.logger.LogEnabled;
  62. import org.apache.avalon.framework.logger.Logger;
  63. // DOM
  64. import org.w3c.dom.Document;
  65. // SAX
  66. import org.xml.sax.ContentHandler;
  67. import org.xml.sax.InputSource;
  68. import org.xml.sax.SAXException;
  69. import org.xml.sax.XMLReader;
  70. import javax.xml.parsers.ParserConfigurationException;
  71. // Java
  72. import java.io.BufferedReader;
  73. import java.io.IOException;
  74. import java.io.InputStream;
  75. import java.io.InputStreamReader;
  76. import java.io.OutputStream;
  77. import java.io.Reader;
  78. import java.util.Enumeration;
  79. import java.util.Iterator;
  80. import java.util.List;
  81. import java.util.Map;
  82. /**
  83. * Primary class that drives overall FOP process.
  84. * <P>
  85. * The simplest way to use this is to instantiate it with the
  86. * InputSource and OutputStream, then set the renderer desired, and
  87. * calling run();
  88. * <P>
  89. * Here is an example use of Driver which outputs PDF:
  90. *
  91. * <PRE>
  92. * Driver driver = new Driver(new InputSource (args[0]),
  93. * new FileOutputStream(args[1]));
  94. * driver.enableLogging(myLogger); //optional
  95. * driver.setRenderer(RENDER_PDF);
  96. * driver.run();
  97. * </PRE>
  98. * If neccessary, calling classes can call into the lower level
  99. * methods to setup and
  100. * render. Methods can be called to set the
  101. * Renderer to use, the (possibly multiple) ElementMapping(s) to
  102. * use and the OutputStream to use to output the results of the
  103. * rendering (where applicable). In the case of the Renderer and
  104. * ElementMapping(s), the Driver may be supplied either with the
  105. * object itself, or the name of the class, in which case Driver will
  106. * instantiate the class itself. The advantage of the latter is it
  107. * enables runtime determination of Renderer and ElementMapping(s).
  108. * <P>
  109. * Once the Driver is set up, the render method
  110. * is called. Depending on whether DOM or SAX is being used, the
  111. * invocation of the method is either render(Document) or
  112. * buildFOTree(Parser, InputSource) respectively.
  113. * <P>
  114. * A third possibility may be used to build the FO Tree, namely
  115. * calling getContentHandler() and firing the SAX events yourself.
  116. * <P>
  117. * Once the FO Tree is built, the format() and render() methods may be
  118. * called in that order.
  119. * <P>
  120. * Here is an example use of Driver which outputs to AWT:
  121. *
  122. * <PRE>
  123. * Driver driver = new Driver();
  124. * driver.enableLogging(myLogger); //optional
  125. * driver.setRenderer(new org.apache.fop.render.awt.AWTRenderer(translator));
  126. * driver.render(parser, fileInputSource(args[0]));
  127. * </PRE>
  128. */
  129. public class Driver implements LogEnabled {
  130. /**
  131. * Render to PDF. OutputStream must be set
  132. */
  133. public static final int RENDER_PDF = 1;
  134. /**
  135. * Render to a GUI window. No OutputStream neccessary
  136. */
  137. public static final int RENDER_AWT = 2;
  138. /**
  139. * Render to MIF. OutputStream must be set
  140. */
  141. public static final int RENDER_MIF = 3;
  142. /**
  143. * Render to XML. OutputStream must be set
  144. */
  145. public static final int RENDER_XML = 4;
  146. /**
  147. * Render to PRINT. No OutputStream neccessary
  148. */
  149. public static final int RENDER_PRINT = 5;
  150. /**
  151. * Render to PCL. OutputStream must be set
  152. */
  153. public static final int RENDER_PCL = 6;
  154. /**
  155. * Render to Postscript. OutputStream must be set
  156. */
  157. public static final int RENDER_PS = 7;
  158. /**
  159. * Render to Text. OutputStream must be set
  160. */
  161. public static final int RENDER_TXT = 8;
  162. /**
  163. * Render to SVG. OutputStream must be set
  164. */
  165. public static final int RENDER_SVG = 9;
  166. /**
  167. * Render to RTF. OutputStream must be set
  168. */
  169. public static final int RENDER_RTF = 10;
  170. /**
  171. * the FO tree builder
  172. */
  173. private FOTreeBuilder treeBuilder;
  174. /**
  175. * the renderer type code given by setRenderer
  176. */
  177. private int rendererType;
  178. /**
  179. * the renderer to use to output the area tree
  180. */
  181. private Renderer renderer;
  182. /**
  183. * the structure handler
  184. */
  185. private StructureHandler structHandler;
  186. /**
  187. * the source of the FO file
  188. */
  189. private InputSource source;
  190. /**
  191. * the stream to use to output the results of the renderer
  192. */
  193. private OutputStream stream;
  194. /**
  195. * The XML parser to use when building the FO tree
  196. */
  197. private XMLReader reader;
  198. /**
  199. * the system resources that FOP will use
  200. */
  201. private Logger log = null;
  202. private FOUserAgent userAgent = null;
  203. /**
  204. * Returns the fully qualified classname of the standard XML parser for FOP
  205. * to use.
  206. * @return the XML parser classname
  207. */
  208. public static final String getParserClassName() {
  209. try {
  210. return javax.xml.parsers.SAXParserFactory.newInstance()
  211. .newSAXParser().getXMLReader().getClass().getName();
  212. } catch (javax.xml.parsers.ParserConfigurationException e) {
  213. return null;
  214. } catch (org.xml.sax.SAXException e) {
  215. return null;
  216. }
  217. }
  218. /**
  219. * Main constructor for the Driver class.
  220. */
  221. public Driver() {
  222. stream = null;
  223. }
  224. /**
  225. * Convenience constructor for directly setting input and output.
  226. * @param source InputSource to take the XSL-FO input from
  227. * @param stream Target output stream
  228. */
  229. public Driver(InputSource source, OutputStream stream) {
  230. this();
  231. this.source = source;
  232. this.stream = stream;
  233. }
  234. /**
  235. * Initializes the Driver object.
  236. */
  237. public void initialize() {
  238. stream = null;
  239. treeBuilder = new FOTreeBuilder();
  240. treeBuilder.setUserAgent(getUserAgent());
  241. setupDefaultMappings();
  242. }
  243. /**
  244. * Optionally sets the FOUserAgent instance for FOP to use. The Driver
  245. * class sets up its own FOUserAgent if none is set through this method.
  246. * @param agent FOUserAgent to use
  247. */
  248. public void setUserAgent(FOUserAgent agent) {
  249. userAgent = agent;
  250. }
  251. private FOUserAgent getUserAgent() {
  252. if (userAgent == null) {
  253. userAgent = new FOUserAgent();
  254. userAgent.enableLogging(getLogger());
  255. userAgent.setBaseURL("");
  256. }
  257. return userAgent;
  258. }
  259. /**
  260. * Provide the Driver instance with a logger. More information on Avalon
  261. * logging can be found at the
  262. * <a href="http://avalon.apache.org">Avalon site</a>.
  263. *
  264. * @param log the logger. Must not be <code>null</code>.
  265. * @see org.apache.avalon.framework.logger.LogEnabled#enableLogging(Logger)
  266. */
  267. public void enableLogging(Logger log) {
  268. if (this.log == null) {
  269. this.log = log;
  270. } else {
  271. getLogger().warn("Logger is already set! Won't use the new logger.");
  272. }
  273. }
  274. /**
  275. * Returns the logger for use by FOP.
  276. * @return the logger
  277. * @see #enableLogging(Logger)
  278. */
  279. protected Logger getLogger() {
  280. if (this.log == null) {
  281. this.log = new ConsoleLogger(ConsoleLogger.LEVEL_INFO);
  282. this.log.error("Logger not set. Using ConsoleLogger as default.");
  283. }
  284. return this.log;
  285. }
  286. /**
  287. * Resets the Driver so it can be reused. Property and element
  288. * mappings are reset to defaults.
  289. * The output stream is cleared. The renderer is cleared.
  290. */
  291. public synchronized void reset() {
  292. source = null;
  293. stream = null;
  294. reader = null;
  295. treeBuilder.reset();
  296. }
  297. /**
  298. * Indicates whether FOP has already received input data.
  299. * @return true, if input data was received
  300. */
  301. public boolean hasData() {
  302. return (treeBuilder.hasData());
  303. }
  304. /**
  305. * Set the OutputStream to use to output the result of the Renderer
  306. * (if applicable)
  307. * @param stream the stream to output the result of rendering to
  308. */
  309. public void setOutputStream(OutputStream stream) {
  310. this.stream = stream;
  311. }
  312. /**
  313. * Set the source for the FO document. This can be a normal SAX
  314. * InputSource, or an DocumentInputSource containing a DOM document.
  315. * @see DocumentInputSource
  316. */
  317. public void setInputSource(InputSource source) {
  318. this.source = source;
  319. }
  320. /**
  321. * Sets the reader used when reading in the source. If not set,
  322. * this defaults to a basic SAX parser.
  323. * @param reader the reader to use.
  324. */
  325. public void setXMLReader(XMLReader reader) {
  326. this.reader = reader;
  327. }
  328. /**
  329. * Sets all the element and property list mappings to their default values.
  330. *
  331. */
  332. public void setupDefaultMappings() {
  333. addElementMapping("org.apache.fop.fo.FOElementMapping");
  334. addElementMapping("org.apache.fop.svg.SVGElementMapping");
  335. addElementMapping("org.apache.fop.extensions.ExtensionElementMapping");
  336. // add mappings from available services
  337. Iterator providers =
  338. Service.providers(org.apache.fop.fo.ElementMapping.class);
  339. if (providers != null) {
  340. while (providers.hasNext()) {
  341. String str = (String)providers.next();
  342. try {
  343. addElementMapping(str);
  344. } catch (IllegalArgumentException e) {
  345. getLogger().warn("Error while adding element mapping", e);
  346. }
  347. }
  348. }
  349. }
  350. /**
  351. * Shortcut to set the rendering type to use. Must be one of
  352. * <ul>
  353. * <li>RENDER_PDF</li>
  354. * <li>RENDER_AWT</li>
  355. * <li>RENDER_MIF</li>
  356. * <li>RENDER_XML</li>
  357. * <li>RENDER_PCL</li>
  358. * <li>RENDER_PS</li>
  359. * <li>RENDER_TXT</li>
  360. * <li>RENDER_SVG</li>
  361. * <li>RENDER_RTF</li>
  362. * </ul>
  363. * @param renderer the type of renderer to use
  364. * @throws IllegalArgumentException if an unsupported renderer type was required.
  365. */
  366. public void setRenderer(int renderer) throws IllegalArgumentException {
  367. rendererType = renderer;
  368. switch (renderer) {
  369. case RENDER_PDF:
  370. setRenderer("org.apache.fop.render.pdf.PDFRenderer");
  371. break;
  372. case RENDER_AWT:
  373. throw new IllegalArgumentException("Use renderer form of setRenderer() for AWT");
  374. case RENDER_PRINT:
  375. throw new IllegalArgumentException("Use renderer form of setRenderer() for PRINT");
  376. case RENDER_PCL:
  377. setRenderer("org.apache.fop.render.pcl.PCLRenderer");
  378. break;
  379. case RENDER_PS:
  380. setRenderer("org.apache.fop.render.ps.PSRenderer");
  381. break;
  382. case RENDER_TXT:
  383. setRenderer("org.apache.fop.render.txt.TXTRenderer()");
  384. break;
  385. case RENDER_MIF:
  386. //structHandler will be set later
  387. break;
  388. case RENDER_XML:
  389. setRenderer("org.apache.fop.render.xml.XMLRenderer");
  390. break;
  391. case RENDER_SVG:
  392. setRenderer("org.apache.fop.render.svg.SVGRenderer");
  393. break;
  394. case RENDER_RTF:
  395. //structHandler will be set later
  396. break;
  397. default:
  398. throw new IllegalArgumentException("Unknown renderer type");
  399. }
  400. }
  401. /**
  402. * Set the Renderer to use.
  403. * @param renderer the renderer instance to use (Note: Logger must be set at this point)
  404. */
  405. public void setRenderer(Renderer renderer) {
  406. renderer.setUserAgent(getUserAgent());
  407. this.renderer = renderer;
  408. }
  409. /**
  410. * Returns the currently active renderer.
  411. * @return the renderer
  412. */
  413. public Renderer getRenderer() {
  414. return renderer;
  415. }
  416. /**
  417. * Sets the renderer.
  418. * @param rendererClassName the fully qualified classname of the renderer
  419. * class to use.
  420. * @param version version number
  421. * @deprecated use renderer.setProducer(version) + setRenderer(renderer) or
  422. * just setRenderer(rendererType) which will use the default producer string.
  423. * @see #setRenderer(int)
  424. * @see #setRenderer(Renderer)
  425. */
  426. public void setRenderer(String rendererClassName, String version) {
  427. setRenderer(rendererClassName);
  428. }
  429. /**
  430. * Set the class name of the Renderer to use as well as the
  431. * producer string for those renderers that can make use of it.
  432. * @param rendererClassName classname of the renderer to use such as
  433. * "org.apache.fop.render.pdf.PDFRenderer"
  434. * @exception IllegalArgumentException if the classname was invalid.
  435. * @see #setRenderer(int)
  436. */
  437. public void setRenderer(String rendererClassName)
  438. throws IllegalArgumentException {
  439. try {
  440. renderer =
  441. (Renderer)Class.forName(rendererClassName).newInstance();
  442. if (renderer instanceof LogEnabled) {
  443. ((LogEnabled)renderer).enableLogging(getLogger());
  444. }
  445. renderer.setProducer(Version.getVersion());
  446. renderer.setUserAgent(getUserAgent());
  447. } catch (ClassNotFoundException e) {
  448. throw new IllegalArgumentException("Could not find "
  449. + rendererClassName);
  450. } catch (InstantiationException e) {
  451. throw new IllegalArgumentException("Could not instantiate "
  452. + rendererClassName);
  453. } catch (IllegalAccessException e) {
  454. throw new IllegalArgumentException("Could not access "
  455. + rendererClassName);
  456. } catch (ClassCastException e) {
  457. throw new IllegalArgumentException(rendererClassName
  458. + " is not a renderer");
  459. }
  460. }
  461. /**
  462. * Add the given element mapping.
  463. * An element mapping maps element names to Java classes.
  464. *
  465. * @param mapping the element mappingto add
  466. */
  467. public void addElementMapping(ElementMapping mapping) {
  468. mapping.addToBuilder(treeBuilder);
  469. }
  470. /**
  471. * Add the element mapping with the given class name.
  472. * @param mappingClassName the class name representing the element mapping.
  473. * @throws IllegalArgumentException if there was not such element mapping.
  474. */
  475. public void addElementMapping(String mappingClassName)
  476. throws IllegalArgumentException {
  477. try {
  478. ElementMapping mapping =
  479. (ElementMapping)Class.forName(mappingClassName).newInstance();
  480. addElementMapping(mapping);
  481. } catch (ClassNotFoundException e) {
  482. throw new IllegalArgumentException("Could not find "
  483. + mappingClassName);
  484. } catch (InstantiationException e) {
  485. throw new IllegalArgumentException("Could not instantiate "
  486. + mappingClassName);
  487. } catch (IllegalAccessException e) {
  488. throw new IllegalArgumentException("Could not access "
  489. + mappingClassName);
  490. } catch (ClassCastException e) {
  491. throw new IllegalArgumentException(mappingClassName
  492. + " is not an ElementMapping");
  493. }
  494. }
  495. /**
  496. * Returns the tree builder (a SAX ContentHandler).
  497. *
  498. * Used in situations where SAX is used but not via a FOP-invoked
  499. * SAX parser. A good example is an XSLT engine that fires SAX
  500. * events but isn't a SAX Parser itself.
  501. * @return a content handler for handling the SAX events.
  502. */
  503. public ContentHandler getContentHandler() {
  504. // TODO: - do this stuff in a better way
  505. // PIJ: I guess the structure handler should be created by the renderer.
  506. if (rendererType == RENDER_MIF) {
  507. structHandler = new org.apache.fop.mif.MIFHandler(stream);
  508. } else if (rendererType == RENDER_RTF) {
  509. structHandler = new org.apache.fop.rtf.renderer.RTFHandler(stream);
  510. } else {
  511. if (renderer == null) {
  512. throw new IllegalStateException(
  513. "Renderer not set when using standard structHandler");
  514. }
  515. structHandler = new LayoutHandler(stream, renderer, true);
  516. }
  517. structHandler.enableLogging(getLogger());
  518. treeBuilder.setUserAgent(getUserAgent());
  519. treeBuilder.setStructHandler(structHandler);
  520. return treeBuilder;
  521. }
  522. /**
  523. * Render the FO document read by a SAX Parser from an InputSource.
  524. * @param parser the SAX parser.
  525. * @param source the input source the parser reads from.
  526. * @throws FOPException if anything goes wrong.
  527. */
  528. public synchronized void render(XMLReader parser, InputSource source)
  529. throws FOPException {
  530. parser.setContentHandler(getContentHandler());
  531. try {
  532. parser.parse(source);
  533. } catch (SAXException e) {
  534. if (e.getException() instanceof FOPException) {
  535. // Undo exception tunneling.
  536. throw (FOPException)e.getException();
  537. } else {
  538. throw new FOPException(e);
  539. }
  540. } catch (IOException e) {
  541. throw new FOPException(e);
  542. }
  543. }
  544. /**
  545. * Render the FO ducument represented by a DOM Document.
  546. * @param document the DOM document to read from
  547. * @throws FOPException if anything goes wrong.
  548. */
  549. public synchronized void render(Document document)
  550. throws FOPException {
  551. try {
  552. DocumentInputSource source = new DocumentInputSource(document);
  553. DocumentReader reader = new DocumentReader();
  554. reader.setContentHandler(getContentHandler());
  555. reader.parse(source);
  556. } catch (SAXException e) {
  557. if (e.getException() instanceof FOPException) {
  558. // Undo exception tunneling.
  559. throw (FOPException)e.getException();
  560. } else {
  561. throw new FOPException(e);
  562. }
  563. } catch (IOException e) {
  564. throw new FOPException(e);
  565. }
  566. }
  567. /**
  568. * Runs the formatting and renderering process using the previously set
  569. * parser, input source, renderer and output stream.
  570. * If the renderer was not set, default to PDF.
  571. * If no parser was set, and the input source is not a dom document,
  572. * get a default SAX parser.
  573. * @throws IOException in case of IO errors.
  574. * @throws FOPException if anything else goes wrong.
  575. */
  576. public synchronized void run() throws IOException, FOPException {
  577. if (renderer == null) {
  578. setRenderer(RENDER_PDF);
  579. }
  580. if (source == null) {
  581. throw new FOPException("InputSource is not set.");
  582. }
  583. if (reader == null) {
  584. if (!(source instanceof DocumentInputSource)) {
  585. try {
  586. reader = javax.xml.parsers.SAXParserFactory.newInstance()
  587. .newSAXParser().getXMLReader();
  588. } catch (SAXException e) {
  589. throw new FOPException(e);
  590. } catch (ParserConfigurationException e) {
  591. throw new FOPException(e);
  592. }
  593. }
  594. }
  595. if (source instanceof DocumentInputSource) {
  596. render(((DocumentInputSource)source).getDocument());
  597. } else {
  598. render(reader, source);
  599. }
  600. }
  601. }
  602. // code stolen from org.apache.batik.util and modified slightly
  603. // does what sun.misc.Service probably does, but it cannot be relied on.
  604. // hopefully will be part of standard jdk sometime.
  605. /**
  606. * This class loads services present in the class path.
  607. */
  608. class Service {
  609. private static Map providerMap = new java.util.Hashtable();
  610. public static synchronized Iterator providers(Class cls) {
  611. ClassLoader cl = cls.getClassLoader();
  612. // null if loaded by bootstrap class loader
  613. if (cl == null) {
  614. cl = ClassLoader.getSystemClassLoader();
  615. }
  616. String serviceFile = "META-INF/services/" + cls.getName();
  617. // getLogger().debug("File: " + serviceFile);
  618. List lst = (List)providerMap.get(serviceFile);
  619. if (lst != null) {
  620. return lst.iterator();
  621. }
  622. lst = new java.util.Vector();
  623. providerMap.put(serviceFile, lst);
  624. Enumeration e;
  625. try {
  626. e = cl.getResources(serviceFile);
  627. } catch (IOException ioe) {
  628. return lst.iterator();
  629. }
  630. while (e.hasMoreElements()) {
  631. try {
  632. java.net.URL u = (java.net.URL)e.nextElement();
  633. //getLogger().debug("URL: " + u);
  634. InputStream is = u.openStream();
  635. Reader r = new InputStreamReader(is, "UTF-8");
  636. BufferedReader br = new BufferedReader(r);
  637. String line = br.readLine();
  638. while (line != null) {
  639. try {
  640. // First strip any comment...
  641. int idx = line.indexOf('#');
  642. if (idx != -1) {
  643. line = line.substring(0, idx);
  644. }
  645. // Trim whitespace.
  646. line = line.trim();
  647. // If nothing left then loop around...
  648. if (line.length() == 0) {
  649. line = br.readLine();
  650. continue;
  651. }
  652. // getLogger().debug("Line: " + line);
  653. // Try and load the class
  654. // Object obj = cl.loadClass(line).newInstance();
  655. // stick it into our vector...
  656. lst.add(line);
  657. } catch (Exception ex) {
  658. // Just try the next line
  659. }
  660. line = br.readLine();
  661. }
  662. } catch (Exception ex) {
  663. // Just try the next file...
  664. }
  665. }
  666. return lst.iterator();
  667. }
  668. }