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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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.FOTreeBuilder;
  10. import org.apache.fop.fo.ElementMapping;
  11. import org.apache.fop.layout.AreaTree;
  12. import org.apache.fop.render.Renderer;
  13. import org.apache.fop.configuration.ConfigurationReader;
  14. import org.apache.fop.configuration.Configuration;
  15. import org.apache.fop.tools.DocumentInputSource;
  16. import org.apache.fop.tools.DocumentReader;
  17. import org.apache.fop.render.pdf.PDFRenderer;
  18. import org.apache.fop.system.BufferManager;
  19. import org.apache.log.*;
  20. import org.apache.log.format.*;
  21. import org.apache.log.output.io.*;
  22. import org.apache.log.output.*;
  23. // DOM
  24. import org.w3c.dom.Document;
  25. import org.w3c.dom.Node;
  26. import org.w3c.dom.NamedNodeMap;
  27. import org.w3c.dom.Attr;
  28. // SAX
  29. import org.xml.sax.ContentHandler;
  30. import org.xml.sax.InputSource;
  31. import org.xml.sax.XMLReader;
  32. import org.xml.sax.SAXException;
  33. import org.xml.sax.helpers.AttributesImpl;
  34. // Java
  35. import java.io.*;
  36. import java.util.*;
  37. /**
  38. * Primary class that drives overall FOP process.
  39. * <P>
  40. * The simplest way to use this is to instantiate it with the
  41. * InputSource and OutputStream, then set the renderer desired, and
  42. * calling run();
  43. * <P>
  44. * Here is an example use of Driver which outputs PDF:
  45. *
  46. * <PRE>
  47. * Driver driver = new Driver(new InputSource (args[0]),
  48. * new FileOutputStream(args[1]));
  49. * driver.setRenderer(RENDER_PDF);
  50. * driver.run();
  51. * </PRE>
  52. * If neccessary, calling classes can call into the lower level
  53. * methods to setup and
  54. * render. Methods can be called to set the
  55. * Renderer to use, the (possibly multiple) ElementMapping(s) to
  56. * use and the OutputStream to use to output the results of the
  57. * rendering (where applicable). In the case of the Renderer and
  58. * ElementMapping(s), the Driver may be supplied either with the
  59. * object itself, or the name of the class, in which case Driver will
  60. * instantiate the class itself. The advantage of the latter is it
  61. * enables runtime determination of Renderer and ElementMapping(s).
  62. * <P>
  63. * Once the Driver is set up, the render method
  64. * is called. Depending on whether DOM or SAX is being used, the
  65. * invocation of the method is either render(Document) or
  66. * buildFOTree(Parser, InputSource) respectively.
  67. * <P>
  68. * A third possibility may be used to build the FO Tree, namely
  69. * calling getContentHandler() and firing the SAX events yourself.
  70. * <P>
  71. * Once the FO Tree is built, the format() and render() methods may be
  72. * called in that order.
  73. * <P>
  74. * Here is an example use of Driver which outputs to AWT:
  75. *
  76. * <PRE>
  77. * Driver driver = new Driver();
  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 {
  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 area tree that is the result of formatting the FO tree
  125. */
  126. private AreaTree _areaTree;
  127. /**
  128. * the renderer to use to output the area tree
  129. */
  130. private Renderer _renderer;
  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. * If true, full error stacks are reported
  145. */
  146. private boolean _errorDump = false;
  147. /**
  148. * the system resources that FOP will use
  149. */
  150. private BufferManager _bufferManager;
  151. private Logger log;
  152. public static final String getParserClassName() {
  153. String parserClassName = null;
  154. try {
  155. parserClassName = System.getProperty("org.xml.sax.parser");
  156. } catch (SecurityException se) {}
  157. if (parserClassName == null) {
  158. parserClassName = "org.apache.xerces.parsers.SAXParser";
  159. }
  160. return parserClassName;
  161. }
  162. /**
  163. * create a new Driver
  164. */
  165. public Driver() {
  166. _stream = null;
  167. _bufferManager = new BufferManager();
  168. _treeBuilder = new FOTreeBuilder();
  169. _treeBuilder.setBufferManager(_bufferManager);
  170. setupDefaultMappings();
  171. }
  172. public Driver(InputSource source, OutputStream stream) {
  173. this();
  174. _source = source;
  175. _stream = stream;
  176. }
  177. public void setLogger(Logger logger) {
  178. log = logger;
  179. }
  180. private Logger getLogger() {
  181. if(log == null) {
  182. Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();
  183. PatternFormatter formatter = new PatternFormatter(
  184. "[%{priority}]: %{message}\n%{throwable}" );
  185. LogTarget target = null;
  186. target = new StreamTarget(System.out, formatter);
  187. hierarchy.setDefaultLogTarget(target);
  188. log = hierarchy.getLoggerFor("fop");
  189. log.setPriority(Priority.INFO);
  190. log.error("Logger not set");
  191. }
  192. return log;
  193. }
  194. /**
  195. * Resets the Driver so it can be reused. Property and element
  196. * mappings are reset to defaults.
  197. * The output stream is cleared. The renderer is cleared.
  198. */
  199. public synchronized void reset() {
  200. _areaTree = null;
  201. _source = null;
  202. _stream = null;
  203. _reader = null;
  204. _treeBuilder.reset();
  205. }
  206. public boolean hasData() {
  207. return (_treeBuilder.hasData());
  208. }
  209. /**
  210. * Set the error dump option
  211. * @param dump if true, full stacks will be reported to the error log
  212. */
  213. public void setErrorDump(boolean dump) {
  214. _errorDump = dump;
  215. }
  216. /**
  217. * Set the OutputStream to use to output the result of the Renderer
  218. * (if applicable)
  219. * @param stream the stream to output the result of rendering to
  220. *
  221. */
  222. public void setOutputStream(OutputStream stream) {
  223. _stream = stream;
  224. }
  225. /**
  226. * Set the source for the FO document. This can be a normal SAX
  227. * InputSource, or an DocumentInputSource containing a DOM document.
  228. * @see DocumentInputSource
  229. */
  230. public void setInputSource(InputSource source) {
  231. _source = source;
  232. }
  233. /**
  234. * Sets the reader used when reading in the source. If not set,
  235. * this defaults to a basic SAX parser.
  236. */
  237. public void setXMLReader(XMLReader reader) {
  238. _reader = reader;
  239. }
  240. /**
  241. * Sets all the element and property list mappings to their default values.
  242. *
  243. */
  244. public void setupDefaultMappings() {
  245. addElementMapping("org.apache.fop.fo.StandardElementMapping");
  246. addElementMapping("org.apache.fop.svg.SVGElementMapping");
  247. addElementMapping("org.apache.fop.extensions.ExtensionElementMapping");
  248. // add mappings from available services
  249. Enumeration providers =
  250. Service.providers(org.apache.fop.fo.ElementMapping.class);
  251. if (providers != null) {
  252. while (providers.hasMoreElements()) {
  253. String str = (String)providers.nextElement();
  254. try {
  255. addElementMapping(str);
  256. } catch (IllegalArgumentException e) {}
  257. }
  258. }
  259. }
  260. /**
  261. * Set the rendering type to use. Must be one of
  262. * <ul>
  263. * <li>RENDER_PDF
  264. * <li>RENDER_AWT
  265. * <li>RENDER_MIF
  266. * <li>RENDER_XML
  267. * <li>RENDER_PCL
  268. * <li>RENDER_PS
  269. * <li>RENDER_TXT
  270. * <li>RENDER_SVG
  271. * </ul>
  272. * @param renderer the type of renderer to use
  273. */
  274. public void setRenderer(int renderer) throws IllegalArgumentException {
  275. switch (renderer) {
  276. case RENDER_PDF:
  277. setRenderer(new org.apache.fop.render.pdf.PDFRenderer());
  278. break;
  279. case RENDER_AWT:
  280. throw new IllegalArgumentException("Use renderer form of setRenderer() for AWT");
  281. case RENDER_PRINT:
  282. throw new IllegalArgumentException("Use renderer form of setRenderer() for PRINT");
  283. case RENDER_PCL:
  284. setRenderer(new org.apache.fop.render.pcl.PCLRenderer());
  285. break;
  286. case RENDER_PS:
  287. setRenderer(new org.apache.fop.render.ps.PSRenderer());
  288. break;
  289. case RENDER_TXT:
  290. setRenderer(new org.apache.fop.render.txt.TXTRenderer());
  291. break;
  292. case RENDER_MIF:
  293. setRenderer(new org.apache.fop.render.mif.MIFRenderer());
  294. break;
  295. case RENDER_XML:
  296. setRenderer(new org.apache.fop.render.xml.XMLRenderer());
  297. break;
  298. case RENDER_SVG:
  299. setRenderer(new org.apache.fop.render.svg.SVGRenderer());
  300. break;
  301. default:
  302. throw new IllegalArgumentException("Unknown renderer type");
  303. }
  304. }
  305. /**
  306. * Set the Renderer to use
  307. * @param renderer the renderer instance to use
  308. */
  309. public void setRenderer(Renderer renderer) {
  310. renderer.setLogger(getLogger());
  311. _renderer = renderer;
  312. }
  313. public Renderer getRenderer() {
  314. return _renderer;
  315. }
  316. /**
  317. * @deprecated use renderer.setProducer(version) + setRenderer(renderer) or just setRenderer(renderer_type) which will use the default producer string.
  318. * @see #setRenderer(int)
  319. * @see #setRenderer(Renderer)
  320. */
  321. public void setRenderer(String rendererClassName, String version) {
  322. setRenderer(rendererClassName);
  323. }
  324. /**
  325. * Set the class name of the Renderer to use as well as the
  326. * producer string for those renderers that can make use of it.
  327. * @param rendererClassName classname of the renderer to use such as
  328. * "org.apache.fop.render.pdf.PDFRenderer"
  329. * @exception IllegalArgumentException if the classname was invalid.
  330. * @see #setRenderer(int)
  331. */
  332. public void setRenderer(String rendererClassName)
  333. throws IllegalArgumentException {
  334. try {
  335. _renderer =
  336. (Renderer)Class.forName(rendererClassName).newInstance();
  337. _renderer.setProducer(Version.getVersion());
  338. } catch (ClassNotFoundException e) {
  339. throw new IllegalArgumentException("Could not find "
  340. + rendererClassName);
  341. }
  342. catch (InstantiationException e) {
  343. throw new IllegalArgumentException("Could not instantiate "
  344. + rendererClassName);
  345. }
  346. catch (IllegalAccessException e) {
  347. throw new IllegalArgumentException("Could not access "
  348. + rendererClassName);
  349. }
  350. catch (ClassCastException e) {
  351. throw new IllegalArgumentException(rendererClassName
  352. + " is not a renderer");
  353. }
  354. }
  355. /**
  356. * Add the given element mapping.
  357. * An element mapping maps element names to Java classes.
  358. *
  359. * @param mapping the element mappingto add
  360. */
  361. public void addElementMapping(ElementMapping mapping) {
  362. mapping.addToBuilder(_treeBuilder);
  363. }
  364. /**
  365. * add the element mapping with the given class name
  366. */
  367. public void addElementMapping(String mappingClassName)
  368. throws IllegalArgumentException {
  369. try {
  370. ElementMapping mapping =
  371. (ElementMapping)Class.forName(mappingClassName).newInstance();
  372. addElementMapping(mapping);
  373. } catch (ClassNotFoundException e) {
  374. throw new IllegalArgumentException("Could not find "
  375. + mappingClassName);
  376. }
  377. catch (InstantiationException e) {
  378. throw new IllegalArgumentException("Could not instantiate "
  379. + mappingClassName);
  380. }
  381. catch (IllegalAccessException e) {
  382. throw new IllegalArgumentException("Could not access "
  383. + mappingClassName);
  384. }
  385. catch (ClassCastException e) {
  386. throw new IllegalArgumentException(mappingClassName
  387. + " is not an ElementMapping");
  388. }
  389. }
  390. /**
  391. * Returns the tree builder (a SAX ContentHandler).
  392. *
  393. * Used in situations where SAX is used but not via a FOP-invoked
  394. * SAX parser. A good example is an XSLT engine that fires SAX
  395. * events but isn't a SAX Parser itself.
  396. */
  397. public ContentHandler getContentHandler() {
  398. StreamRenderer streamRenderer = new StreamRenderer(_stream, _renderer);
  399. streamRenderer.setLogger(getLogger());
  400. _treeBuilder.setLogger(getLogger());
  401. _treeBuilder.setStreamRenderer(streamRenderer);
  402. return _treeBuilder;
  403. }
  404. /**
  405. * Build the formatting object tree using the given SAX Parser and
  406. * SAX InputSource
  407. */
  408. public synchronized void render(XMLReader parser, InputSource source)
  409. throws FOPException {
  410. parser.setContentHandler(getContentHandler());
  411. try {
  412. parser.parse(source);
  413. } catch (SAXException e) {
  414. if (e.getException() instanceof FOPException) {
  415. throw (FOPException)e.getException();
  416. } else {
  417. throw new FOPException(e);
  418. }
  419. }
  420. catch (IOException e) {
  421. throw new FOPException(e);
  422. }
  423. }
  424. /**
  425. * Build the formatting object tree using the given DOM Document
  426. */
  427. public synchronized void render(Document document)
  428. throws FOPException {
  429. try {
  430. DocumentInputSource source = new DocumentInputSource(document);
  431. DocumentReader reader = new DocumentReader();
  432. reader.setContentHandler(getContentHandler());
  433. reader.parse(source);
  434. } catch (SAXException e) {
  435. throw new FOPException(e);
  436. }
  437. catch (IOException e) {
  438. throw new FOPException(e);
  439. }
  440. }
  441. /**
  442. * Dumps an error
  443. */
  444. public void dumpError(Exception e) {
  445. if (_errorDump) {
  446. Logger log = getLogger();
  447. if (e instanceof SAXException) {
  448. log.error("", e);
  449. if (((SAXException)e).getException() != null) {
  450. log.error("", ((SAXException)e).getException());
  451. }
  452. } else if (e instanceof FOPException) {
  453. e.printStackTrace();
  454. if (((FOPException)e).getException() != null) {
  455. log.error("", ((FOPException)e).getException());
  456. }
  457. } else {
  458. log.error("", e);
  459. }
  460. }
  461. }
  462. /* Set up the system buffers */
  463. public void setBufferFile(File bufferFile) {
  464. this._bufferManager.addBufferFile(bufferFile);
  465. }
  466. /**
  467. * Runs the formatting and renderering process using the previously set
  468. * inputsource and outputstream
  469. */
  470. public synchronized void run() throws IOException, FOPException {
  471. if (_renderer == null) {
  472. setRenderer(RENDER_PDF);
  473. }
  474. if (_source == null) {
  475. throw new FOPException("InputSource is not set.");
  476. }
  477. if (_reader == null) {
  478. if (!(_source instanceof DocumentInputSource)) {
  479. _reader = ConfigurationReader.createParser();
  480. }
  481. }
  482. if (_source instanceof DocumentInputSource) {
  483. render(((DocumentInputSource)_source).getDocument());
  484. } else {
  485. render(_reader, _source);
  486. }
  487. }
  488. }
  489. // code stolen from org.apache.batik.util and modified slightly
  490. // does what sun.misc.Service probably does, but it cannot be relied on.
  491. // hopefully will be part of standard jdk sometime.
  492. /**
  493. * This class loads services present in the class path.
  494. */
  495. class Service {
  496. static Hashtable providerMap = new Hashtable();
  497. public static synchronized Enumeration providers(Class cls) {
  498. ClassLoader cl = cls.getClassLoader();
  499. // null if loaded by bootstrap class loader
  500. if(cl == null) {
  501. cl = ClassLoader.getSystemClassLoader();
  502. }
  503. String serviceFile = "META-INF/services/" + cls.getName();
  504. // System.out.println("File: " + serviceFile);
  505. Vector v = (Vector)providerMap.get(serviceFile);
  506. if (v != null)
  507. return v.elements();
  508. v = new Vector();
  509. providerMap.put(serviceFile, v);
  510. Enumeration e;
  511. try {
  512. e = cl.getResources(serviceFile);
  513. } catch (IOException ioe) {
  514. return v.elements();
  515. }
  516. while (e.hasMoreElements()) {
  517. try {
  518. java.net.URL u = (java.net.URL)e.nextElement();
  519. // System.out.println("URL: " + u);
  520. InputStream is = u.openStream();
  521. Reader r = new InputStreamReader(is, "UTF-8");
  522. BufferedReader br = new BufferedReader(r);
  523. String line = br.readLine();
  524. while (line != null) {
  525. try {
  526. // First strip any comment...
  527. int idx = line.indexOf('#');
  528. if (idx != -1)
  529. line = line.substring(0, idx);
  530. // Trim whitespace.
  531. line = line.trim();
  532. // If nothing left then loop around...
  533. if (line.length() == 0) {
  534. line = br.readLine();
  535. continue;
  536. }
  537. // System.out.println("Line: " + line);
  538. // Try and load the class
  539. // Object obj = cl.loadClass(line).newInstance();
  540. // stick it into our vector...
  541. v.add(line);
  542. } catch (Exception ex) {
  543. // Just try the next line
  544. }
  545. line = br.readLine();
  546. }
  547. } catch (Exception ex) {
  548. // Just try the next file...
  549. }
  550. }
  551. return v.elements();
  552. }
  553. }