Added: websites/staging/xmlgraphics/trunk/content/fop/2.0/events.html ============================================================================== --- websites/staging/xmlgraphics/trunk/content/fop/2.0/events.html (added) +++ websites/staging/xmlgraphics/trunk/content/fop/2.0/events.html Thu May 21 15:08:45 2015 @@ -0,0 +1,594 @@ + + + + Apache(tm) FOP: Events/Processing Feedback + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ The Apache FOP Project +

The Apache™ FOP Project

+
+ + + +
+
+
+ +

Apache™ FOP: Events/Processing Feedback

+

Introduction

+

In versions until 0.20.5, Apache™ FOP used Avalon-style Logging where it was possible to supply a logger per processing run. During the redesign the logging infrastructure was switched over to Commons Logging which is (like Log4J or java.util.logging) a "static" logging framework (the logger is accessed through static variables). This made it very difficult in a multi-threaded system to retrieve information for a single processing run.

+

With FOP's event subsystem, we'd like to close this gap again and even go further. The first point is to realize that we have two kinds of "logging". Firstly, we have the logging infrastructure for the (FOP) developer who needs to be able to enable finer log messages for certain parts of FOP to track down a certain problem. Secondly, we have the user who would like to be informed about missing images, overflowing lines or substituted fonts. These messages (or events) are targeted at less technical people and may ideally be localized (translated). Furthermore, tool and solution builders would like to integrate FOP into their own solutions. For example, an FO editor should be able to point the user to the right place where a particular problem occurred while developing a document template. Finally, some integrators would like to abort processing if a resource (an image or a font) has not been found, while others would simply continue. The event system allows to react on these event s.

+

On this page, we won't discuss logging as such. We will show how the event subsystem can be used for various tasks. We'll first look at the event subsystem from the consumer side. Finally, the production of events inside FOP will be discussed (this is mostly interesting for FOP developers only).

+

The consumer side

+

The event subsystem is located in the org.apache.fop.events package and its base is the Event class. An instance is created for each event and is sent to a set of EventListener instances by the EventBroadcaster. An Event contains:

+ +

The EventFormatter class can be used to translate the events into human-readable, localized messages.

+

A full example of what is shown here can be found in the examples/embedding/java/embedding/events directory in the FOP distribution. The example can also be accessed via the web.

+

Writing an EventListener

+

The following code sample shows a very simple EventListener. It basically just sends all events to System.out (stdout) or System.err (stderr) depending on the event severity.

+
import org.apache.fop.events.Event;
+import org.apache.fop.events.EventFormatter;
+import org.apache.fop.events.EventListener;
+import org.apache.fop.events.model.EventSeverity;
+
+/** A simple event listener that writes the events to stdout and stderr. */
+public class SysOutEventListener implements EventListener {
+
+    /** {@inheritDoc} */
+    public void processEvent(Event event) {
+        String msg = EventFormatter.format(event);
+        EventSeverity severity = event.getSeverity();
+        if (severity == EventSeverity.INFO) {
+            System.out.println("[INFO ] " + msg);
+        } else if (severity == EventSeverity.WARN) {
+            System.out.println("[WARN ] " + msg);
+        } else if (severity == EventSeverity.ERROR) {
+            System.err.println("[ERROR] " + msg);
+        } else if (severity == EventSeverity.FATAL) {
+            System.err.println("[FATAL] " + msg);
+        } else {
+            assert false;
+        }
+    }
+}
+
+ + +

You can see that for every event the method processEvent of the EventListener will be called. Inside this method you can do whatever processing you would like including throwing a RuntimeException, if you want to abort the current processing run.

+

The code above also shows how you can turn an event into a human-readable, localized message that can be presented to a user. The EventFormatter class does this for you. It provides additional methods if you'd like to explicitly specify the locale.

+

It is possible to gather all events for a whole processing run so they can be evaluated afterwards. However, care should be taken about memory consumption since the events provide references to objects inside FOP which may themselves have references to other objects. So holding on to these objects may mean that whole object trees cannot be released!

+

Adding an EventListener

+

To register the event listener with FOP, get the EventBroadcaster which is associated with the user agent (FOUserAgent) and add it there:

+
FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
+foUserAgent.getEventBroadcaster().addEventListener(new SysOutEventListener());
+
+ + +

Please note that this is done separately for each processing run, i.e. for each new user agent.

+

An additional listener example

+

Here's an additional example of an event listener:

+

By default, FOP continues processing even if an image wasn't found. If you have more strict requirements and want FOP to stop if an image is not available, you can do something like the following in the simplest case:

+
public class MyEventListener implements EventListener {
+
+    public void processEvent(Event event) {
+        if ("org.apache.fop.ResourceEventProducer".equals(
+                event.getEventGroupID())) {
+            event.setSeverity(EventSeverity.FATAL);
+        } else {
+            //ignore all other events (or do something of your choice)
+        }
+    }
+
+}
+
+ + +

Increasing the event severity to FATAL will signal the event broadcaster to throw an exception and stop further processing. In the above case, all resource-related events will cause FOP to stop processing.

+

You can also customize the exception to throw (you can may throw a RuntimeException or subclass yourself) and/or which event to respond to:

+
public class MyEventListener implements EventListener {
+
+    public void processEvent(Event event) {
+        if ("org.apache.fop.ResourceEventProducer.imageNotFound"
+                .equals(event.getEventID())) {
+
+            //Get the FileNotFoundException that's part of the event's parameters
+            FileNotFoundException fnfe = (FileNotFoundException)event.getParam("fnfe");
+
+            throw new RuntimeException(EventFormatter.format(event), fnfe);
+        } else {
+            //ignore all other events (or do something of your choice)
+        }
+    }
+
+}
+
+ + +

This throws a RuntimeException with the FileNotFoundException as the cause. Further processing effectively stops in FOP. You can catch the exception in your code and react as you see necessary.

+

The producer side (for FOP developers)

+

This section is primarily for FOP and FOP plug-in developers. It describes how to use the event subsystem for producing events.

+

The event package has been designed in order to be theoretically useful for use cases outside FOP. If you think this is interesting independently from FOP, please talk to us.

+

Producing and sending an event

+

The basics are very simple. Just instantiate an Event object and fill it with the necessary parameters. Then pass it to the EventBroadcaster which distributes the events to the interested listeneners. Here's a code example:

+
Event ev = new Event(this, "complain", EventSeverity.WARN,
+        Event.paramsBuilder()
+            .param("reason", "I'm tired")
+            .param("blah", new Integer(23))
+            .build());
+EventBroadcaster broadcaster = [get it from somewhere];
+broadcaster.broadcastEvent(ev);
+
+ + +

The Event.paramsBuilder() is a fluent interface to help with the build-up of the parameters. You could just as well instantiate a Map (Map<String, Object>) and fill it with values.

+

The EventProducer interface

+

To simplify event production, the event subsystem provides the EventProducer interface. You can create interfaces which extend EventProducer. These interfaces will contain one method per event to be generated. By contract, each event method must have as its first parameter a parameter named "source" (Type Object) which indicates the object that generated the event. After that come an arbitrary number of parameters of any type as needed by the event.

+

The event producer interface does not need to have any implementation. The implementation is produced at runtime by a dynamic proxy created by DefaultEventBroadcaster. The dynamic proxy creates Event instances for each method call against the event producer interface. Each parameter (except "source") is added to the event's parameter map.

+

To simplify the code needed to get an instance of the event producer interface it is suggested to create a public inner provider class inside the interface.

+

Here's an example of such an event producer interface:

+
public interface MyEventProducer extends EventProducer {
+
+    public class Provider {
+
+        public static MyEventProducer get(EventBroadcaster broadcaster) {
+            return (MyEventProducer)broadcaster.getEventProducerFor(MyEventProducer.class);
+        }
+    }
+
+    /**
+     * Complain about something.
+     * @param source the event source
+     * @param reason the reason for the complaint
+     * @param blah the complaint
+     * @event.severity WARN
+     */
+    void complain(Object source, String reason, int blah);
+
+}
+
+ + +

To produce the same event as in the first example above, you'd use the following code:

+
EventBroadcaster broadcaster = [get it from somewhere];
+TestEventProducer producer = TestEventProducer.Provider.get(broadcaster);
+producer.complain(this, "I'm tired", 23);
+
+ + +

The event model

+

Inside an invocation handler for a dynamic proxy, there's no information about the names of each parameter. The JVM doesn't provide it. The only thing you know is the interface and method name. In order to properly fill the Event 's parameter map we need to know the parameter names. These are retrieved from an event object model. This is found in the org.apache.fop.events.model package. The data for the object model is retrieved from an XML representation of the event model that is loaded as a resource. The XML representation is generated using an Ant task at build time (ant resourcegen). The Ant task (found in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java) scans FOP's sources for descendants of the EventProducer interface and uses QDox to parse these interfaces.

+

The event model XML files are generated during build by the Ant task mentioned above when running the "resourcegen" task. So just run "ant resourcegen" if you receive a MissingResourceException at runtime indicating that "event-model.xml" is missing.

+

Primarily, the QDox-based collector task records the parameters' names and types. Furthermore, it extracts additional attributes embedded as Javadoc comments from the methods. At the moment, the only such attribute is "@event.severity" which indicates the default event severity (which can be changed by event listeners). The example event producer above shows the Javadocs for an event method.

+

There's one more information that is extracted from the event producer information for the event model: an optional primary exception. The first exception in the "throws" declaration of an event method is noted. It is used to throw an exception from the invocation handler if the event has an event severity of "FATAL" when all listeners have been called (listeners can update the event severity). Please note that an implementation of org.apache.fop.events.EventExceptionManager$ExceptionFactory has to be registered for the EventExceptionManager to be able to construct the exception from an event.

+

For a given application, there can be multiple event models active at the same time. In FOP, each renderer is considered to be a plug-in and provides its own specific event model. The individual event models are provided through an EventModelFactory. This interface is implemented for each event model and registered through the service provider mechanism (see the plug-ins section for details).

+

Event severity

+

Four different levels of severity for events has been defined:

+
    +
  1. +

    INFO: informational only

    +
  2. +
  3. +

    WARN: a Warning

    +
  4. +
  5. +

    ERROR: an error condition from which FOP can recover. FOP will continue processing.

    +
  6. +
  7. +

    FATAL: a fatal error which causes an exception in the end and FOP will stop processing.

    +
  8. +
+

Event listeners can choose to ignore certain events based on their event severity. Please note that you may recieve an event "twice" in a specific case: if there is a fatal error an event is generated and sent to the listeners. After that an exception is thrown with the same information and processing stops. If the fatal event is shown to the user and the following exception is equally presented to the user it may appear that the event is duplicated. Of course, the same information is just published through two different channels.

+

Plug-ins to the event subsystem

+

The event subsystem is extensible. There are a number of extension points:

+ +

The names in bold above are used as filenames for the service provider files that are placed in the META-INF/services directory. That way, they are automatically detected. This is a mechanism defined by the JAR file specification.

+

Localization (L10n)

+

One goal of the event subsystem was to have localized (translated) event messages. The EventFormatter class can be used to convert an event to a human-readable message. Each EventProducer can provide its own XML-based translation file. If there is none, a central translation file is used, called "EventFormatter.xml" (found in the same directory as the EventFormatter class).

+

The XML format used by the EventFormatter is the same as Apache Cocoon's catalog format. Here's an example:

+
<?xml version="1.0" encoding="UTF-8"?>
+<catalogue xml:lang="en">
+  <message key="locator">
+    [ (See position {loc})| (See { #gatherContextInfo})| (No context info available)]
+  </message>
+  <message key="org.apache.fop.render.rtf.RTFEventProducer.explicitTableColumnsRequired">
+    RTF output requires that all table-columns for a table are defined. Output will be incorrect.
+  </message>
+  <message key="org.apache.fop.render.rtf.RTFEventProducer.ignoredDeferredEvent">
+    Ignored deferred event for {node} ({start,if,start,end}).
+  </message>
+</catalogue>
+
+ + +

The example (extracted from the RTF handler's event producer) has message templates for two event methods. The class used to do variable replacement in the templates is org.apache.fop.util.text.AdvancedMessageFormat which is more powerful than the MessageFormat classes provided by the Java class library (java.util.text package).

+

"locator" is a template that is reused by the other message templates by referencing it through "". This is some kind of include command.

+

Normal event parameters are accessed by name inside single curly braces, for example: "{node}". For objects, this format just uses the toString() method to turn the object into a string, unless there is an ObjectFormatter registered for that type (there's an example for org.xml.sax.Locator).

+

The single curly braces pattern supports additional features. For example, it is possible to do this: "{start,if,start,end}". "if" here is a special field modifier that evaluates "start" as a boolean and if that is true returns the text right after the second comma ("start"). Otherwise it returns the text after the third comma ("end"). The "equals" modifier is similar to "if" but it takes as an additional (comma-separated) parameter right after the "equals" modifier, a string that is compared to the value of the variable. An example: {severity,equals,EventSeverity:FATAL,,some text} (this adds "some text" if the severity is not FATAL).

+

Additional such modifiers can be added by implementing the AdvancedMessageFormat$Part and AdvancedMessageFormat$PartFactory interfaces.

+

Square braces can be used to specify optional template sections. The whole section will be omitted if any of the variables used within are unavailable. Pipe (|) characters can be used to specify alternative sub-templates (see "locator" above for an example).

+

Developers can also register a function (in the above example: { #gatherContextInfo}) to do more complex information rendering. These functions are implementations of the AdvancedMessageFormat$Function interface. Please take care that this is done in a locale-independent way as there is no locale information available, yet.

+
+ +
+ + + + + + Added: websites/staging/xmlgraphics/trunk/content/fop/2.0/extensions.html ============================================================================== --- websites/staging/xmlgraphics/trunk/content/fop/2.0/extensions.html (added) +++ websites/staging/xmlgraphics/trunk/content/fop/2.0/extensions.html Thu May 21 15:08:45 2015 @@ -0,0 +1,553 @@ + + + + Standard Apache(tm) FOP Extensions + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ The Apache FOP Project +

The Apache™ FOP Project

+
+ + + +
+
+
+ +

Standard Apache(tm) FOP Extensions

+

By "extension", we mean any data that can be placed in the input XML document that is not addressed by the XSL-FO standard. By having a mechanism for supporting extensions, Apache™ FOP is able to add features that are not covered in the specification.

+

The extensions documented here are included with FOP, and are automatically available to you. If you wish to add an extension of your own to FOP, please see the Developers' Extension Page.

+

All extensions require the correct use of an appropriate namespace in your input document.

+

SVG

+

Please see the SVG documentation for more details.

+

FO Extensions

+

Namespace

+

By convention, FO extensions in FOP use the "fox" namespace prefix. To use any of the FO extensions, add a namespace entry for http://xmlgraphics.apache.org/fop/extensions to the root element:

+
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format"
+         xmlns:fox="http://xmlgraphics.apache.org/fop/extensions">
+
+ + +

PDF Bookmarks

+

In old versions of Apache FOP there was a fox:outline element which was used to create outlines in PDF files. The redesigned code makes use of the bookmark feature defined in the W3C XSL 1.1 standard.

+

Anchors or Named Destinations

+

Use the fox:destination element to define "named destinations" inside a PDF document. These are useful as fragment identifiers, e.g. "http://server/document.pdf#anchor-name". fox:destination elements can be placed almost anywhere in the fo document, including a child of root, a block-level element, or an inline-level element. For the destination to actually work, it must correspond to an "id" attribute on some fo element within the document. In other words, the "id" attribute actually creates the "view" within the PDF document. The fox:destination simply gives that view an independent name.

+
<fox:destination internal-destination="table-of-contents"/>
+...
+<fo:block id="table-of-contents">Table of Contents</fo:block>
+
+ + +

It is possible that in some future release of FOP, all elements with "id" attributes will generate named-destinations, which will eliminate the need for fox:destination.

+

Table Continuation Label

+

In old versions of Apache FOP, there was a fox:continued-label element which was used to insert a message when a table went over several pages. +This extension element will not be reimplemented for the redesigned code. +The redesigned code makes use of the fo:retrieve-table-marker element defined in the W3C XSL 1.1 standard.

+

Row Scope for Header Table Cells

+

This feature is described in the Accessibility section.

+

fox:orphan-content-limit and fox:widow-content-limit

+

The two proprietary extension properties, fox:orphan-content-limit and fox:widow-content-limit, are used to improve the layout of list-blocks and tables. If you have a table with many entries, you don't want a single row to be left over on a page. You will want to make sure that at least two or three lines are kept together. The properties take an absolute length which specifies the area at the beginning (fox:widow-content-limit) or at the end (fox:orphan-content-limit) of a table or list-block. The properties are inherited and only have an effect on fo:table and fo:list-block. An example: fox:widow-content-limit="3 * 1.2em" would make sure the you'll have at least three lines (assuming line-height="1.2") together on a table or list-block.

+

fox:external-document

+

This feature is incomplete. Support for multi-page documents will be added shortly. At the moment, only single-page images will work. And this will not work with RTF output.

+

This is a proprietary extension element which allows to add whole images as pages to an FO document. For example, if you have a scanned document or a fax as multi-page TIFF file, you can append or insert this document using the fox:external-document element. Each page of the external document will create one full page in the target format.

+

The fox:external-document element is structurally a peer to fo:page-sequence, so wherever you can put an fo:page-sequence you could also place a fox:external-document. Therefore, the specified contents for fo:root change to:

+
(layout-master-set, declarations?, bookmark-tree?, (page-sequence|page-sequence-wrapper|fox:external-document|fox:destination)+)
+
+ + +

Specification

+

The fox:external-document extension formatting object is used to specify how to create a (sub-)sequence of pages within a document. The content of these pages comes from the individual subimages/pages of an image or paged document (for example: multi-page TIFF in the form of faxes or scanned documents, or PDF files). The formatting object creates the necessary areas to display one image per page.

+

In terms of page numbers, the behaviour is the same as for fo:page-sequence. The placement of the image inside the page is similar to that of fo:external-graphic or fo:instream-foreign-object, i.e. the viewport (and therefore the page size) is defined by either the intrinsic size of the image or by the size properties that apply to this formatting object.

+

Content: EMPTY

+

The following properties apply to this formatting object:

+ +

Datatype "page-set": Value: auto | , Default: "auto" which means all pages/subimages of the document. allows values such as "7" or "1-3"

+

fox:external-document is not suitable for concatenating FO documents.

+

For this, XInclude is recommended.

+

Free-form Transformation for fo:block-container

+

For fo:block-container elements whose absolute-position set to "absolute" or "fixed" you can use the extension attribute fox:transform to apply a free-form transformation to the whole block-container. The content of the fox:transform attribute is the same as for SVG's transform attribute. The transformation specified here is performed in addition to other implicit transformations of the block-container (resulting from top, left and other properties) and after them.

+

Examples: fox:transform="rotate(45)" would rotate the block-container by 45 degrees clock-wise around its upper-left corner. fox:transform="translate(10000,0)" would move the block-container to the right by 10 points (=10000 millipoints, FOP uses millipoints internally!).

+

This extension attribute doesn't work for all output formats! It's currently only supported for PDF, PS and Java2D-based renderers.

+

Color functions

+

XSL-FO supports specifying color using the rgb(), rgb-icc() and system-color() functions. Apache FOP provides additional color functions for special use cases. Please note that using these functions compromises the interoperability of an FO document.

+

cmyk()

+

color cmyk(numeric, numeric, numeric, numeric)

+

This function will construct a color in device-specific CMYK color space. The numbers must be between 0.0 and 1.0. For output formats that don't support device-specific color space the CMYK value is converted to an sRGB value.

+

#CMYK pseudo-profile

+

color rgb-icc(numeric, numeric, numeric, #CMYK, numeric, numeric, numeric, numeric)

+

The rgb-icc function will respond to a pseudo-profile called "#CMYK" which indicates a device-specific CMYK color space. The "#CMYK" profile is implicitely available and doesn't have to be (and cannot be) defined through an fo:color-profile element. It is provided for compatibility with certain commercial XSL-FO implementations. Please note that this is not part of the official specification but rather a convention. The following two color specifications are equivalent:

+ +

Rounded Corners

+

Rounded corners on block areas can be specified with the fox:border-*-*-radius properties. Each corner can be specified with two radii that define a quarter ellipse that defines the shape of the corner of the outer border edge (in accordance with the W3 CSS3 Recommendation). +The property fox:border-BP-IP-radius specifies the radius of the corner connecting border segment BP is one of 'before|after' and IP is one of 'start|end', and takes one or two values. A single value will generate circular corners. Two values define elliptic corners where the first value defines the radius in the Inline Progression Direction, and the second the radius in the Block Progression Direction*.

+

The shorthand property fox:border-radius can be used to specify uniform corners and takes 1 or 2 values, as above.

+

The example fo examples/fo/advanced/rounded-corners.fo demonstrates some finer points of this extension.

+

Current Limitations

+ +

Prepress Support

+

This section defines a number of extensions related to prepress support. fox:scale defines a general scale factor for the generated pages. fox:bleed defines the bleed area for a page. fox:crop-offset defines the outer edges of the area in which crop marks, registration marks, color bars and page information are placed. For details, please read on below.

+

Those extensions have been implemented in the PDF and Java2D renderers only.

+

fox:scale

+

Value: {1,2}

+

Initial: 1

+

Applies to: fo:simple-page-master

+

This property specifies a scale factor along resp. the x and y axes. If only one number is provided it is used for both the x and y scales. A scale factor smaller than 1 shrinks the page. A scale factor greater than 1 enlarges the page.

+

fox:bleed

+

Value: {1,4}

+

Initial: 0pt

+

Applies to: fo:simple-page-master

+

If there is only one value, it applies to all sides. If there are two values, the top and bottom bleed widths are set to the first value and the right and left bleed widths are set to the second. If there are three values, the top is set to the first value, the left and right are set to the second, and the bottom is set to the third. If there are four values, they apply to the top, right, bottom, and left, respectively. (Corresponds to the definition of padding).

+

This extension indirectly defines the BleedBox and is calculated by expanding the TrimBox by the bleed widths. The lengths must be non-negative.

+

fox:crop-offset

+

Value: {1,4}

+

Initial: bleed (see below)

+

Applies to: fo:simple-page-master

+

Same behaviour as with fox:bleed. The initial value is set to the same values as the fox:bleed property.

+

This extension indirectly defines the MediaBox and is calculated by expanding the TrimBox by the crop offsets. The lengths must be non-negative.

+

fox:crop-box

+

Value: [trim-box | bleed-box | media-box]

+

Initial: media-box

+

Applies to: fo:simple-page-master

+

The crop box controls how Acrobat displays the page (CropBox in PDF) or how the Java2DRenderer sizes the output media. The PDF specification defines that the CropBox defaults to the MediaBox. This extension follows that definition. To simplify usage and cover most use cases, the three supported enumeration values "trim-box", "bleed-box" and "media-box" set the CropBox to one of those three other boxes.

+

If requested in the future, we could offer to specify the CropBox in absolute coordinates rather than just by referencing another box.

+

Background Images

+

Background images can be resized on the fly using these two extensions:

+

fox:background-image-width

+

Value: length

+

fox:background-image-height

+

Value: length

+

These extensions apply to the elements where background-image applies.

+
+ +
+ + + + + + --------------------------------------------------------------------- To unsubscribe, e-mail: commits-unsubscribe@xmlgraphics.apache.org For additional commands, e-mail: commits-help@xmlgraphics.apache.org