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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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.apps.FopFactory;
  48. import org.apache.fop.render.awt.viewer.Renderable;
  49. /**
  50. * Class for handling files input from command line
  51. * either with XML and XSLT files (and optionally xsl
  52. * parameters) or FO File input alone.
  53. */
  54. public class InputHandler implements ErrorListener, Renderable {
  55. /** original source file */
  56. protected File sourcefile;
  57. private File stylesheet; // for XML/XSLT usage
  58. private Vector xsltParams; // for XML/XSLT usage
  59. private EntityResolver entityResolver = null;
  60. private URIResolver uriResolver = null;
  61. /** the logger */
  62. protected Log log = LogFactory.getLog(InputHandler.class);
  63. /**
  64. * Constructor for XML->XSLT->FO input
  65. *
  66. * @param xmlfile XML file
  67. * @param xsltfile XSLT file
  68. * @param params Vector of command-line parameters (name, value,
  69. * name, value, ...) for XSL stylesheet, null if none
  70. */
  71. public InputHandler(File xmlfile, File xsltfile, Vector params) {
  72. sourcefile = xmlfile;
  73. stylesheet = xsltfile;
  74. xsltParams = params;
  75. }
  76. /**
  77. * Constructor for FO input
  78. * @param fofile the file to read the FO document.
  79. */
  80. public InputHandler(File fofile) {
  81. sourcefile = fofile;
  82. }
  83. /**
  84. * Generate a document, given an initialized Fop object
  85. * @param userAgent the user agent
  86. * @param outputFormat the output format to generate (MIME type, see MimeConstants)
  87. * @param out the output stream to write the generated output to (may be null if not applicable)
  88. * @throws FOPException in case of an error during processing
  89. */
  90. public void renderTo(FOUserAgent userAgent, String outputFormat, OutputStream out)
  91. throws FOPException {
  92. FopFactory factory = userAgent.getFactory();
  93. Fop fop;
  94. if (out != null) {
  95. fop = factory.newFop(outputFormat, userAgent, out);
  96. } else {
  97. fop = factory.newFop(outputFormat, userAgent);
  98. }
  99. // if base URL was not explicitly set in FOUserAgent, obtain here
  100. if (fop.getUserAgent().getBaseURL() == null && sourcefile != null) {
  101. String baseURL = null;
  102. try {
  103. baseURL = new File(sourcefile.getAbsolutePath()).
  104. getParentFile().toURI().toURL().toExternalForm();
  105. } catch (Exception e) {
  106. baseURL = "";
  107. }
  108. fop.getUserAgent().setBaseURL(baseURL);
  109. }
  110. // Resulting SAX events (the generated FO) must be piped through to FOP
  111. Result res = new SAXResult(fop.getDefaultHandler());
  112. transformTo(res);
  113. }
  114. /** {@inheritDoc} */
  115. public void renderTo(FOUserAgent userAgent, String outputFormat) throws FOPException {
  116. renderTo(userAgent, outputFormat, null);
  117. }
  118. /**
  119. * In contrast to render(Fop) this method only performs the XSLT stage and saves the
  120. * intermediate XSL-FO file to the output file.
  121. * @param out OutputStream to write the transformation result to.
  122. * @throws FOPException in case of an error during processing
  123. */
  124. public void transformTo(OutputStream out) throws FOPException {
  125. Result res = new StreamResult(out);
  126. transformTo(res);
  127. }
  128. /**
  129. * Creates a Source for the main input file. Processes XInclude if
  130. * available in the XML parser.
  131. *
  132. * @return the Source for the main input file
  133. */
  134. protected Source createMainSource() {
  135. Source source;
  136. InputStream in;
  137. String uri;
  138. if (this.sourcefile != null) {
  139. try {
  140. in = new java.io.FileInputStream(this.sourcefile);
  141. uri = this.sourcefile.toURI().toASCIIString();
  142. } catch (FileNotFoundException e) {
  143. //handled elsewhere
  144. return new StreamSource(this.sourcefile);
  145. }
  146. } else {
  147. in = System.in;
  148. uri = null;
  149. }
  150. try {
  151. InputSource is = new InputSource(in);
  152. is.setSystemId(uri);
  153. XMLReader xr = getXMLReader();
  154. if (entityResolver != null) {
  155. xr.setEntityResolver(entityResolver);
  156. }
  157. source = new SAXSource(xr, is);
  158. } catch (SAXException e) {
  159. if (this.sourcefile != null) {
  160. source = new StreamSource(this.sourcefile);
  161. } else {
  162. source = new StreamSource(in, uri);
  163. }
  164. } catch (ParserConfigurationException e) {
  165. if (this.sourcefile != null) {
  166. source = new StreamSource(this.sourcefile);
  167. } else {
  168. source = new StreamSource(in, uri);
  169. }
  170. }
  171. return source;
  172. }
  173. /**
  174. * Creates a catalog resolver and uses it for XML parsing and XSLT URI resolution.
  175. * Tries the Apache Commons Resolver, and if unsuccessful,
  176. * tries the same built into Java 6.
  177. * @param userAgent the user agent instance
  178. */
  179. public void createCatalogResolver(FOUserAgent userAgent) {
  180. String[] classNames = new String[] {
  181. "org.apache.xml.resolver.tools.CatalogResolver",
  182. "com.sun.org.apache.xml.internal.resolver.tools.CatalogResolver"};
  183. ResourceEventProducer eventProducer
  184. = ResourceEventProducer.Provider.get(userAgent.getEventBroadcaster());
  185. Class resolverClass = null;
  186. for (int i = 0; i < classNames.length && resolverClass == null; ++i) {
  187. try {
  188. resolverClass = Class.forName(classNames[i]);
  189. } catch (ClassNotFoundException e) {
  190. // No worries
  191. }
  192. }
  193. if (resolverClass == null) {
  194. eventProducer.catalogResolverNotFound(this);
  195. return;
  196. }
  197. try {
  198. entityResolver = (EntityResolver) resolverClass.newInstance();
  199. uriResolver = (URIResolver) resolverClass.newInstance();
  200. } catch (InstantiationException e) {
  201. log.error("Error creating the catalog resolver: " + e.getMessage());
  202. eventProducer.catalogResolverNotCreated(this, e.getMessage());
  203. } catch (IllegalAccessException e) {
  204. log.error("Error creating the catalog resolver: " + e.getMessage());
  205. eventProducer.catalogResolverNotCreated(this, e.getMessage());
  206. }
  207. }
  208. /**
  209. * Creates a Source for the selected stylesheet.
  210. *
  211. * @return the Source for the selected stylesheet or null if there's no stylesheet
  212. */
  213. protected Source createXSLTSource() {
  214. Source xslt = null;
  215. if (this.stylesheet != null) {
  216. if (entityResolver != null) {
  217. try {
  218. InputSource is = new InputSource(this.stylesheet.getPath());
  219. XMLReader xr = getXMLReader();
  220. xr.setEntityResolver(entityResolver);
  221. xslt = new SAXSource(xr, is);
  222. } catch (SAXException e) {
  223. // return StreamSource
  224. } catch (ParserConfigurationException e) {
  225. // return StreamSource
  226. }
  227. }
  228. if (xslt == null) {
  229. xslt = new StreamSource(this.stylesheet);
  230. }
  231. }
  232. return xslt;
  233. }
  234. private XMLReader getXMLReader() throws ParserConfigurationException, SAXException {
  235. SAXParserFactory spf = SAXParserFactory.newInstance();
  236. spf.setFeature("http://xml.org/sax/features/namespaces", true);
  237. spf.setFeature("http://apache.org/xml/features/xinclude", true);
  238. XMLReader xr = spf.newSAXParser().getXMLReader();
  239. return xr;
  240. }
  241. /**
  242. * Transforms the input document to the input format expected by FOP using XSLT.
  243. * @param result the Result object where the result of the XSL transformation is sent to
  244. * @throws FOPException in case of an error during processing
  245. */
  246. protected void transformTo(Result result) throws FOPException {
  247. try {
  248. // Setup XSLT
  249. TransformerFactory factory = TransformerFactory.newInstance();
  250. Transformer transformer;
  251. Source xsltSource = createXSLTSource();
  252. if (xsltSource == null) { // FO Input
  253. transformer = factory.newTransformer();
  254. } else { // XML/XSLT input
  255. transformer = factory.newTransformer(xsltSource);
  256. // Set the value of parameters, if any, defined for stylesheet
  257. if (xsltParams != null) {
  258. for (int i = 0; i < xsltParams.size(); i += 2) {
  259. transformer.setParameter((String) xsltParams.elementAt(i),
  260. (String) xsltParams.elementAt(i + 1));
  261. }
  262. }
  263. if (uriResolver != null) {
  264. transformer.setURIResolver(uriResolver);
  265. }
  266. }
  267. transformer.setErrorListener(this);
  268. // Create a SAXSource from the input Source file
  269. Source src = createMainSource();
  270. // Start XSLT transformation and FOP processing
  271. transformer.transform(src, result);
  272. } catch (Exception e) {
  273. throw new FOPException(e);
  274. }
  275. }
  276. // --- Implementation of the ErrorListener interface ---
  277. /**
  278. * {@inheritDoc}
  279. */
  280. public void warning(TransformerException exc) {
  281. log.warn(exc.getLocalizedMessage());
  282. }
  283. /**
  284. * {@inheritDoc}
  285. */
  286. public void error(TransformerException exc) {
  287. log.error(exc.toString());
  288. }
  289. /**
  290. * {@inheritDoc}
  291. */
  292. public void fatalError(TransformerException exc)
  293. throws TransformerException {
  294. throw exc;
  295. }
  296. }