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

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