morten 01/05/17 08:36:42
Added: java/samples/CompiledApplet README.applet
TransformApplet.java index.html menu.html
java/samples/CompiledBrazil README.brazil
TransformHandler.java
java/samples/CompiledServlet CompileServlet.java
README.servlet TransformServlet.java
Log:
Added XSLTC demo files to the java/samples directory.
Submitted by: [EMAIL PROTECTED]
Reviewed by: [EMAIL PROTECTED]
Revision Changes Path
1.1 xml-xalan/java/samples/CompiledApplet/README.applet
Index: README.applet
===================================================================
======================================================================
The Sun XSLT Compiler (XSLTC) is a Java-based tool for compiling XSL
stylesheets into extremely lightweight and portable Java byte code.
The XSLTC Java Runtime environment can then process XML files against
these compiled stylesheets (Translets) to generate any manner of
output per the stylesheet instructions.
This Applet Demo shows you how translets can be run in a client
browser as Java applets to perform XSLT transformations on XML
source documents residing on a Web server. Because of XSLTC's small
footprint, it is possible to download the compiled stylesheets
(translets) and the runtime classes in the applet. Whereas, this
would not be easy with a fullsize Java-based XSLT processor.
There are two important advatages of this approach:
1) It offloads XSLT processing from the server
2) It enables browsers, such as Netscape 4.x, that do not have native
XSLT support to perform XSLT transformations today!
-----------------------------------------------------------------------
DEMO CONTENTS
-----------------------------------------------------------------------
The applet demo is very generic. It will let you run any pre-compiled
translet through an applet, and it lets you use that on any XML file
you can refer to using an URL. The contents of this demo are:
TransformApplet.java - The applet that wraps the XSLTC runtime
classes and your translet(s).
index.html - Your main HTML document (displays two frames)
menu.html - The HTML document for your dialog frame. This is the
document that invokes the TransformApplet
-----------------------------------------------------------------------
HOW TO SET UP THE DEMO ON YOUR SITE
-----------------------------------------------------------------------
1. Install and configure Xalan with XSLTC
2. Compile the stylesheets you want to export. This will result in one
or more small Java classes (translets).
3. Create a JAR file with your the applet class (compile it first, of
cource), your translet classes and these classes from the xalan/xsltc
package:
org/apache/xalan/xsltc/*.class
org/apache/xalan/xsltc/dom/*.class
org/apache/xalan/xsltc/runtime/*.class
org/apache/xalan/xsltc/util/*.class
Be sure to make the JAR file world readable!
4. Make your XML source documents readable through a URL (either place
them behind a web server or make them readable for your browser as
a file).
5. Open the supplied index.html and try out the demo!
----------------------------------------------------------------------
KNOW PROBLEMS
----------------------------------------------------------------------
The following problems are specific to the Netscape 4.x browser.
Class Already Loaded - If you start up the Netscape client browser on
a Unix system where you have been running XSLTC, and consequently
have a CLASSPATH that includes xml.jar, and xlstcrt.jar, the applet
demo fails. You'll see a message saying a class has already been
loaded in the Javascript console. To bring up the Javascript console,
you type
javascript:
in the location/URL field of the browser. To work around this problem,
unset your CLASSPATH before starting Netscape from a terminal window.
This still may not resolve the problem if Netscape is started from
a wrapper that sets your environment from your startup file (e.g.,
your .cshrc file for the C-shell).
Parser Exception - This problem only applies to Netscape on the
Windows platform with XML documents that have an external DTD.
If you see the following message:
org.xml.sax.SAXParseException:
External parameter entity "%(DOCTYPE);"
has characters after markup.
try removing the reference to an external DTD in your XML source.
----------------------------------------------------------------------
END OF README
1.1
xml-xalan/java/samples/CompiledApplet/TransformApplet.java
Index: TransformApplet.java
===================================================================
/*
* @(#)$Id: TransformApplet.java,v 1.1 2001/05/17 15:36:29 morten Exp $
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 2001, Sun
* Microsystems., http://www.sun.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* @author Morten Jorgensen
* @author Jacek Ambroziak
*
*/
import java.io.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.XMLReader;
import org.xml.sax.SAXException;
import org.apache.xalan.xsltc.*;
import org.apache.xalan.xsltc.runtime.*;
import org.apache.xalan.xsltc.dom.*;
/**
* This applet demonstrates how XSL transformations can be made run in
* browsers without native XSLT support.
*
* Note that the XSLTC transformation engine is invoked through its native
* interface and not the javax.xml.transform (JAXP) interface. This because
* XSLTC still does not offer precompiled transformations through JAXP.
*/
public final class TransformApplet extends Applet {
// Single document cache
private String _documentUrl = "";
private DOMImpl _dom = null;
private DTDMonitor _dtdMonitor = null;
/**
* This class implements a dialog box used for XSL messages/comments
*/
public class MessageFrame extends Frame {
public Frame frame;
public class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
}
}
/**
* This method handles xml:message and xsl:comment by displaying
* the message/comment in a dialog box.
*/
public MessageFrame(String title, String message) {
super(title);
frame = this; // Make visible to ButtonHandler
setSize(320,200);
// Create a panel for the message itself
Panel center = new Panel();
center.add(new Label(message));
// Create a panel for the 'OK' button
Panel bottom = new Panel();
Button okButton = new Button(" OK ");
okButton.addActionListener(new ButtonHandler());
bottom.add(okButton);
// Add the two panels to the window/frame
add(center, BorderLayout.CENTER);
add(bottom,BorderLayout.SOUTH);
// Show the fecking thing
setVisible(true);
}
}
/**
* The appled uses this method to display messages and comments
* generated by xsl:message and xsl:comment elements.
*/
public class AppletMessageHandler extends MessageHandler {
public void displayMessage(String msg) {
MessageFrame z = new MessageFrame("XSL transformation alert",msg);
}
}
/**
* Reads the input document from the supplied URL and builds the
* internal "DOM" tree.
*/
private DOM getDOM(String url) throws Exception {
// Check if the document is already in the 1-document cache
if (url.equals(_documentUrl) == false) {
// Create a SAX parser and get the XMLReader object it uses
final SAXParserFactory factory = SAXParserFactory.newInstance();
final SAXParser parser = factory.newSAXParser();
final XMLReader reader = parser.getXMLReader();
// Set the DOM's builder as the XMLReader's SAX2 content handler
_dom = new DOMImpl();
reader.setContentHandler(_dom.getBuilder());
// Create a DTD monitor and pass it to the XMLReader object
final DTDMonitor dtdMonitor = new DTDMonitor();
dtdMonitor.handleDTD(reader);
// Parse the input document
reader.parse(url);
// Update the 1-document cahce with this DOM
_documentUrl = url;
}
return _dom;
}
/**
* This method is the main body of the applet. The method is called
* by some JavaScript code in an HTML document.
*/
public String transform(Object arg1, Object arg2) {
// Convert the two arguments to strings.
final String transletName = (String)arg1;
final String documentUrl = (String)arg2;
// Initialise the output stream
final StringWriter sout = new StringWriter();
final PrintWriter out = new PrintWriter(sout);
try {
// Check that the parameters are valid
if (transletName == null || documentUrl == null) {
out.println("<h1>Transformation error</h1>");
out.println("The parameters <b><tt>class</tt></b> "+
"and <b><tt>source</tt></b> must be specified");
}
else {
// Instanciate a message handler for xsl:message/xsl:comment
AppletMessageHandler msgHandler = new AppletMessageHandler();
// Get a refenrence to the translet class
final Class tc = Class.forName(transletName);
// Instanciate and initialise the tranlet object
AbstractTranslet translet = (AbstractTranslet)tc.newInstance();
((AbstractTranslet)translet).setMessageHandler(msgHandler);
// Initialise the translet's output handler
DefaultSAXOutputHandler saxHandler =
new DefaultSAXOutputHandler(out);
TextOutput textOutput = new TextOutput(saxHandler);
getDOM(documentUrl);
final long start = System.currentTimeMillis();
// Set size of key/id indices
translet.setIndexSize(_dom.getSize());
// If there are any elements with ID attributes, build an index
_dtdMonitor.buildIdIndex(_dom, 0, translet);
// Pass unparsed entities to translet
translet.setUnparsedEntityURIs(_dtdMonitor.
getUnparsedEntityURIs());
// Do the actual transformation
translet.transform(_dom, textOutput);
final long done = System.currentTimeMillis() - start;
out.println("<!-- transformed by XSLTC in "+done+"msecs -->");
}
// Now close up the sink, and return the HTML output in the
// StringWrite object as a string.
out.close();
return sout.toString();
}
catch (RuntimeException e) {
out.close();
return sout.toString();
}
catch (Exception e) {
out.println("<h1>exception</h1>");
out.println(e.toString());
out.close();
return sout.toString();
}
}
}
1.1 xml-xalan/java/samples/CompiledApplet/index.html
Index: index.html
===================================================================
<html>
<head><title>XSLT Applet Demonstration</title></head>
<backgroundcolor=#ffffff>
<frameset border="1" cols="25%,*">
<frame src="menu.html" name="demo_ctrl">
<frame src="about:blank" name="demo_output">
</frameset>
</html>
1.1 xml-xalan/java/samples/CompiledApplet/menu.html
Index: menu.html
===================================================================
<html>
<head></head>
<body bgcolor=#ffffff>
<hr>
<center><h3>Xalan/XSLTC Applet Demo</h3></center>
Each of these examples illustrate the use of translets
within a Java applet:
<p>
<script language="JavaScript">
function run_transform(form) {
/* Get the input document and translet class name from input form */
var translet = form.translet;
var document = form.document;
/* Get the frame to output to */
var output_frame = parent.frames.demo_output.document;
/* Display the output in this frame */
output_frame.clear();
output_frame.writeln(document.TransformApplet.transform(translet,
document));
output_frame.close();
return(true);
}
</script>
<form name="xslt_form" onSubmit="run_transform(this.form)">
<p>Select translet:</p>
<p><input name="translet" width="64"></p>
<p>Select XML source document:</p>
<p><input name="document" width="64"></p>
<p><input type="button" value="Run"
onClick="run_transform(this.form)"></p>
</form>
<!--
The xsltc.jar file must contain the XSLTC runtime classes and your
pre-compiled translets, as described in the README.applet file.
-->
<applet archive="xsltc.jar"
code="TransformApplet"
name="TransformApplet"
width="10"
height="10">
</applet>
</body>
1.1 xml-xalan/java/samples/CompiledBrazil/README.brazil
Index: README.brazil
===================================================================
============================================================
CONTENTS OF THIS DOCUMENT:
o) HOW TO PROVIDE XSL TRANSFORMATIONS AS A WEB SERVICE
o) HOW TO INVOKE TRANSLETS FROM A BRAZIL HANDLER
o) BUILDING YOUR OWN DOM CACHE
------------------------------------------------------------
HOW TO PROVIDE XSL TRANSFORMATIONS AS A WEB SERVICE
This sample code illustrates how Xalan/XSLTC can be used to
offer XSL transformations as a web service without using a
full web server. We have chosen to use the Brazil prototype
for the web interface, available from Sunlabs:
http://www.sun.com/research/brazil/
but we could easily have used some other web interface such
as Tomcat. The supplied Java code implements a Brazil
"handler", which very much resembles a servlet.
------------------------------------------------------------
HOW TO INVOKE TRANSLETS FROM A BRAZIL HANDLER
The XSLTC preview package contains the example source code:
TransformHandler.java
This file contains a minimal implementation of an XSL
transformation handler. The handler performs the same basic
steps as the class implementing the XSLT command-line tool:
// Obtain a reference to the translet class
Class cls = Class.forName(transletName);
// Instanciate a translet object (inherits AbstractTranslet)
AbstractTranslet translet = (AbstractTranslet)cls.newInstance();
// Prepare the internal DOM tree
final DOMImpl dom = new DOMImpl();
dom.setDocumentURI(inputURI);
// Create a parser for the input document
final Parser parser = new Parser();
parser.setDocumentHandler(dom.getBuilder());
// Create a DTDMonitor for handling ID references in the DTD
DTDMonitor dtdMonitor = new DTDMonitor();
parser.setDTDHandler(dtdMonitor);
// Create output handler (you can plug in your own)
DefaultSAXOutputHandler saxHandler;
saxHandler = new DefaultSAXOutputHandler(out);
// Parse the document and build the internal DOM
parser.parse(inputURI);
// Pass information on id/key indicies to the translet
translet.setIndexSize(dom.getSize());
dtdMonitor.buildIdIndex(dom, 0, translet);
translet.setUnparsedEntityURIs(dtdMonitor.getUnparsedEntityURIs());
// Start the transformation
translet.transform(dom, new TextOutput(saxHandler));
Alternatively the handler can use a cache for storing
frequently accessed XML documents. This is not only a matter
of reading the initial input document from the cache, as
the translet may load other XML input documents as runtime.
(If the xsl:document() function was used in the stylesheet.)
// Get a reference to the translet class
Class cls = Class.forName(transletName);
// Instanciate a translet object (inherits AbstractTranslet)
AbstractTranslet translet = (AbstractTranslet)cls.newInstance();
// The translet needs a reference to the cache in case
// in needs to load additional XML documents.
translet.setDOMCache(cache);
// Get the DOM from the DOM cache
DOMImpl dom = cache.retrieveDocument(documentURI, 0, translet);
// Create output handler (you can plug in your own)
DefaultSAXOutputHandler saxHandler;
saxHandler = new DefaultSAXOutputHandler(out);
// Start the transformation
translet.transform(dom, new TextOutput(saxHandler));
------------------------------------------------------------
BUILDING YOUR OWN DOM CACHE
The interface for the DOM cache consists of a single method,
and its definition can be found in:
org/apache/xalan/xsltc/DOMCache.java
The method contained in the interface is:
public DOMImpl retrieveDocument(String uri,
int mask,
Translet translet);
The responsibilities of this method are:
A) Build new a DOMImpl and DTDMonitor for XML documents
that are not already in the cache:
// Instanciate a DOMImpl object
Parser parser = new Parser();
DOMImpl dom = new DOMImpl();
dom.setDocumentURI(uri);
parser.setDocumentHandler(dom.getBuilder());
// Use a DTDMonitor to track ID references in DTD
DTDMonitor dtdMonitor = new DTDMonitor();
parser.setDTDHandler(dtdMonitor);
// Parse the input document and build DOM
parser.parse(uri);
At this point the DOMImpl and DTDMonitor objects are
populated with the necessary data. The two objects
are ready to be put in the cache (using the URI as
the lookup key).
B) For each time a new document is requested by a translet:
// Expand translet's index array to fit this DOM
translet.setIndexSize(dom.getSize());
// Build indices for this DOM's DTD's ID references
dtd.buildIdIndex(dom, mask, translet);
// Pass unparsed entity URIs to the translet
translet.setUnparsedEntityURIs(dtd.getUnparsedEntityURIs());
Step A) must be done every time a document is read into the
cache, and step B) every time a document is given to a
translet.
The XSLTC package contains an example implementation of a
DOM cache, based on a very simple round-robin caching
algorithm:
org/apache/xalan/xsltc/dom/DocumentCache.java
------------------------------------------------------------
END OF README
1.1
xml-xalan/java/samples/CompiledBrazil/TransformHandler.java
Index: TransformHandler.java
===================================================================
/*
* @(#)$Id: TransformHandler.java,v 1.1 2001/05/17 15:36:35 morten Exp $
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 2001, Sun
* Microsystems., http://www.sun.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* @author Morten Jorgensen
*
*/
package org.apache.xalan.xsltc.demo.brazil;
import java.io.*;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.util.Vector;
import org.xml.sax.*;
import org.apache.xalan.xsltc.*;
import org.apache.xalan.xsltc.runtime.*;
import org.apache.xalan.xsltc.dom.*;
import sunlabs.brazil.server.Handler;
import sunlabs.brazil.server.Request;
import sunlabs.brazil.server.Server;
/**
* This Brazil handler demonstrates how XSL transformations can be made
* available as a web service without using a full web server. This class
* implements the Handler interface from the Brazil project, see:
* http://www.sun.com/research/brazil/
*
* Note that the XSLTC transformation engine is invoked through its native
* interface and not the javax.xml.transform (JAXP) interface. This because
* XSLTC still does not offer precompiled transformations through JAXP.
*/
public class TransformHandler implements Handler {
// A cache for internal DOM structures
private static DocumentCache cache = null;
// These two are used while parsing the parameters in the URL
private final String PARAM_TRANSLET = "translet=";
private final String PARAM_DOCUMENT = "document=";
private final String PARAM_STATS = "stats=";
// All output goes here:
private PrintWriter _out = null;
/**
* Dump an error message to output
*/
public void errorMessage(String message, Exception e) {
if (_out == null) return;
_out.println("<h1>XSL transformation error</h1>"+message);
_out.println("<br>Exception:</br>"+e.toString());
}
public void errorMessage(String message) {
if (_out == null) return;
_out.println("<h1>XSL transformation error</h1>"+message);
}
/**
* This method is run when the Brazil proxy is loaded
*/
public boolean init(Server server, String prefix) {
return true;
}
/**
* This method is run for every HTTP request sent to the proxy
*/
public boolean respond(Request request) throws IOException {
// Initialise the output buffer
final StringWriter sout = new StringWriter();
_out = new PrintWriter(sout);
// These two hold the parameters from the URL 'translet' and 'document'
String transletName = null;
String document = null;
String stats = null;
// Get the parameters from the URL
final StringTokenizer params = new StringTokenizer(request.query,"&");
while (params.hasMoreElements()) {
final String param = params.nextToken();
if (param.startsWith(PARAM_TRANSLET)) {
transletName = param.substring(PARAM_TRANSLET.length());
}
else if (param.startsWith(PARAM_DOCUMENT)) {
document = param.substring(PARAM_DOCUMENT.length());
}
else if (param.startsWith(PARAM_STATS)) {
stats = param.substring(PARAM_STATS.length());
}
}
try {
// Initialize the document cache with 32 DOM slots
if (cache == null) cache = new DocumentCache(32);
// Output statistics if user looked up "server:port/?stats=xxx"
if (stats != null) {
cache.getStatistics(_out); // get cache statistics (in HTML)
}
// Make sure that both parameters were specified
else if ((transletName == null) || (document == null)) {
errorMessage("Parameters <b><tt>translet</tt></b> and/or "+
"<b><tt>document</tt></b> not specified.");
}
else {
// Get a reference to the translet class
Class transletClass = Class.forName(transletName);
// Instanciate the translet object (inherits AbstractTranslet)
AbstractTranslet translet =
(AbstractTranslet)transletClass.newInstance();
translet.setDOMCache(cache);
// Get the DOM from the DOM cache
DOMImpl dom = cache.retrieveDocument(document, 0, translet);
if (dom == null) {
errorMessage("Could not locate: \"<b>"+document+"\"</b>");
}
else {
// Initialise the translet's output handler
DefaultSAXOutputHandler saxHandler =
new DefaultSAXOutputHandler(_out);
// Do the actual transformation
final long start = System.currentTimeMillis();
translet.transform(dom, new TextOutput(saxHandler));
final long done = System.currentTimeMillis() - start;
_out.println("<!-- transformed by XSLTC in "+done+"ms -->");
}
}
}
catch (SAXException e) {
errorMessage("Error parsing document \""+document+"\"");
}
catch (ClassNotFoundException e) {
errorMessage("Could not locate the translet class: \""+
transletName+"\"<br>Exception:</br>",e);
}
catch (Exception e) {
errorMessage("Internal error.",e);
}
// Pass the transformation output as the HTTP response
request.sendResponse(sout.toString());
return true;
}
}
1.1
xml-xalan/java/samples/CompiledServlet/CompileServlet.java
Index: CompileServlet.java
===================================================================
/*
* @(#)$Id: CompileServlet.java,v 1.1 2001/05/17 15:36:39 morten Exp $
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 2001, Sun
* Microsystems., http://www.sun.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* @author Morten Jorgensen
* @author Jacek Ambroziak
*
*/
package org.apache.xalan.xsltc.demo.servlet;
import java.io.*;
import java.text.*;
import java.util.*;
import java.net.URL;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.xalan.xsltc.compiler.*;
import org.apache.xalan.xsltc.compiler.util.*;
import org.apache.xalan.xsltc.util.getopt.*;
public class Compile extends HttpServlet {
/**
* Main servlet entry point. The servlet reads a stylesheet from the
* URI specified by the "sheet" parameter. The compiled Java class
* ends up in the CWD of the web server (a better solution would be
* to have an environment variable point to a translet directory).
*/
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String stylesheetName = request.getParameter("sheet");
out.println("<html><head>");
out.println("<title>Servlet Stylesheet Compilation</title>");
out.println("</head><body>");
if (stylesheetName == null) {
out.println("<h1>Compilation error</h1>");
out.println("The parameter <b><tt>sheet</tt></b> "+
"must be specified");
}
else {
XSLTC xsltc = new XSLTC();
xsltc.init();
xsltc.compile(new URL(stylesheetName));
out.println("<h1>Compilation successful</h1>");
out.println("The stylesheet was compiled into the translet "+
"class "+xsltc.getClassName() + " and is now "+
"available for transformations on this server.");
}
out.println("</body></html>");
}
}
1.1 xml-xalan/java/samples/CompiledServlet/README.servlet
Index: README.servlet
===================================================================
============================================================
CONTENTS OF THIS DOCUMENT:
o) HOW TO PROVIDE XSL TRANSFORMATIONS AS A WEB SERVICE
o) HOW TO INVOKE TRANSLETS FROM A SERVLET
o) BUILDING YOUR OWN DOM CACHE
------------------------------------------------------------
HOW TO PROVIDE XSL TRANSFORMATIONS AS A WEB SERVICE
With XSLTC, XSL transformations can be run from within a
servlet. The XSLTC preview package contains an example demonstrating
how this can be done.
------------------------------------------------------------
HOW TO INVOKE TRANSLETS FROM A SERVLET
The XSLTC preview package contains the example source code:
TransformServlet.java
This file contains a minimal implementation of an XSL
transformation servlet. The servlet performs the same basic
steps as the class implementing the XSLT command-line tool:
// Obtain a reference to the translet class
Class cls = Class.forName(transletName);
// Instanciate a translet object (inherits AbstractTranslet)
AbstractTranslet translet = (AbstractTranslet)cls.newInstance();
// Prepare the internal DOM tree
final DOMImpl dom = new DOMImpl();
dom.setDocumentURI(inputURI);
// Create a parser for the input document
final Parser parser = new Parser();
parser.setDocumentHandler(dom.getBuilder());
// Create a DTDMonitor for handling ID references in the DTD
DTDMonitor dtdMonitor = new DTDMonitor();
parser.setDTDHandler(dtdMonitor);
// Create output handler (you can plug in your own)
DefaultSAXOutputHandler saxHandler;
saxHandler = new DefaultSAXOutputHandler(out);
// Parse the document and build the internal DOM
parser.parse(inputURI);
// Pass information on id/key indicies to the translet
translet.setIndexSize(dom.getSize());
dtdMonitor.buildIdIndex(dom, 0, translet);
translet.setUnparsedEntityURIs(dtdMonitor.getUnparsedEntityURIs());
// Start the transformation
translet.transform(dom, new TextOutput(saxHandler));
Alternatively the servlet can use a cache for storing
frequently accessed XML documents. This is not only a matter
of reading the initial input document from the cache, as
the translet may load other XML input documents as runtime.
(If the xsl:document() function was used in the stylesheet.)
// Get a reference to the translet class
Class cls = Class.forName(transletName);
// Instanciate a translet object (inherits AbstractTranslet)
AbstractTranslet translet = (AbstractTranslet)cls.newInstance();
// The translet needs a reference to the cache in case
// in needs to load additional XML documents.
translet.setDOMCache(cache);
// Get the DOM from the DOM cache
DOMImpl dom = cache.retrieveDocument(documentURI, 0, translet);
// Create output handler (you can plug in your own)
DefaultSAXOutputHandler saxHandler;
saxHandler = new DefaultSAXOutputHandler(out);
// Start the transformation
translet.transform(dom, new TextOutput(saxHandler));
------------------------------------------------------------
BUILDING YOUR OWN DOM CACHE
The interface for the DOM cache consists of a single method,
and its definition can be found in:
org/apache/xalan/xsltc/DOMCache.java
The method contained in the interface is:
public DOMImpl retrieveDocument(String uri,
int mask,
Translet translet);
The responsibilities of this method are:
A) Build new a DOMImpl and DTDMonitor for XML documents
that are not already in the cache:
// Instanciate a DOMImpl object
Parser parser = new Parser();
DOMImpl dom = new DOMImpl();
dom.setDocumentURI(uri);
parser.setDocumentHandler(dom.getBuilder());
// Use a DTDMonitor to track ID references in DTD
DTDMonitor dtdMonitor = new DTDMonitor();
parser.setDTDHandler(dtdMonitor);
// Parse the input document and build DOM
parser.parse(uri);
At this point the DOMImpl and DTDMonitor objects are
populated with the necessary data. The two objects
are ready to be put in the cache (using the URI as
the lookup key).
B) For each time a new document is requested by a translet:
// Expand translet's index array to fit this DOM
translet.setIndexSize(dom.getSize());
// Build indices for this DOM's DTD's ID references
dtd.buildIdIndex(dom, mask, translet);
// Pass unparsed entity URIs to the translet
translet.setUnparsedEntityURIs(dtd.getUnparsedEntityURIs());
Step A) must be done every time a document is read into the
cache, and step B) every time a document is given to a
translet.
The XSLTC package contains an example implementation of a
DOM cache, based on a very simple round-robin caching
algorithm:
org/apache/xalan/xsltc/dom/DocumentCache.java
------------------------------------------------------------
END OF README
1.1
xml-xalan/java/samples/CompiledServlet/TransformServlet.java
Index: TransformServlet.java
===================================================================
/*
* @(#)$Id: TransformServlet.java,v 1.1 2001/05/17 15:36:40 morten Exp $
*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [EMAIL PROTECTED]
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 2001, Sun
* Microsystems., http://www.sun.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* @author Morten Jorgensen
* @author Jacek Ambroziak
*
*/
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.xml.sax.*;
import org.apache.xalan.xsltc.*;
import org.apache.xalan.xsltc.runtime.*;
import org.apache.xalan.xsltc.dom.*;
/**
* This servlet demonstrates how XSL transformations can be made available as
* a web service. See the CompileServlet for an example on how stylesheets
* can be pre-compiled before this servlet is invoked.
*
* Note that the XSLTC transformation engine is invoked through its native
* interface and not the javax.xml.transform (JAXP) interface. This because
* XSLTC still does not offer precompiled transformations through JAXP.
*/
public final class TransformServlet extends HttpServlet {
/*
* This is a document cache with 32 document slots. This servlet returns
* cache statistics if the 'stats' parameter is passed with the HTTP
* request in doGet().
*/
private static DocumentCache cache = null;
/**
* Main servlet entry point
*/
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
// Initialise the output writer
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Get the two paramters "class" and "source".
String className = request.getParameter("class");
String documentURI = request.getParameter("source");
try {
// Initialize document cache with 32 DOM slots
if (cache == null) cache = new DocumentCache(32);
if (request.getParameter("stats") != null) {
cache.getStatistics(out);
}
else if ((className == null) || (documentURI == null)) {
out.println("<h1>XSL transformation error</h1>");
out.println("The parameters <b><tt>class</tt></b> and " +
"<b><tt>source</tt></b> must be specified");
}
else {
// Get a reference to the translet class (not object yet)
Class tc = Class.forName(className);
// Instanciate a translet object (inherits AbstractTranslet)
AbstractTranslet translet = (AbstractTranslet)tc.newInstance();
// Set the document cache for the translet. This is needed in
// case the translet uses the document() function.
translet.setDOMCache(cache);
// Read input document from the DOM cache
DOMImpl dom = cache.retrieveDocument(documentURI, 0, translet);
// Initialize the output handler
DefaultSAXOutputHandler saxHandler =
new DefaultSAXOutputHandler(out);
// Start the transformation
final long start = System.currentTimeMillis();
translet.transform(dom, new TextOutput(saxHandler));
final long done = System.currentTimeMillis() - start;
out.println("<!-- transformed by XSLTC in "+done+"msecs -->");
}
}
catch (IOException e) {
out.println("<h1>Error</h1>");
out.println("Could not locate source document: " + documentURI);
out.println(e.toString());
}
catch (ClassNotFoundException e) {
out.println("<h1>Error</h1>");
out.println("Could not locate the translet class: " + className);
out.println(e.toString());
}
catch (SAXException e) {
out.println("<h1>Error</h1>");
out.println("Error parsing document " + documentURI);
}
catch (Exception e) {
out.println("<h1>Error</h1>");
out.println(e.toString());
}
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]