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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. */
  178. public void createCatalogResolver(FOUserAgent userAgent) {
  179. String[] classNames = new String[] {
  180. "org.apache.xml.resolver.tools.CatalogResolver",
  181. "com.sun.org.apache.xml.internal.resolver.tools.CatalogResolver"};
  182. ResourceEventProducer eventProducer =
  183. ResourceEventProducer.Provider.get(userAgent.getEventBroadcaster());
  184. Class resolverClass = null;
  185. for (int i = 0; i < classNames.length && resolverClass == null; ++i) {
  186. try {
  187. resolverClass = Class.forName(classNames[i]);
  188. } catch (ClassNotFoundException e) {
  189. // No worries
  190. }
  191. }
  192. if (resolverClass == null) {
  193. eventProducer.catalogResolverNotFound(this);
  194. return;
  195. }
  196. try {
  197. entityResolver = (EntityResolver) resolverClass.newInstance();
  198. uriResolver = (URIResolver) resolverClass.newInstance();
  199. } catch (InstantiationException e) {
  200. log.error("Error creating the catalog resolver: " + e.getMessage());
  201. eventProducer.catalogResolverNotCreated(this, e.getMessage());
  202. } catch (IllegalAccessException e) {
  203. log.error("Error creating the catalog resolver: " + e.getMessage());
  204. eventProducer.catalogResolverNotCreated(this, e.getMessage());
  205. }
  206. }
  207. /**
  208. * Creates a Source for the selected stylesheet.
  209. *
  210. * @return the Source for the selected stylesheet or null if there's no stylesheet
  211. */
  212. protected Source createXSLTSource() {
  213. Source xslt = null;
  214. if (this.stylesheet != null) {
  215. if (entityResolver != null) {
  216. try {
  217. InputSource is = new InputSource(this.stylesheet.getPath());
  218. XMLReader xr = getXMLReader();
  219. xr.setEntityResolver(entityResolver);
  220. xslt = new SAXSource(xr, is);
  221. } catch (SAXException e) {
  222. // return StreamSource
  223. } catch (ParserConfigurationException e) {
  224. // return StreamSource
  225. }
  226. }
  227. if (xslt == null) {
  228. xslt = new StreamSource(this.stylesheet);
  229. }
  230. }
  231. return xslt;
  232. }
  233. private XMLReader getXMLReader() throws ParserConfigurationException, SAXException {
  234. SAXParserFactory spf = SAXParserFactory.newInstance();
  235. spf.setFeature("http://xml.org/sax/features/namespaces", true);
  236. spf.setFeature("http://apache.org/xml/features/xinclude", true);
  237. XMLReader xr = spf.newSAXParser().getXMLReader();
  238. return xr;
  239. }
  240. /**
  241. * Transforms the input document to the input format expected by FOP using XSLT.
  242. * @param result the Result object where the result of the XSL transformation is sent to
  243. * @throws FOPException in case of an error during processing
  244. */
  245. protected void transformTo(Result result) throws FOPException {
  246. try {
  247. // Setup XSLT
  248. TransformerFactory factory = TransformerFactory.newInstance();
  249. Transformer transformer;
  250. Source xsltSource = createXSLTSource();
  251. if (xsltSource == null) { // FO Input
  252. transformer = factory.newTransformer();
  253. } else { // XML/XSLT input
  254. transformer = factory.newTransformer(xsltSource);
  255. // Set the value of parameters, if any, defined for stylesheet
  256. if (xsltParams != null) {
  257. for (int i = 0; i < xsltParams.size(); i += 2) {
  258. transformer.setParameter((String) xsltParams.elementAt(i),
  259. (String) xsltParams.elementAt(i + 1));
  260. }
  261. }
  262. if (uriResolver != null) {
  263. transformer.setURIResolver(uriResolver);
  264. }
  265. }
  266. transformer.setErrorListener(this);
  267. // Create a SAXSource from the input Source file
  268. Source src = createMainSource();
  269. // Start XSLT transformation and FOP processing
  270. transformer.transform(src, result);
  271. } catch (Exception e) {
  272. throw new FOPException(e);
  273. }
  274. }
  275. // --- Implementation of the ErrorListener interface ---
  276. /**
  277. * {@inheritDoc}
  278. */
  279. public void warning(TransformerException exc) {
  280. log.warn(exc.getLocalizedMessage());
  281. }
  282. /**
  283. * {@inheritDoc}
  284. */
  285. public void error(TransformerException exc) {
  286. log.error(exc.toString());
  287. }
  288. /**
  289. * {@inheritDoc}
  290. */
  291. public void fatalError(TransformerException exc)
  292. throws TransformerException {
  293. throw exc;
  294. }
  295. }