Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

InputHandler.java 12KB

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