Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

Driver.java 19KB

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