morten      01/05/03 08:42:28

  Added:       java/src/org/apache/xalan/xsltc/demo/applet
                        TransformApplet.java
               java/src/org/apache/xalan/xsltc/demo/brazil
                        TransformHandler.java
               java/src/org/apache/xalan/xsltc/demo/servlet Compile.java
                        Transform.java
  Log:
  Added 3 demos that show how translets can be run in an applet, servlet
  or brazil handler. (Brazil is a prototype from sunlabs that web-enables
  applications without the need for a web server.)
  
  Revision  Changes    Path
  1.1                  
xml-xalan/java/src/org/apache/xalan/xsltc/demo/applet/TransformApplet.java
  
  Index: TransformApplet.java
  ===================================================================
  /*
   * @(#)$Id: TransformApplet.java,v 1.1 2001/05/03 15:42:19 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.applet;
  
  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.*;
  
  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/src/org/apache/xalan/xsltc/demo/brazil/TransformHandler.java
  
  Index: TransformHandler.java
  ===================================================================
  /*
   * @(#)$Id: TransformHandler.java,v 1.1 2001/05/03 15:42:23 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 class implements the Handler interface from the Brazil project
   * http://www.sun.com/research/brazil/
   */
  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/src/org/apache/xalan/xsltc/demo/servlet/Compile.java
  
  Index: Compile.java
  ===================================================================
  /*
   * @(#)$Id: Compile.java,v 1.1 2001/05/03 15:42:26 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/src/org/apache/xalan/xsltc/demo/servlet/Transform.java
  
  Index: Transform.java
  ===================================================================
  /*
   * @(#)$Id: Transform.java,v 1.1 2001/05/03 15:42:27 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 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.*;
  
  public final class Transform 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 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]

Reply via email to