XML technologies / XSLT / Java and XSLT / XSLT processing with Java / Stylesheet compilation

(Excerpt from “Java und XSLT” by Eric M. Burke)

XSLT is a programming language expressed through XML syntax. This helps humans rather than computers. Before execution, the stylesheet must become an internal machine-readable representation, just as an interpreter or compiler translates other high-level languages.

Interpreters translate on every execution. For XSLT, the stylesheet is loaded by an XML parser, translated and applied to XML. Repetition harms performance because stylesheets rarely change: they are often defined early and stay static while XML is generated per request.

Parse and compile once, keeping the reusable internal representation in memory. This is stylesheet compilation, the same concept as in other languages.

The Templates API

Processors compile differently, so JAXP standardizes this with interface javax.xml.transform.Templates, with this simple API:

public interface Templates {
  java.util.Properties getOutputProperties( );
  javax.xml.transform.Transformer newTransformer( )
    throws TransformerConfigurationException;
}

Method getOutputProperties( ) returns a clone of properties associated with element <xsl:output>, such as method="xml", indent="yes" and encoding="ISO-8859-1". Recall that java.util.Properties, a subclass of java.util.Hashtable, maps property-name keys to values. Since this is a clone, modify the Properties instance for future transformations without changing the compiled stylesheet represented by Templates.

Method newTransformer( ) is more common and creates an instance implementing interface Transformer. This Transformer object performs transformations. JAXP hides the implementation of interface Templates, so use this method on javax.xml.transform.TransformerFactory to create it:

public Templates newTemplates(Source source)
  throws TransformerConfigurationException

As earlier, object Source can read stylesheets from files, system identifiers or even a DOM tree. In every case, the XSLT processor should compile an optimized internal representation.

Actual compilation depends on the implementation. Expect performance to improve over the next few years as tools stabilize and vendors optimize them.

The figure relates instances of Templates and Transformer.

Templates and Transformer relationship

Figure: Templates and Transformer relationship

Thread safety matters in Java, particularly on the web where many users share a stylesheet. One instance of Templates represents one stylesheet and is thread-safe.

Transformations maintain state and client-specific output properties, so each concurrent transformation requires its own Transformer instance.

Transformer is an abstract JAXP class whose implementations should be lightweight. Many Transformer copies will be created, but relatively few Templates objects. Transformer instances are not thread-safe mainly because they hold current transformation state. They may be reused after completion, however.

A stylesheet cache

Shared web servers handle many concurrent users, making Templates objects useful for performance. Ideally share one Templates instance across clients, reducing repeated parsing, compilation and memory use.

This custom cache automates creation and storage of Templates instances. It also checks the file’s lastModified flag and reloads modified stylesheets. During development, refresh the browser after an edit to see the result.

Example: StylesheetCache.java

package com.oreilly.javaxslt.util;

import java.io.*;
import java.util.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;

/**
 * Eine Tool-Klasse, die XSLT-Stylesheets zwischenspeichert.
 */
public class StylesheetCache {
   // XSLT-Dateinamen werden auf MapEintrag-Instanzen abgebildet
   // (MapEintrag wird weiter unten definiert)
   private static Map cache = new HashMap( );
  
   /**
     * Alle Stylesheets werden aus dem Speicher gelöscht und so der Cache geleert.
     */
    public static synchronized void flushAll( ) {
        cache.clear( );
    }
  
  /**
   * Ein spezifisches Stylesheet wird aus dem Speicher entfernt.
   *
   * @param xsltDateiname der Name des zu entfernenden Stylesheets.
   */
  public static synchronized void flush(String xsltDateiname) {
     cache.remove(xsltDateiname);
  }
  
  /**
   * Hole eine Transformer-Instanz für den angegebenen XSLT-Dateinamen.
   * Ein neuer Eintrag wird dem Cache hinzugefügt, wenn dies die erste Anfrage
   * für den angegebenen Dateinamen ist.
   *
   * @param xsltDateiname der Dateiname eines XSLT-Stylesheets.
   * @return ein Transformationskontext für das angegebene Stylesheet.
   */
  public static synchronized Transformer neuerTransformer(String xsltDateiname)
        throws TransformerConfigurationException {
    File xsltDatei = new File(xsltDateiname);
          
    // ermittle, wann die Datei auf der Festplatte zuletzt geändert wurde
    long xslLastModified = xsltFile.lastModified( );
    MapEintrag eintrag = (MapEintrag) cache.get(xsltDateiname);
          
    if (eintrag != null) {
       // wenn die Datei neuer ist als das gespeicherte Stylesheet,
       // dann entferne die Referenz auf den Eintrag
       if (xslLastModified > eintrag.lastModified) {
           eintrag = null;
       }
    }
  
    // erzeuge einen neuen Eintrag im Cache, falls nötig
    if (eintrag == null) {
        Source xslSource = new StreamSource(xsltDatei);
  
        TransformerFactory transFact = TransformerFactory.newInstance( );
        Templates templates = transFact.newTemplates(xslSource);
          eintrag = new MapEintrag(xslLastModified, templates);
          cache.put(xsltDateiname, eintrag);
        } 

    return eintrag.templates.newTransformer( );
  }

  // verhindere die Instantiierung dieser Klasse
  private StylesheetCache( ) {
  }

  /**
   * Diese Klasse repräsentiert einen Wert im Map-Objekt.
   */
  static class MapEintrag {
    long lastModified; // wann wurde die Datei modifiziert
    Templates templates;
    
    MapEintrag(long lastModified, Templates templates) {
       this.lastModified = lastModified;
       this.templates = templates;
    }
  }
}

As a singleton, the class has a private constructor and static methods, each declared synchronized to avoid thread problems.

The cache itself is a java.util.Map:

private static Map cache = new HashMap( );

Although HashMap is not thread-safe, making every method synchronized prevents concurrency problems. Each entry in the Map maps a stylesheet filename to an instance of MapEintrag. MapEintrag is a nested class tracking the compiled stylesheet and file modification time:

static class MapEintrag {
    long lastModified; // wann wurde die Datei modifiziert
    Templates templates;
  
    MapEintrag(long lastModified, Templates templates) {
         this.lastModified = lastModified;
         this.templates = templates;
    }
}

Two methods remove cached entries:

public static synchronized void flushAll( ) {
    cache.clear( );
}
public static synchronized void flush(String xsltDateiname) {
    cache.remove(xsltDateiname);
}

The first clears the entire Map; the second removes one stylesheet. For example, call flushAll from servlet method destroy( ) for cleanup. Individual servlets may remove their own stylesheets through flush(...). An absent parameter xsltDateiname is simply ignored by the map.

Most interaction uses method neuerTransformer with signature:

public static synchronized Transformer neuerTransformer(String xsltDateiname)
  throws TransformerConfigurationException {

Passing a filename permits modification-time checks. Class java.io.File gets the timestamp so changes can trigger reloading. A system identifier or InputStream object would prevent this. Next create object File and check flag lastModified:

File xsltDatei = new File(xsltDateiname);

// ermittle, wann die Datei auf der Festplatte zuletzt geändert wurde
long xslLastModified = xsltDatei.lastModified( );

The compiled stylesheet, a MapEintrag instance, is retrieved from the Map. Compare an existing entry’s timestamp with the current file for automatic reloading:

MapEintrag eintrag = (MapEintrag) cache.get(xsltDateiname);

if (eintrag != null) {
   // wenn die Datei neuer ist als das gespeicherte Stylesheet,
   // dann entferne die Referenz auf den Eintrag
   if (xslLastModified > eintrag.lastModified) {
        eintrag = null;
  }
}

Create a new entry if its reference is still null. Wrap object File in a StreamSource object, instantiate TransformerFactory and use that Factory instance to create the Templates object, then store the Templates object in the cache for the next client:

 

// erzeuge einen neuen Eintrag im Cache, falls nötig
if (eintrag == null) {
    Source xslSource = new StreamSource(xsltDatei);

    TransformerFactory transFact = TransformerFactory.newInstance( );
    Templates templates = transFact.newTemplates(xslSource);

    eintrag = new MapEintrag(xslLastModified, templates);
    cache.put(xsltDateiname, eintrag);
  }

Finally create a new Transformer and return it to the caller:

return eintrag.templates.newTransformer( );

A fresh Transformer is essential because only Templates is thread-safe, while Transformer is not. Each caller gets its own Transformer to prevent client collisions.

One improvement would add timestamp letzterZugriff to every MapEintrag object. Another thread could run every few hours to remove Map entries unused for some time. Usually unnecessary, this reduces memory for large sites with rarely visited pages.

Another change would pass javax.xml.transform.Source objects rather than filenames to method neuerTransformer, but loses automatic reloading for all Source types.

   

 

 

 

back to top