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.

InputHandler.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /* $Id$ */
  18. package org.apache.fop.cli;
  19. import java.io.File;
  20. import java.io.FileNotFoundException;
  21. import java.io.InputStream;
  22. import java.io.OutputStream;
  23. import java.util.Vector;
  24. import javax.xml.parsers.ParserConfigurationException;
  25. import javax.xml.parsers.SAXParserFactory;
  26. import javax.xml.transform.ErrorListener;
  27. import javax.xml.transform.Result;
  28. import javax.xml.transform.Source;
  29. import javax.xml.transform.Transformer;
  30. import javax.xml.transform.TransformerException;
  31. import javax.xml.transform.TransformerFactory;
  32. import javax.xml.transform.URIResolver;
  33. import javax.xml.transform.sax.SAXResult;
  34. import javax.xml.transform.sax.SAXSource;
  35. import javax.xml.transform.stream.StreamResult;
  36. import javax.xml.transform.stream.StreamSource;
  37. import org.xml.sax.EntityResolver;
  38. import org.xml.sax.InputSource;
  39. import org.xml.sax.SAXException;
  40. import org.xml.sax.XMLReader;
  41. import org.apache.commons.logging.Log;
  42. import org.apache.commons.logging.LogFactory;
  43. import org.apache.fop.ResourceEventProducer;
  44. import org.apache.fop.apps.FOPException;
  45. import org.apache.fop.apps.FOUserAgent;
  46. import org.apache.fop.apps.Fop;
  47. import org.apache.fop.render.awt.viewer.Renderable;
  48. /**
  49. * Class for handling files input from command line
  50. * either with XML and XSLT files (and optionally xsl
  51. * parameters) or FO File input alone.
  52. */
  53. public class InputHandler implements ErrorListener, Renderable {
  54. /** original source file */
  55. protected File sourcefile;
  56. private File stylesheet; // for XML/XSLT usage
  57. private Vector xsltParams; // for XML/XSLT usage
  58. private EntityResolver entityResolver;
  59. private URIResolver uriResolver;
  60. /** the logger */
  61. protected Log log = LogFactory.getLog(InputHandler.class);
  62. /**
  63. * Constructor for XML->XSLT->FO input
  64. *
  65. * @param xmlfile XML file
  66. * @param xsltfile XSLT file
  67. * @param params Vector of command-line parameters (name, value,
  68. * name, value, ...) for XSL stylesheet, null if none
  69. */
  70. public InputHandler(File xmlfile, File xsltfile, Vector params) {
  71. sourcefile = xmlfile;
  72. stylesheet = xsltfile;
  73. xsltParams = params;
  74. }
  75. /**
  76. * Constructor for FO input
  77. * @param fofile the file to read the FO document.
  78. */
  79. public InputHandler(File fofile) {
  80. sourcefile = fofile;
  81. }
  82. /**
  83. * Generate a document, given an initialized Fop object
  84. * @param userAgent the user agent
  85. * @param outputFormat the output format to generate (MIME type, see MimeConstants)
  86. * @param out the output stream to write the generated output to (may be null if not applicable)
  87. * @throws FOPException in case of an error during processing
  88. */
  89. public void renderTo(FOUserAgent userAgent, String outputFormat, OutputStream out)
  90. throws FOPException {
  91. Fop fop;
  92. if (out != null) {
  93. fop = userAgent.newFop(outputFormat, out);
  94. } else {
  95. fop = userAgent.newFop(outputFormat);
  96. }
  97. // Resulting SAX events (the generated FO) must be piped through to FOP
  98. Result res = new SAXResult(fop.getDefaultHandler());
  99. transformTo(res);
  100. }
  101. /** {@inheritDoc} */
  102. public void renderTo(FOUserAgent userAgent, String outputFormat) throws FOPException {
  103. renderTo(userAgent, outputFormat, null);
  104. }
  105. /**
  106. * In contrast to render(Fop) this method only performs the XSLT stage and saves the
  107. * intermediate XSL-FO file to the output file.
  108. * @param out OutputStream to write the transformation result to.
  109. * @throws FOPException in case of an error during processing
  110. */
  111. public void transformTo(OutputStream out) throws FOPException {
  112. Result res = new StreamResult(out);
  113. transformTo(res);
  114. }
  115. /**
  116. * Creates a Source for the main input file. Processes XInclude if
  117. * available in the XML parser.
  118. *
  119. * @return the Source for the main input file
  120. */
  121. protected Source createMainSource() {
  122. Source source;
  123. InputStream in;
  124. String uri;
  125. if (this.sourcefile != null) {
  126. try {
  127. in = new java.io.FileInputStream(this.sourcefile);
  128. uri = this.sourcefile.toURI().toASCIIString();
  129. } catch (FileNotFoundException e) {
  130. //handled elsewhere
  131. return new StreamSource(this.sourcefile);
  132. }
  133. } else {
  134. in = System.in;
  135. uri = null;
  136. }
  137. try {
  138. InputSource is = new InputSource(in);
  139. is.setSystemId(uri);
  140. XMLReader xr = getXMLReader();
  141. if (entityResolver != null) {
  142. xr.setEntityResolver(entityResolver);
  143. }
  144. source = new SAXSource(xr, is);
  145. } catch (SAXException e) {
  146. if (this.sourcefile != null) {
  147. source = new StreamSource(this.sourcefile);
  148. } else {
  149. source = new StreamSource(in, uri);
  150. }
  151. } catch (ParserConfigurationException e) {
  152. if (this.sourcefile != null) {
  153. source = new StreamSource(this.sourcefile);
  154. } else {
  155. source = new StreamSource(in, uri);
  156. }
  157. }
  158. return source;
  159. }
  160. /**
  161. * Creates a catalog resolver and uses it for XML parsing and XSLT URI resolution.
  162. * Tries the Apache Commons Resolver, and if unsuccessful,
  163. * tries the same built into Java 6.
  164. * @param userAgent the user agent instance
  165. */
  166. public void createCatalogResolver(FOUserAgent userAgent) {
  167. String[] classNames = new String[] {
  168. "org.apache.xml.resolver.tools.CatalogResolver",
  169. "com.sun.org.apache.xml.internal.resolver.tools.CatalogResolver"};
  170. ResourceEventProducer eventProducer
  171. = ResourceEventProducer.Provider.get(userAgent.getEventBroadcaster());
  172. Class resolverClass = null;
  173. for (int i = 0; i < classNames.length && resolverClass == null; ++i) {
  174. try {
  175. resolverClass = Class.forName(classNames[i]);
  176. } catch (ClassNotFoundException e) {
  177. // No worries
  178. }
  179. }
  180. if (resolverClass == null) {
  181. eventProducer.catalogResolverNotFound(this);
  182. return;
  183. }
  184. try {
  185. entityResolver = (EntityResolver) resolverClass.newInstance();
  186. uriResolver = (URIResolver) resolverClass.newInstance();
  187. } catch (InstantiationException e) {
  188. log.error("Error creating the catalog resolver: " + e.getMessage());
  189. eventProducer.catalogResolverNotCreated(this, e.getMessage());
  190. } catch (IllegalAccessException e) {
  191. log.error("Error creating the catalog resolver: " + e.getMessage());
  192. eventProducer.catalogResolverNotCreated(this, e.getMessage());
  193. }
  194. }
  195. /**
  196. * Creates a Source for the selected stylesheet.
  197. *
  198. * @return the Source for the selected stylesheet or null if there's no stylesheet
  199. */
  200. protected Source createXSLTSource() {
  201. Source xslt = null;
  202. if (this.stylesheet != null) {
  203. if (entityResolver != null) {
  204. try {
  205. InputSource is = new InputSource(this.stylesheet.getPath());
  206. XMLReader xr = getXMLReader();
  207. xr.setEntityResolver(entityResolver);
  208. xslt = new SAXSource(xr, is);
  209. } catch (SAXException e) {
  210. // return StreamSource
  211. } catch (ParserConfigurationException e) {
  212. // return StreamSource
  213. }
  214. }
  215. if (xslt == null) {
  216. xslt = new StreamSource(this.stylesheet);
  217. }
  218. }
  219. return xslt;
  220. }
  221. private XMLReader getXMLReader() throws ParserConfigurationException, SAXException {
  222. SAXParserFactory spf = SAXParserFactory.newInstance();
  223. spf.setFeature("http://xml.org/sax/features/namespaces", true);
  224. spf.setFeature("http://apache.org/xml/features/xinclude", true);
  225. XMLReader xr = spf.newSAXParser().getXMLReader();
  226. return xr;
  227. }
  228. /**
  229. * Transforms the input document to the input format expected by FOP using XSLT.
  230. * @param result the Result object where the result of the XSL transformation is sent to
  231. * @throws FOPException in case of an error during processing
  232. */
  233. protected void transformTo(Result result) throws FOPException {
  234. try {
  235. // Setup XSLT
  236. TransformerFactory factory = TransformerFactory.newInstance();
  237. Transformer transformer;
  238. Source xsltSource = createXSLTSource();
  239. if (xsltSource == null) { // FO Input
  240. transformer = factory.newTransformer();
  241. } else { // XML/XSLT input
  242. transformer = factory.newTransformer(xsltSource);
  243. // Set the value of parameters, if any, defined for stylesheet
  244. if (xsltParams != null) {
  245. for (int i = 0; i < xsltParams.size(); i += 2) {
  246. transformer.setParameter((String) xsltParams.elementAt(i),
  247. (String) xsltParams.elementAt(i + 1));
  248. }
  249. }
  250. if (uriResolver != null) {
  251. transformer.setURIResolver(uriResolver);
  252. }
  253. }
  254. transformer.setErrorListener(this);
  255. // Create a SAXSource from the input Source file
  256. Source src = createMainSource();
  257. // Start XSLT transformation and FOP processing
  258. transformer.transform(src, result);
  259. } catch (Exception e) {
  260. throw new FOPException(e);
  261. }
  262. }
  263. // --- Implementation of the ErrorListener interface ---
  264. /**
  265. * {@inheritDoc}
  266. */
  267. public void warning(TransformerException exc) {
  268. log.warn(exc.getLocalizedMessage());
  269. }
  270. /**
  271. * {@inheritDoc}
  272. */
  273. public void error(TransformerException exc) {
  274. log.error(exc.toString());
  275. }
  276. /**
  277. * {@inheritDoc}
  278. */
  279. public void fatalError(TransformerException exc)
  280. throws TransformerException {
  281. throw exc;
  282. }
  283. }