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 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. /*
  2. * $Id$
  3. * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
  4. * For details on use and redistribution please refer to the
  5. * LICENSE file included with these sources.
  6. */
  7. package org.apache.fop.apps;
  8. // FOP
  9. import org.apache.fop.fo.FOUserAgent;
  10. import org.apache.fop.fo.FOTreeBuilder;
  11. import org.apache.fop.fo.ElementMapping;
  12. import org.apache.fop.render.Renderer;
  13. import org.apache.fop.tools.DocumentInputSource;
  14. import org.apache.fop.tools.DocumentReader;
  15. import org.apache.fop.render.pdf.PDFRenderer;
  16. // Avalon
  17. import org.apache.avalon.framework.logger.ConsoleLogger;
  18. import org.apache.avalon.framework.logger.Logger;
  19. import org.apache.avalon.framework.logger.LogEnabled;
  20. import org.apache.avalon.framework.logger.AbstractLogEnabled;
  21. // DOM
  22. import org.w3c.dom.Document;
  23. import org.w3c.dom.Node;
  24. import org.w3c.dom.NamedNodeMap;
  25. import org.w3c.dom.Attr;
  26. // SAX
  27. import org.xml.sax.ContentHandler;
  28. import org.xml.sax.InputSource;
  29. import org.xml.sax.XMLReader;
  30. import org.xml.sax.SAXException;
  31. import org.xml.sax.helpers.AttributesImpl;
  32. // Java
  33. import java.io.*;
  34. import java.util.*;
  35. /**
  36. * Primary class that drives overall FOP process.
  37. * <P>
  38. * The simplest way to use this is to instantiate it with the
  39. * InputSource and OutputStream, then set the renderer desired, and
  40. * calling run();
  41. * <P>
  42. * Here is an example use of Driver which outputs PDF:
  43. *
  44. * <PRE>
  45. * Driver driver = new Driver(new InputSource (args[0]),
  46. * new FileOutputStream(args[1]));
  47. * driver.enableLogging(myLogger); //optional
  48. * driver.setRenderer(RENDER_PDF);
  49. * driver.run();
  50. * </PRE>
  51. * If neccessary, calling classes can call into the lower level
  52. * methods to setup and
  53. * render. Methods can be called to set the
  54. * Renderer to use, the (possibly multiple) ElementMapping(s) to
  55. * use and the OutputStream to use to output the results of the
  56. * rendering (where applicable). In the case of the Renderer and
  57. * ElementMapping(s), the Driver may be supplied either with the
  58. * object itself, or the name of the class, in which case Driver will
  59. * instantiate the class itself. The advantage of the latter is it
  60. * enables runtime determination of Renderer and ElementMapping(s).
  61. * <P>
  62. * Once the Driver is set up, the render method
  63. * is called. Depending on whether DOM or SAX is being used, the
  64. * invocation of the method is either render(Document) or
  65. * buildFOTree(Parser, InputSource) respectively.
  66. * <P>
  67. * A third possibility may be used to build the FO Tree, namely
  68. * calling getContentHandler() and firing the SAX events yourself.
  69. * <P>
  70. * Once the FO Tree is built, the format() and render() methods may be
  71. * called in that order.
  72. * <P>
  73. * Here is an example use of Driver which outputs to AWT:
  74. *
  75. * <PRE>
  76. * Driver driver = new Driver();
  77. * driver.enableLogging(myLogger); //optional
  78. * driver.setRenderer(new org.apache.fop.render.awt.AWTRenderer(translator));
  79. * driver.render(parser, fileInputSource(args[0]));
  80. * </PRE>
  81. */
  82. public class Driver implements LogEnabled {
  83. /**
  84. * Render to PDF. OutputStream must be set
  85. */
  86. public static final int RENDER_PDF = 1;
  87. /**
  88. * Render to a GUI window. No OutputStream neccessary
  89. */
  90. public static final int RENDER_AWT = 2;
  91. /**
  92. * Render to MIF. OutputStream must be set
  93. */
  94. public static final int RENDER_MIF = 3;
  95. /**
  96. * Render to XML. OutputStream must be set
  97. */
  98. public static final int RENDER_XML = 4;
  99. /**
  100. * Render to PRINT. No OutputStream neccessary
  101. */
  102. public static final int RENDER_PRINT = 5;
  103. /**
  104. * Render to PCL. OutputStream must be set
  105. */
  106. public static final int RENDER_PCL = 6;
  107. /**
  108. * Render to Postscript. OutputStream must be set
  109. */
  110. public static final int RENDER_PS = 7;
  111. /**
  112. * Render to Text. OutputStream must be set
  113. */
  114. public static final int RENDER_TXT = 8;
  115. /**
  116. * Render to SVG. OutputStream must be set
  117. */
  118. public static final int RENDER_SVG = 9;
  119. /**
  120. * the FO tree builder
  121. */
  122. private FOTreeBuilder _treeBuilder;
  123. /**
  124. * the renderer to use to output the area tree
  125. */
  126. private Renderer _renderer;
  127. /**
  128. * the structure handler
  129. */
  130. private StructureHandler structHandler;
  131. /**
  132. * the source of the FO file
  133. */
  134. private InputSource _source;
  135. /**
  136. * the stream to use to output the results of the renderer
  137. */
  138. private OutputStream _stream;
  139. /**
  140. * The XML parser to use when building the FO tree
  141. */
  142. private XMLReader _reader;
  143. /**
  144. * the system resources that FOP will use
  145. */
  146. private Logger log = null;
  147. private FOUserAgent userAgent = null;
  148. public static final String getParserClassName() {
  149. try {
  150. return javax.xml.parsers.SAXParserFactory.newInstance().newSAXParser().getXMLReader().getClass().getName();
  151. } catch (javax.xml.parsers.ParserConfigurationException e) {
  152. return null;
  153. } catch (org.xml.sax.SAXException e) {
  154. return null;
  155. }
  156. }
  157. /**
  158. * create a new Driver
  159. */
  160. public Driver() {
  161. _stream = null;
  162. }
  163. public Driver(InputSource source, OutputStream stream) {
  164. this();
  165. _source = source;
  166. _stream = stream;
  167. }
  168. public void initialize() {
  169. _stream = null;
  170. _treeBuilder = new FOTreeBuilder();
  171. _treeBuilder.setUserAgent(getUserAgent());
  172. setupDefaultMappings();
  173. }
  174. public void setUserAgent(FOUserAgent agent) {
  175. userAgent = agent;
  176. }
  177. private FOUserAgent getUserAgent() {
  178. if(userAgent == null) {
  179. userAgent = new FOUserAgent();
  180. userAgent.enableLogging(getLogger());
  181. userAgent.setBaseURL("file:/.");
  182. }
  183. return userAgent;
  184. }
  185. public void enableLogging(Logger log) {
  186. if (this.log == null) {
  187. this.log = log;
  188. } else {
  189. getLogger().warn("Logger is already set! Won't use the new logger.");
  190. }
  191. }
  192. protected Logger getLogger() {
  193. if(this.log == null) {
  194. this.log = new ConsoleLogger(ConsoleLogger.LEVEL_INFO);
  195. this.log.error("Logger not set. Using ConsoleLogger as default.");
  196. }
  197. return this.log;
  198. }
  199. /**
  200. * Resets the Driver so it can be reused. Property and element
  201. * mappings are reset to defaults.
  202. * The output stream is cleared. The renderer is cleared.
  203. */
  204. public synchronized void reset() {
  205. _source = null;
  206. _stream = null;
  207. _reader = null;
  208. _treeBuilder.reset();
  209. }
  210. public boolean hasData() {
  211. return (_treeBuilder.hasData());
  212. }
  213. /**
  214. * Set the OutputStream to use to output the result of the Renderer
  215. * (if applicable)
  216. * @param stream the stream to output the result of rendering to
  217. *
  218. */
  219. public void setOutputStream(OutputStream stream) {
  220. _stream = stream;
  221. }
  222. /**
  223. * Set the source for the FO document. This can be a normal SAX
  224. * InputSource, or an DocumentInputSource containing a DOM document.
  225. * @see DocumentInputSource
  226. */
  227. public void setInputSource(InputSource source) {
  228. _source = source;
  229. }
  230. /**
  231. * Sets the reader used when reading in the source. If not set,
  232. * this defaults to a basic SAX parser.
  233. */
  234. public void setXMLReader(XMLReader reader) {
  235. _reader = reader;
  236. }
  237. /**
  238. * Sets all the element and property list mappings to their default values.
  239. *
  240. */
  241. public void setupDefaultMappings() {
  242. addElementMapping("org.apache.fop.fo.FOElementMapping");
  243. addElementMapping("org.apache.fop.svg.SVGElementMapping");
  244. addElementMapping("org.apache.fop.extensions.ExtensionElementMapping");
  245. // add mappings from available services
  246. Enumeration providers =
  247. Service.providers(org.apache.fop.fo.ElementMapping.class);
  248. if (providers != null) {
  249. while (providers.hasMoreElements()) {
  250. String str = (String)providers.nextElement();
  251. try {
  252. addElementMapping(str);
  253. } catch (IllegalArgumentException e) {}
  254. }
  255. }
  256. }
  257. /**
  258. * Set the rendering type to use. Must be one of
  259. * <ul>
  260. * <li>RENDER_PDF
  261. * <li>RENDER_AWT
  262. * <li>RENDER_MIF
  263. * <li>RENDER_XML
  264. * <li>RENDER_PCL
  265. * <li>RENDER_PS
  266. * <li>RENDER_TXT
  267. * <li>RENDER_SVG
  268. * </ul>
  269. * @param renderer the type of renderer to use
  270. */
  271. public void setRenderer(int renderer) throws IllegalArgumentException {
  272. switch (renderer) {
  273. case RENDER_PDF:
  274. setRenderer("org.apache.fop.render.pdf.PDFRenderer");
  275. break;
  276. case RENDER_AWT:
  277. throw new IllegalArgumentException("Use renderer form of setRenderer() for AWT");
  278. case RENDER_PRINT:
  279. throw new IllegalArgumentException("Use renderer form of setRenderer() for PRINT");
  280. case RENDER_PCL:
  281. setRenderer("org.apache.fop.render.pcl.PCLRenderer");
  282. break;
  283. case RENDER_PS:
  284. setRenderer("org.apache.fop.render.ps.PSRenderer");
  285. break;
  286. case RENDER_TXT:
  287. setRenderer("org.apache.fop.render.txt.TXTRenderer()");
  288. break;
  289. case RENDER_MIF:
  290. //structHandler = new org.apache.fop.mif.MIFHandler(_stream);
  291. break;
  292. case RENDER_XML:
  293. setRenderer("org.apache.fop.render.xml.XMLRenderer");
  294. break;
  295. case RENDER_SVG:
  296. setRenderer("org.apache.fop.render.svg.SVGRenderer");
  297. break;
  298. default:
  299. throw new IllegalArgumentException("Unknown renderer type");
  300. }
  301. }
  302. /**
  303. * Set the Renderer to use.
  304. * @param renderer the renderer instance to use (Note: Logger must be set at this point)
  305. */
  306. public void setRenderer(Renderer renderer) {
  307. renderer.setUserAgent(getUserAgent());
  308. _renderer = renderer;
  309. }
  310. public Renderer getRenderer() {
  311. return _renderer;
  312. }
  313. /**
  314. * @deprecated use renderer.setProducer(version) + setRenderer(renderer) or just setRenderer(renderer_type) which will use the default producer string.
  315. * @see #setRenderer(int)
  316. * @see #setRenderer(Renderer)
  317. */
  318. public void setRenderer(String rendererClassName, String version) {
  319. setRenderer(rendererClassName);
  320. }
  321. /**
  322. * Set the class name of the Renderer to use as well as the
  323. * producer string for those renderers that can make use of it.
  324. * @param rendererClassName classname of the renderer to use such as
  325. * "org.apache.fop.render.pdf.PDFRenderer"
  326. * @exception IllegalArgumentException if the classname was invalid.
  327. * @see #setRenderer(int)
  328. */
  329. public void setRenderer(String rendererClassName)
  330. throws IllegalArgumentException {
  331. try {
  332. _renderer =
  333. (Renderer)Class.forName(rendererClassName).newInstance();
  334. if (_renderer instanceof LogEnabled) {
  335. ((LogEnabled)_renderer).enableLogging(getLogger());
  336. }
  337. _renderer.setProducer(Version.getVersion());
  338. _renderer.setUserAgent(getUserAgent());
  339. } catch (ClassNotFoundException e) {
  340. throw new IllegalArgumentException("Could not find "
  341. + rendererClassName);
  342. }
  343. catch (InstantiationException e) {
  344. throw new IllegalArgumentException("Could not instantiate "
  345. + rendererClassName);
  346. }
  347. catch (IllegalAccessException e) {
  348. throw new IllegalArgumentException("Could not access "
  349. + rendererClassName);
  350. }
  351. catch (ClassCastException e) {
  352. throw new IllegalArgumentException(rendererClassName
  353. + " is not a renderer");
  354. }
  355. }
  356. /**
  357. * Add the given element mapping.
  358. * An element mapping maps element names to Java classes.
  359. *
  360. * @param mapping the element mappingto add
  361. */
  362. public void addElementMapping(ElementMapping mapping) {
  363. mapping.addToBuilder(_treeBuilder);
  364. }
  365. /**
  366. * add the element mapping with the given class name
  367. */
  368. public void addElementMapping(String mappingClassName)
  369. throws IllegalArgumentException {
  370. try {
  371. ElementMapping mapping =
  372. (ElementMapping)Class.forName(mappingClassName).newInstance();
  373. addElementMapping(mapping);
  374. } catch (ClassNotFoundException e) {
  375. throw new IllegalArgumentException("Could not find "
  376. + mappingClassName);
  377. }
  378. catch (InstantiationException e) {
  379. throw new IllegalArgumentException("Could not instantiate "
  380. + mappingClassName);
  381. }
  382. catch (IllegalAccessException e) {
  383. throw new IllegalArgumentException("Could not access "
  384. + mappingClassName);
  385. }
  386. catch (ClassCastException e) {
  387. throw new IllegalArgumentException(mappingClassName
  388. + " is not an ElementMapping");
  389. }
  390. }
  391. /**
  392. * Returns the tree builder (a SAX ContentHandler).
  393. *
  394. * Used in situations where SAX is used but not via a FOP-invoked
  395. * SAX parser. A good example is an XSLT engine that fires SAX
  396. * events but isn't a SAX Parser itself.
  397. */
  398. public ContentHandler getContentHandler() {
  399. // TODO - do this stuff in a better way
  400. if(_renderer != null) {
  401. structHandler = new LayoutHandler(_stream, _renderer, true);
  402. } else {
  403. structHandler = new org.apache.fop.mif.MIFHandler(_stream);
  404. }
  405. structHandler.enableLogging(getLogger());
  406. _treeBuilder.setUserAgent(getUserAgent());
  407. _treeBuilder.setStructHandler(structHandler);
  408. return _treeBuilder;
  409. }
  410. /**
  411. * Build the formatting object tree using the given SAX Parser and
  412. * SAX InputSource
  413. */
  414. public synchronized void render(XMLReader parser, InputSource source)
  415. throws FOPException {
  416. parser.setContentHandler(getContentHandler());
  417. try {
  418. parser.parse(source);
  419. } catch (SAXException e) {
  420. if (e.getException() instanceof FOPException) {
  421. throw (FOPException)e.getException();
  422. } else {
  423. throw new FOPException(e);
  424. }
  425. }
  426. catch (IOException e) {
  427. throw new FOPException(e);
  428. }
  429. }
  430. /**
  431. * Build the formatting object tree using the given DOM Document
  432. */
  433. public synchronized void render(Document document)
  434. throws FOPException {
  435. try {
  436. DocumentInputSource source = new DocumentInputSource(document);
  437. DocumentReader reader = new DocumentReader();
  438. reader.setContentHandler(getContentHandler());
  439. reader.parse(source);
  440. } catch (SAXException e) {
  441. throw new FOPException(e);
  442. }
  443. catch (IOException e) {
  444. throw new FOPException(e);
  445. }
  446. }
  447. /**
  448. * Runs the formatting and renderering process using the previously set
  449. * inputsource and outputstream
  450. */
  451. public synchronized void run() throws IOException, FOPException {
  452. if (_renderer == null) {
  453. setRenderer(RENDER_PDF);
  454. }
  455. if (_source == null) {
  456. throw new FOPException("InputSource is not set.");
  457. }
  458. if (_reader == null) {
  459. if (!(_source instanceof DocumentInputSource)) {
  460. try {
  461. _reader = javax.xml.parsers.SAXParserFactory.newInstance().newSAXParser().getXMLReader();
  462. } catch(Exception e) {
  463. throw new FOPException(e);
  464. }
  465. }
  466. }
  467. if (_source instanceof DocumentInputSource) {
  468. render(((DocumentInputSource)_source).getDocument());
  469. } else {
  470. render(_reader, _source);
  471. }
  472. }
  473. }
  474. // code stolen from org.apache.batik.util and modified slightly
  475. // does what sun.misc.Service probably does, but it cannot be relied on.
  476. // hopefully will be part of standard jdk sometime.
  477. /**
  478. * This class loads services present in the class path.
  479. */
  480. class Service {
  481. static Hashtable providerMap = new Hashtable();
  482. public static synchronized Enumeration providers(Class cls) {
  483. ClassLoader cl = cls.getClassLoader();
  484. // null if loaded by bootstrap class loader
  485. if(cl == null) {
  486. cl = ClassLoader.getSystemClassLoader();
  487. }
  488. String serviceFile = "META-INF/services/" + cls.getName();
  489. // getLogger().debug("File: " + serviceFile);
  490. Vector v = (Vector)providerMap.get(serviceFile);
  491. if (v != null)
  492. return v.elements();
  493. v = new Vector();
  494. providerMap.put(serviceFile, v);
  495. Enumeration e;
  496. try {
  497. e = cl.getResources(serviceFile);
  498. } catch (IOException ioe) {
  499. return v.elements();
  500. }
  501. while (e.hasMoreElements()) {
  502. try {
  503. java.net.URL u = (java.net.URL)e.nextElement();
  504. //getLogger().debug("URL: " + u);
  505. InputStream is = u.openStream();
  506. Reader r = new InputStreamReader(is, "UTF-8");
  507. BufferedReader br = new BufferedReader(r);
  508. String line = br.readLine();
  509. while (line != null) {
  510. try {
  511. // First strip any comment...
  512. int idx = line.indexOf('#');
  513. if (idx != -1)
  514. line = line.substring(0, idx);
  515. // Trim whitespace.
  516. line = line.trim();
  517. // If nothing left then loop around...
  518. if (line.length() == 0) {
  519. line = br.readLine();
  520. continue;
  521. }
  522. // getLogger().debug("Line: " + line);
  523. // Try and load the class
  524. // Object obj = cl.loadClass(line).newInstance();
  525. // stick it into our vector...
  526. v.add(line);
  527. } catch (Exception ex) {
  528. // Just try the next line
  529. }
  530. line = br.readLine();
  531. }
  532. } catch (Exception ex) {
  533. // Just try the next file...
  534. }
  535. }
  536. return v.elements();
  537. }
  538. }