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.

ExampleEvents.java 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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 embedding.events;
  19. import java.io.BufferedOutputStream;
  20. import java.io.File;
  21. import java.io.FileNotFoundException;
  22. import java.io.FileOutputStream;
  23. import java.io.IOException;
  24. import java.io.OutputStream;
  25. import java.net.URL;
  26. import javax.xml.transform.Result;
  27. import javax.xml.transform.Source;
  28. import javax.xml.transform.Transformer;
  29. import javax.xml.transform.TransformerException;
  30. import javax.xml.transform.TransformerFactory;
  31. import javax.xml.transform.sax.SAXResult;
  32. import javax.xml.transform.stream.StreamSource;
  33. import org.xml.sax.SAXException;
  34. import org.apache.commons.io.IOUtils;
  35. import org.apache.fop.apps.FOPException;
  36. import org.apache.fop.apps.FOUserAgent;
  37. import org.apache.fop.apps.Fop;
  38. import org.apache.fop.apps.FopFactory;
  39. import org.apache.fop.apps.MimeConstants;
  40. import org.apache.fop.events.Event;
  41. import org.apache.fop.events.EventFormatter;
  42. import org.apache.fop.events.EventListener;
  43. import org.apache.fop.events.model.EventSeverity;
  44. /**
  45. * This class demonstrates how to register an event listener with FOP so you can customize
  46. * FOP's error behaviour.
  47. */
  48. public class ExampleEvents {
  49. // configure fopFactory as desired
  50. private FopFactory fopFactory = FopFactory.newInstance();
  51. /**
  52. * Converts an FO file to a PDF file using FOP
  53. * @param fo the FO file
  54. * @param pdf the target PDF file
  55. * @throws IOException In case of an I/O problem
  56. * @throws FOPException In case of a FOP problem
  57. * @throws TransformerException In case of a problem with XSLT
  58. */
  59. public void convertFO2PDF(URL fo, File pdf)
  60. throws IOException, FOPException, TransformerException {
  61. OutputStream out = null;
  62. try {
  63. //Create the user agent for this processing run
  64. FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
  65. //Adding a simple logging listener that writes to stdout and stderr
  66. foUserAgent.getEventBroadcaster().addEventListener(new SysOutEventListener());
  67. // Add your own event listener
  68. foUserAgent.getEventBroadcaster().addEventListener(new MyEventListener());
  69. // configure foUserAgent further as desired
  70. // Setup output stream. Note: Using BufferedOutputStream
  71. // for performance reasons (helpful with FileOutputStreams).
  72. out = new FileOutputStream(pdf);
  73. out = new BufferedOutputStream(out);
  74. // Construct fop with desired output format
  75. Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
  76. // Setup JAXP using identity transformer
  77. TransformerFactory factory = TransformerFactory.newInstance();
  78. Transformer transformer = factory.newTransformer(); // identity transformer
  79. // Setup input stream
  80. Source src = new StreamSource(fo.toExternalForm());
  81. // Resulting SAX events (the generated FO) must be piped through to FOP
  82. Result res = new SAXResult(fop.getDefaultHandler());
  83. // Start XSLT transformation and FOP processing
  84. transformer.transform(src, res);
  85. } finally {
  86. IOUtils.closeQuietly(out);
  87. }
  88. }
  89. private static class MyEventListener implements EventListener {
  90. public void processEvent(Event event) {
  91. if ("org.apache.fop.events.ResourceEventProducer.imageNotFound"
  92. .equals(event.getEventID())) {
  93. //Get the FileNotFoundException that's part of the event's parameters
  94. FileNotFoundException fnfe = (FileNotFoundException)event.getParam("fnfe");
  95. System.out.println("---=== imageNotFound Event for " + event.getParam("uri")
  96. + "!!! ===---");
  97. //Stop processing when an image could not be found. Otherwise, FOP would just
  98. //continue without the image!
  99. System.out.println("Throwing a RuntimeException...");
  100. throw new RuntimeException(EventFormatter.format(event), fnfe);
  101. } else {
  102. //ignore all other events
  103. }
  104. }
  105. }
  106. /** A simple event listener that writes the events to stdout and sterr. */
  107. private static class SysOutEventListener implements EventListener {
  108. /** {@inheritDoc} */
  109. public void processEvent(Event event) {
  110. String msg = EventFormatter.format(event);
  111. EventSeverity severity = event.getSeverity();
  112. if (severity == EventSeverity.INFO) {
  113. System.out.println("[INFO ] " + msg);
  114. } else if (severity == EventSeverity.WARN) {
  115. System.out.println("[WARN ] " + msg);
  116. } else if (severity == EventSeverity.ERROR) {
  117. System.err.println("[ERROR] " + msg);
  118. } else if (severity == EventSeverity.FATAL) {
  119. System.err.println("[FATAL] " + msg);
  120. } else {
  121. assert false;
  122. }
  123. }
  124. }
  125. /**
  126. * This method extracts the original exception from some exception. The exception
  127. * might be nested multiple levels deep.
  128. * @param t the Throwable to inspect
  129. * @return the original Throwable or the method parameter t if there are no nested Throwables.
  130. */
  131. private static Throwable getOriginalThrowable(Throwable t) {
  132. if (t instanceof SAXException) {
  133. SAXException saxe = (SAXException)t;
  134. if (saxe.getException() != null) {
  135. return getOriginalThrowable(saxe.getException());
  136. } else {
  137. return saxe;
  138. }
  139. } else {
  140. if (t.getCause() != null) {
  141. return getOriginalThrowable(t.getCause());
  142. } else {
  143. return t;
  144. }
  145. }
  146. }
  147. /**
  148. * Main method.
  149. * @param args command-line arguments
  150. */
  151. public static void main(String[] args) {
  152. try {
  153. System.out.println("FOP ExampleEvents\n");
  154. System.out.println("Preparing...");
  155. //Setup directories
  156. File baseDir = new File(".");
  157. File outDir = new File(baseDir, "out");
  158. outDir.mkdirs();
  159. //Setup input and output files
  160. URL fo = ExampleEvents.class.getResource("missing-image.fo");
  161. File pdffile = new File(outDir, "out.pdf");
  162. System.out.println("Input: XSL-FO (" + fo.toExternalForm() + ")");
  163. System.out.println("Output: PDF (" + pdffile + ")");
  164. System.out.println();
  165. System.out.println("Transforming...");
  166. ExampleEvents app = new ExampleEvents();
  167. try {
  168. app.convertFO2PDF(fo, pdffile);
  169. } catch (TransformerException te) {
  170. //Note: We don't get the original exception here!
  171. //FOP needs to embed the exception in a SAXException and the TraX transformer
  172. //again wraps the SAXException in a TransformerException. Even our own
  173. //RuntimeException just wraps the original FileNotFoundException.
  174. //So we need to unpack to get the original exception (about three layers deep).
  175. Throwable originalThrowable = getOriginalThrowable(te);
  176. originalThrowable.printStackTrace(System.err);
  177. System.out.println("Aborted!");
  178. System.exit(-1);
  179. }
  180. System.out.println("Success!");
  181. } catch (Exception e) {
  182. //Some other error (shouldn't happen in this example)
  183. e.printStackTrace(System.err);
  184. System.exit(-1);
  185. }
  186. }
  187. }