InputHandler.java 12 KB

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