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.

events.xml 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!--
  3. Licensed to the Apache Software Foundation (ASF) under one or more
  4. contributor license agreements. See the NOTICE file distributed with
  5. this work for additional information regarding copyright ownership.
  6. The ASF licenses this file to You under the Apache License, Version 2.0
  7. (the "License"); you may not use this file except in compliance with
  8. the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing, software
  11. distributed under the License is distributed on an "AS IS" BASIS,
  12. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. See the License for the specific language governing permissions and
  14. limitations under the License.
  15. -->
  16. <!-- $Id$ -->
  17. <!DOCTYPE document PUBLIC "-//APACHE//DTD Documentation V2.0//EN" "http://forrest.apache.org/dtd/document-v20.dtd">
  18. <document>
  19. <header>
  20. <title>Apache™ FOP: Events/Processing Feedback</title>
  21. <version>$Revision$</version>
  22. </header>
  23. <body>
  24. <section id="introduction">
  25. <title>Introduction</title>
  26. <p>
  27. In versions until 0.20.5, Apache™ FOP used
  28. <a href="http://excalibur.apache.org/framework/index.html">Avalon-style Logging</a> where
  29. it was possible to supply a logger per processing run. During the redesign
  30. the logging infrastructure was switched over to
  31. <a href="http://commons.apache.org/logging/">Commons Logging</a> which is (like Log4J or
  32. java.util.logging) a "static" logging framework (the logger is accessed through static
  33. variables). This made it very difficult in a multi-threaded system to retrieve information
  34. for a single processing run.
  35. </p>
  36. <p>
  37. With FOP's event subsystem, we'd like to close this gap again and even go further. The
  38. first point is to realize that we have two kinds of "logging". Firstly, we have the logging
  39. infrastructure for the (FOP) developer who needs to be able to enable finer log messages
  40. for certain parts of FOP to track down a certain problem. Secondly, we have the user who
  41. would like to be informed about missing images, overflowing lines or substituted fonts.
  42. These messages (or events) are targeted at less technical people and may ideally be
  43. localized (translated). Furthermore, tool and solution builders would like to integrate
  44. FOP into their own solutions. For example, an FO editor should be able to point the user
  45. to the right place where a particular problem occurred while developing a document template.
  46. Finally, some integrators would like to abort processing if a resource (an image or a font)
  47. has not been found, while others would simply continue. The event system allows to
  48. react on these events.
  49. </p>
  50. <p>
  51. On this page, we won't discuss logging as such. We will show how the event subsystem can
  52. be used for various tasks. We'll first look at the event subsystem from the consumer side.
  53. Finally, the production of events inside FOP will be discussed (this is mostly interesting
  54. for FOP developers only).
  55. </p>
  56. </section>
  57. <section id="consumer">
  58. <title>The consumer side</title>
  59. <p>
  60. The event subsystem is located in the <code>org.apache.fop.events</code> package and its
  61. base is the <code>Event</code> class. An instance is created for each event and is sent
  62. to a set of <code>EventListener</code> instances by the <code>EventBroadcaster</code>.
  63. An <code>Event</code> contains:
  64. </p>
  65. <ul>
  66. <li>an event ID,</li>
  67. <li>a source object (which generated the event),</li>
  68. <li>a severity level (Info, Warning, Error and Fatal Error) and</li>
  69. <li>a map of named parameters.</li>
  70. </ul>
  71. <p>
  72. The <code>EventFormatter</code> class can be used to translate the events into
  73. human-readable, localized messages.
  74. </p>
  75. <p>
  76. A full example of what is shown here can be found in the
  77. <code>examples/embedding/java/embedding/events</code> directory in the FOP distribution.
  78. The example can also be accessed
  79. <a href="http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/examples/embedding/java/embedding/events/">via the web</a>.
  80. </p>
  81. <section id="write-listener">
  82. <title>Writing an EventListener</title>
  83. <p>
  84. The following code sample shows a very simple EventListener. It basically just sends
  85. all events to System.out (stdout) or System.err (stderr) depending on the event severity.
  86. </p>
  87. <source><![CDATA[import org.apache.fop.events.Event;
  88. import org.apache.fop.events.EventFormatter;
  89. import org.apache.fop.events.EventListener;
  90. import org.apache.fop.events.model.EventSeverity;
  91. /** A simple event listener that writes the events to stdout and stderr. */
  92. public class SysOutEventListener implements EventListener {
  93. /** {@inheritDoc} */
  94. public void processEvent(Event event) {
  95. String msg = EventFormatter.format(event);
  96. EventSeverity severity = event.getSeverity();
  97. if (severity == EventSeverity.INFO) {
  98. System.out.println("[INFO ] " + msg);
  99. } else if (severity == EventSeverity.WARN) {
  100. System.out.println("[WARN ] " + msg);
  101. } else if (severity == EventSeverity.ERROR) {
  102. System.err.println("[ERROR] " + msg);
  103. } else if (severity == EventSeverity.FATAL) {
  104. System.err.println("[FATAL] " + msg);
  105. } else {
  106. assert false;
  107. }
  108. }
  109. }]]></source>
  110. <p>
  111. You can see that for every event the method <code>processEvent</code> of the
  112. <code>EventListener</code> will be called. Inside this method you can do whatever
  113. processing you would like including throwing a <code>RuntimeException</code>, if you want
  114. to abort the current processing run.
  115. </p>
  116. <p>
  117. The code above also shows how you can turn an event into a human-readable, localized
  118. message that can be presented to a user. The <code>EventFormatter</code> class does
  119. this for you. It provides additional methods if you'd like to explicitly specify
  120. the locale.
  121. </p>
  122. <p>
  123. It is possible to gather all events for a whole processing run so they can be
  124. evaluated afterwards. However, care should be taken about memory consumption since
  125. the events provide references to objects inside FOP which may themselves have
  126. references to other objects. So holding on to these objects may mean that whole
  127. object trees cannot be released!
  128. </p>
  129. </section>
  130. <section id="add-listener">
  131. <title>Adding an EventListener</title>
  132. <p>
  133. To register the event listener with FOP, get the <code>EventBroadcaster</code> which
  134. is associated with the user agent (<code>FOUserAgent</code>) and add it there:
  135. </p>
  136. <source><![CDATA[FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
  137. foUserAgent.getEventBroadcaster().addEventListener(new SysOutEventListener());]]></source>
  138. <p>
  139. Please note that this is done separately for each processing run, i.e. for each
  140. new user agent.
  141. </p>
  142. </section>
  143. <section id="listener-example1">
  144. <title>An additional listener example</title>
  145. <p>
  146. Here's an additional example of an event listener:
  147. </p>
  148. <p>
  149. By default, FOP continues processing even if an image wasn't found. If you have
  150. more strict requirements and want FOP to stop if an image is not available, you can
  151. do something like the following in the simplest case:
  152. </p>
  153. <source><![CDATA[public class MyEventListener implements EventListener {
  154. public void processEvent(Event event) {
  155. if ("org.apache.fop.ResourceEventProducer".equals(
  156. event.getEventGroupID())) {
  157. event.setSeverity(EventSeverity.FATAL);
  158. } else {
  159. //ignore all other events (or do something of your choice)
  160. }
  161. }
  162. }]]></source>
  163. <p>
  164. Increasing the event severity to FATAL will signal the event broadcaster to throw
  165. an exception and stop further processing. In the above case, all resource-related
  166. events will cause FOP to stop processing.
  167. </p>
  168. <p>
  169. You can also customize the exception to throw (you can may throw a RuntimeException
  170. or subclass yourself) and/or which event to respond to:
  171. </p>
  172. <source><![CDATA[public class MyEventListener implements EventListener {
  173. public void processEvent(Event event) {
  174. if ("org.apache.fop.ResourceEventProducer.imageNotFound"
  175. .equals(event.getEventID())) {
  176. //Get the FileNotFoundException that's part of the event's parameters
  177. FileNotFoundException fnfe = (FileNotFoundException)event.getParam("fnfe");
  178. throw new RuntimeException(EventFormatter.format(event), fnfe);
  179. } else {
  180. //ignore all other events (or do something of your choice)
  181. }
  182. }
  183. }]]></source>
  184. <p>
  185. This throws a <code>RuntimeException</code> with the <code>FileNotFoundException</code>
  186. as the cause. Further processing effectively stops in FOP. You can catch the exception
  187. in your code and react as you see necessary.
  188. </p>
  189. </section>
  190. </section>
  191. <section id="producer">
  192. <title>The producer side (for FOP developers)</title>
  193. <p>
  194. This section is primarily for FOP and FOP plug-in developers. It describes how to use
  195. the event subsystem for producing events.
  196. </p>
  197. <note>
  198. The event package has been designed in order to be theoretically useful for use cases
  199. outside FOP. If you think this is interesting independently from FOP, please talk to
  200. <a href="mailto:fop-dev@xmlgraphics.apache.org">us</a>.
  201. </note>
  202. <section id="basic-event-production">
  203. <title>Producing and sending an event</title>
  204. <p>
  205. The basics are very simple. Just instantiate an <code>Event</code> object and fill
  206. it with the necessary parameters. Then pass it to the <code>EventBroadcaster</code>
  207. which distributes the events to the interested listeneners. Here's a code example:
  208. </p>
  209. <source><![CDATA[Event ev = new Event(this, "complain", EventSeverity.WARN,
  210. Event.paramsBuilder()
  211. .param("reason", "I'm tired")
  212. .param("blah", new Integer(23))
  213. .build());
  214. EventBroadcaster broadcaster = [get it from somewhere];
  215. broadcaster.broadcastEvent(ev);
  216. ]]></source>
  217. <p>
  218. The <code>Event.paramsBuilder()</code> is a
  219. <a href="http://en.wikipedia.org/wiki/Fluent_interface">fluent interface</a>
  220. to help with the build-up of the parameters. You could just as well instantiate a
  221. <code>Map</code> (<code>Map&lt;String, Object&gt;</code>) and fill it with values.
  222. </p>
  223. </section>
  224. <section id="event-producer">
  225. <title>The EventProducer interface</title>
  226. <p>
  227. To simplify event production, the event subsystem provides the <code>EventProducer</code>
  228. interface. You can create interfaces which extend <code>EventProducer</code>. These
  229. interfaces will contain one method per event to be generated. By contract, each event
  230. method must have as its first parameter a parameter named "source" (Type Object) which
  231. indicates the object that generated the event. After that come an arbitrary number of
  232. parameters of any type as needed by the event.
  233. </p>
  234. <p>
  235. The event producer interface does not need to have any implementation. The implementation
  236. is produced at runtime by a dynamic proxy created by <code>DefaultEventBroadcaster</code>.
  237. The dynamic proxy creates <code>Event</code> instances for each method call against
  238. the event producer interface. Each parameter (except "source") is added to the event's
  239. parameter map.
  240. </p>
  241. <p>
  242. To simplify the code needed to get an instance of the event producer interface it is
  243. suggested to create a public inner provider class inside the interface.
  244. </p>
  245. <p>
  246. Here's an example of such an event producer interface:
  247. </p>
  248. <source><![CDATA[public interface MyEventProducer extends EventProducer {
  249. public class Provider {
  250. public static MyEventProducer get(EventBroadcaster broadcaster) {
  251. return (MyEventProducer)broadcaster.getEventProducerFor(MyEventProducer.class);
  252. }
  253. }
  254. /**
  255. * Complain about something.
  256. * @param source the event source
  257. * @param reason the reason for the complaint
  258. * @param blah the complaint
  259. * @event.severity WARN
  260. */
  261. void complain(Object source, String reason, int blah);
  262. }]]></source>
  263. <p>
  264. To produce the same event as in the first example above, you'd use the following code:
  265. </p>
  266. <source><![CDATA[EventBroadcaster broadcaster = [get it from somewhere];
  267. TestEventProducer producer = TestEventProducer.Provider.get(broadcaster);
  268. producer.complain(this, "I'm tired", 23);]]></source>
  269. </section>
  270. <section id="event-model">
  271. <title>The event model</title>
  272. <p>
  273. Inside an invocation handler for a dynamic proxy, there's no information about
  274. the names of each parameter. The JVM doesn't provide it. The only thing you know is
  275. the interface and method name. In order to properly fill the <code>Event</code>'s
  276. parameter map we need to know the parameter names. These are retrieved from an
  277. event object model. This is found in the <code>org.apache.fop.events.model</code>
  278. package. The data for the object model is retrieved from an XML representation of the
  279. event model that is loaded as a resource. The XML representation is generated using an
  280. Ant task at build time (<code>ant resourcegen</code>). The Ant task (found in
  281. <code>src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java</code>)
  282. scans FOP's sources for descendants of the <code>EventProducer</code> interface and
  283. uses <a href="http://qdox.codehaus.org/">QDox</a> to parse these interfaces.
  284. </p>
  285. <p>
  286. The event model XML files are generated during build by the Ant task mentioned above when
  287. running the "resourcegen" task. So just run <code>"ant resourcegen"</code> if you receive
  288. a <code>MissingResourceException</code> at runtime indicating that
  289. <code>"event-model.xml"</code> is missing.
  290. </p>
  291. <p>
  292. Primarily, the QDox-based collector task records the parameters' names and types.
  293. Furthermore, it extracts additional attributes embedded as Javadoc comments from
  294. the methods. At the moment, the only such attribute is "@event.severity" which indicates
  295. the default event severity (which can be changed by event listeners). The example event
  296. producer above shows the Javadocs for an event method.
  297. </p>
  298. <p>
  299. There's one more information that is extracted from the event producer information for
  300. the event model: an optional primary exception. The first exception in the "throws"
  301. declaration of an event method is noted. It is used to throw an exception from
  302. the invocation handler if the event has an event severity of "FATAL" when all
  303. listeners have been called (listeners can update the event severity). Please note
  304. that an implementation of
  305. <code>org.apache.fop.events.EventExceptionManager$ExceptionFactory</code> has to be
  306. registered for the <code>EventExceptionManager</code> to be able to construct the
  307. exception from an event.
  308. </p>
  309. <p>
  310. For a given application, there can be multiple event models active at the same time.
  311. In FOP, each renderer is considered to be a plug-in and provides its own specific
  312. event model. The individual event models are provided through an
  313. <code>EventModelFactory</code>. This interface is implemented for each event model
  314. and registered through the service provider mechanism
  315. (see the <a href="#plug-ins">plug-ins section</a> for details).
  316. </p>
  317. </section>
  318. <section id="event-severity">
  319. <title>Event severity</title>
  320. <p>
  321. Four different levels of severity for events has been defined:
  322. </p>
  323. <ol>
  324. <li>INFO: informational only</li>
  325. <li>WARN: a Warning</li>
  326. <li>ERROR: an error condition from which FOP can recover. FOP will continue processing.</li>
  327. <li>FATAL: a fatal error which causes an exception in the end and FOP will stop processing.</li>
  328. </ol>
  329. <p>
  330. Event listeners can choose to ignore certain events based on their event severity.
  331. Please note that you may recieve an event "twice" in a specific case: if there is
  332. a fatal error an event is generated and sent to the listeners. After that an exception
  333. is thrown with the same information and processing stops. If the fatal event is
  334. shown to the user and the following exception is equally presented to the user it
  335. may appear that the event is duplicated. Of course, the same information is just
  336. published through two different channels.
  337. </p>
  338. </section>
  339. <section id="plug-ins">
  340. <title>Plug-ins to the event subsystem</title>
  341. <p>
  342. The event subsystem is extensible. There are a number of extension points:
  343. </p>
  344. <ul>
  345. <li>
  346. <strong><code>org.apache.fop.events.model.EventModelFactory</code>:</strong> Provides
  347. an event model to the event subsystem.
  348. </li>
  349. <li>
  350. <strong><code>org.apache.fop.events.EventExceptionManager$ExceptionFactory</code>:</strong>
  351. Creates exceptions for events, i.e. turns an event into a specific exception.
  352. </li>
  353. </ul>
  354. <p>
  355. The names in bold above are used as filenames for the service provider files that
  356. are placed in the <code>META-INF/services</code> directory. That way, they are
  357. automatically detected. This is a mechanism defined by the
  358. <a href="http://java.sun.com/j2se/1.4.2/docs/guide/jar/jar.html#Service%20Provider">JAR file specification</a>.
  359. </p>
  360. </section>
  361. <section id="l10n">
  362. <title>Localization (L10n)</title>
  363. <p>
  364. One goal of the event subsystem was to have localized (translated) event messages.
  365. The <code>EventFormatter</code> class can be used to convert an event to a
  366. human-readable message. Each <code>EventProducer</code> can provide its own XML-based
  367. translation file. If there is none, a central translation file is used, called
  368. "EventFormatter.xml" (found in the same directory as the <code>EventFormatter</code>
  369. class).
  370. </p>
  371. <p>
  372. The XML format used by the <code>EventFormatter</code> is the same as
  373. <a href="ext:cocoon">Apache Cocoon's</a> catalog format. Here's an example:
  374. </p>
  375. <source><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
  376. <catalogue xml:lang="en">
  377. <message key="locator">
  378. [ (See position {loc})| (See {#gatherContextInfo})| (No context info available)]
  379. </message>
  380. <message key="org.apache.fop.render.rtf.RTFEventProducer.explicitTableColumnsRequired">
  381. RTF output requires that all table-columns for a table are defined. Output will be incorrect.{{locator}}
  382. </message>
  383. <message key="org.apache.fop.render.rtf.RTFEventProducer.ignoredDeferredEvent">
  384. Ignored deferred event for {node} ({start,if,start,end}).{{locator}}
  385. </message>
  386. </catalogue>
  387. ]]></source>
  388. <p>
  389. The example (extracted from the RTF handler's event producer) has message templates for
  390. two event methods. The class used to do variable replacement in the templates is
  391. <code>org.apache.fop.util.text.AdvancedMessageFormat</code> which is more powerful
  392. than the <code>MessageFormat</code> classes provided by the Java class library
  393. (<code>java.util.text</code> package).
  394. </p>
  395. <p>
  396. "locator" is a template that is reused by the other message templates
  397. by referencing it through "{{locator}}". This is some kind of include command.
  398. </p>
  399. <p>
  400. Normal event parameters are accessed by name inside single curly braces, for example:
  401. "{node}". For objects, this format just uses the <code>toString()</code> method to turn
  402. the object into a string, unless there is an <code>ObjectFormatter</code> registered
  403. for that type (there's an example for <code>org.xml.sax.Locator</code>).
  404. </p>
  405. <p>
  406. The single curly braces pattern supports additional features. For example, it is possible
  407. to do this: "{start,if,start,end}". "if" here is a special field modifier that evaluates
  408. "start" as a boolean and if that is true returns the text right after the second comma
  409. ("start"). Otherwise it returns the text after the third comma ("end"). The "equals"
  410. modifier is similar to "if" but it takes as an additional (comma-separated) parameter
  411. right after the "equals" modifier, a string that is compared to the value of the variable.
  412. An example: {severity,equals,EventSeverity:FATAL,,some text} (this adds "some text" if
  413. the severity is not FATAL).
  414. </p>
  415. <p>
  416. Additional such modifiers can be added by implementing the
  417. <code>AdvancedMessageFormat$Part</code> and <code>AdvancedMessageFormat$PartFactory</code>
  418. interfaces.
  419. </p>
  420. <p>
  421. Square braces can be used to specify optional template sections. The whole section will
  422. be omitted if any of the variables used within are unavailable. Pipe (|) characters can
  423. be used to specify alternative sub-templates (see "locator" above for an example).
  424. </p>
  425. <p>
  426. Developers can also register a function (in the above example:
  427. <code>{#gatherContextInfo})</code>
  428. to do more complex information rendering. These functions are implementations of the
  429. <code>AdvancedMessageFormat$Function</code> interface. Please take care that this is
  430. done in a locale-independent way as there is no locale information available, yet.
  431. </p>
  432. </section>
  433. </section>
  434. </body>
  435. </document>