You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@xalan.apache.org by JJAR <jj...@eresmas.com> on 2001/01/12 18:33:12 UTC

Problem with a simple servlet (that works using using Xalan 1.2.2) when using Xalan 2.0 and TrAX

Hi I have a problem and I would like to know if it is a BUG or I am DUMB:

I have modified "SimpleTransform.java" and it is working, now it looks like
this:

/***************************************************************************
***************************/

// Imported TraX classes
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;


// Imported java classes
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 *  Use the TraX interface to perform a transformation in the simplest
manner possible
 *  (3 statements).
 */
public class SimpleTransform
{
    private TransformerFactory tFactory;
    private Templates docbookTemplate;

    public static void main(String[] args)
        throws  TransformerException, TransformerConfigurationException,
                FileNotFoundException, IOException
    {
        // Use the static TransformerFactory.newInstance() method to
instantiate
        // a TransformerFactory. The javax.xml.transform.TransformerFactory
        // system property setting determines the actual class to
instantiate --
        // org.apache.xalan.transformer.TransformerImpl.
        tFactory = TransformerFactory.newInstance();

        // Use the TransformerFactory to instantiate a Transformer that will
work with
        // the stylesheet you specify. This method call also processes the
stylesheet
        // into a compiled Templates object.
        docbookTemplate = tFactory.newTemplates( new StreamSource(
"TutorialXml.db.html.xsl" ) );
        Transformer transformer = docbookTemplate.newTransformer();

        // Use the Transformer to apply the associated Templates object to
an XML document
        // (foo.xml) and write the output to a file (foo.out).
        transformer.transform(new StreamSource( new FileInputStream(
"TutorialXml.db.xml" ) ), new StreamResult( new FileOutputStream(
"TutorialXml.html" ) ) );

        System.out.println("************* The result is in birds.out
*************");
    }
}

/***************************************************************************
***************************/





And I am trying to make a servlet,using Tomcat 3.2.1, making exactly the
same with the same files. The code looks like this:



/***************************************************************************
***************************/
package com.objectier.servlet;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;

//importaciones para la transformación del XML
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.Templates;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;

public class WebsiteTrAX extends HttpServlet
{
    private String baseURL = "http://objectier/website/";
    private String baseDir = "C:/org/apache/tomcat/webapps/website/";

    //private Templates docbookTemplate;
    //private TransformerFactory transFactory;

    public void init() throws ServletException
    {
        super.init();
        /*transFactory = TransformerFactory.newInstance();
        try {
            docbookTemplate = transFactory.newTemplates( new StreamSource(
new FileInputStream( baseDir + "TutorialXml.db.html.xsl" )  )  );
        }
        catch ( TransformerConfigurationException eTransConf ) {
            System.out.println( "Error al generar el Template" +
eTransConf.toString() );
            log( "Error al generar el Template", eTransConf);
        }
        catch ( FileNotFoundException eFNF ) {
            System.out.println( "Error al obtener el archivo con la hoja de
transformacines: " + eFNF.toString() );
            log( "Error al obtener el archivo con la hoja de
transformacines: ", eFNF );
        }*/
    }

    public void service( HttpServletRequest req, HttpServletResponse resp )
    {
        String userAgent = req.getHeader( "user-agent" );

        if ( userAgent.indexOf( "WAP" ) != -1 ) {
            doGetWAP( req, resp );
        }
        else {
            doGetHTTP( req, resp );
        }
    }

    public void doGetWAP( HttpServletRequest req, HttpServletResponse resp )
    {
        resp.setContentType( "text/vnd.wap.wml" );
        try {
            resp.sendRedirect( baseURL + "modDeResult.wml" );
        }
        catch ( IOException eIO ) {
            System.out.println( "Se produjo un error al redireccionar un
móvil WAP:" + eIO.toString() );
            log( "Se produjo un error al redireccionar un móvil WAP:",
eIO );
        }
    }

    public void doGetHTTP( HttpServletRequest req, HttpServletResponse
resp )
    {
        resp.setContentType( "text/html" );
        try {
            TransformerFactory transFactory =
TransformerFactory.newInstance();
            try {
                Transformer trans = transFactory.newTransformer( new
StreamSource( new FileInputStream( baseDir +
"TutorialXml.db.html.xsl" ) ) );//docbookTemplate.newTransformer();
                try {
                    trans.transform( new StreamSource( new
FileInputStream( baseDir + "TutorialXml.db.xml" ) ), new StreamResult(
resp.getWriter() ) );
                }
                catch ( TransformerException eTrans) {
                    System.out.println( "Falló el proceso de transformación"
+ eTrans.toString() );
                    log( "Falló el proceso de transformación", eTrans );
                }
            }
            catch ( TransformerConfigurationException eTransConf ) {
                System.out.println( "Error la crear el Transformer a partir
del Template" + eTransConf.toString() );
                log( "Error la crear el Transformer a partir del Template",
eTransConf );
            }
        }
        catch ( IOException eIO ) {
            System.out.println( "Error al crear el flujo de salida." +
eIO.toString() );
            log( "Error al crear el flujo de salida.", eIO );
        }
    }
}
/***************************************************************************
***************************/

In the beginning I thought there was something wrong with using
"javax.xml.transform.Templates" but as you can see I have removed this.
I thought it could be a deployment problem so I did the same servlet doing
it with Xalan 1.2.2 and it worked fine with the same deployment (changing
<servlet-class>...</servlet-class>).
I thought it could be a classpath problem because tomcat includes Sun's
parse.jar and jaxp.jar files so I tried unzipping xerces.jar and xalan.jar
and putting them under the classes directory under the servlet deployment
directory.
I thought it could be a problem with biding so I included "jaxp.properties"
in every lib directoy:

C:\Archivos de programa\JavaSoft\JRE\1.3\lib
C:\java\jdk1.3\lib
C:\java\jdk1.3\jre\lib

I also tried including the .properties files included inside the
jar-packaged Xalan 2.0:

javax.xml.parsers.DocumentBuilderFactory
javax.xml.parsers.SAXParserFactory
javax.xml.transform.TransformerFactory

The Tomcat's log file has this output (always the same):

Iniciando tomcat. Comprueba el archivo logs/tomcat.log si hay errores
Error la crear el Transformer a partir del Template
javax.xml.transform.TransformerConfigurationException: Namespace not
supported by SAXParser

in English:

Beginig tomcat. Check file logs/tomcat.log if there are errors
Error creating Transformer from the Template	//I have added this myself but
i have removed Templates 								//so it means a problem with the
Transformer
javax.xml.transform.TransformerConfigurationException: Namespace not
supported by SAXParser

I also tried removing the DOCTYPE declaration from the .xml file.

Here is the same thing but using Xerces 1.2.2 (this works):

/***************************************************************************
***************************/
package com.objectier.servlet;

//importtaciones para el servlet
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

//importaciones para la transformación del XML
import org.apache.xalan.xslt.XSLTProcessorFactory;
import org.apache.xalan.xslt.XSLTProcessor;
import org.apache.xalan.xslt.XSLTInputSource;
import org.apache.xalan.xslt.XSLTResultTarget;
import org.xml.sax.SAXException;

public class WebsiteServlet extends HttpServlet
{
    private String baseURL = "http://objectier/website/";
    private String baseDir = "C:/org/apache/tomcat/webapps/website/";


    public void init() throws ServletException
    {
        super.init();
    }

    public void service( HttpServletRequest req, HttpServletResponse resp )
    {
        String userAgent = req.getHeader( "user-agent" );

        if ( userAgent.indexOf( "WAP" ) != -1 ) {
            doGetWAP( req, resp );
        }
        else {
            doGetHTTP( req, resp );
        }
    }

    public void doGetWAP( HttpServletRequest req, HttpServletResponse resp )
    {
        resp.setContentType( "text/vnd.wap.wml" );
        try {
            resp.sendRedirect( baseURL + "modDeResult.wml" );
        }
        catch ( IOException eIO ) {
            System.out.println( "Se produjo un error al redireccionar un
móvil WAP:" + eIO.toString() );
        }
    }

    public void doGetHTTP( HttpServletRequest req, HttpServletResponse
resp )
    {
        try {
            XSLTProcessor xmlProcessor =
XSLTProcessorFactory.getProcessor();
            try {
                XSLTInputSource docbookArticleXml = new XSLTInputSource( new
FileInputStream( baseDir + "TutorialXml.db.xml" ) );
                XSLTInputSource docbookArticleXsl = new XSLTInputSource( new
FileInputStream( baseDir + "TutorialXml.db.html.xsl" ) );
                try {
                    XSLTResultTarget docbookArticleHtml = new
XSLTResultTarget( resp.getWriter() );
                    try {
                        xmlProcessor.process( docbookArticleXml,
docbookArticleXsl, docbookArticleHtml );
                    }
                    catch ( SAXException eSAX ) {
                        System.out.println( "Error durante la
transformación: " + eSAX.toString() );
                    }
                }
                catch ( IOException eIO ) {
                    System.out.println( "Error al obtener el flujo de
salida."  + eIO.toString() );
                }
            }
            catch ( FileNotFoundException eFNF ) {
                System.out.println( "Archivo no encontrado: " +
eFNF.toString() );
            }
        }
        catch ( SAXException eSAX ) {
            System.out.println( "Error al obtener el procesador: " +
eSAX.toString() );
        }
    }
}
/***************************************************************************
***************************/

And finally I have attached the files if you want to give them a try.
TutorialXml.html is made with modified SimpleTransform.java . I have used
DocBook 4.1.2 to write TutorialXml.db.xml

Thank you in advance for your help.
Sorry for the lengthy e-mail, this drives me crazy, I can't find the logiX
;)

Doctype Definition

Posted by Edierley Messias <ed...@dcc.ufmg.br>.
Hello Xalan people,

In my xml document a have the doctype declaration:
--------------------------------------------------------------------
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://www.wapforum.org/DTD/wml_1.1.xml">
<wml>
  <card id="a">
    <p>
      Hello.
    </p>
  </card>
</wml>

When a use the XalanJ-1.2 processor to copy the xml document, the Xalan
contacts the site wapforum and take the DTD definition to the document,
like this (I took of many lines to show better in the email):

<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- 
Wireless Markup Language (WML) Document Type Definition.
Copyright Wireless Application Protocol Forum Ltd., 1998,1999.
                      All rights reserved.
<!-- Navigation and event elements -->
<!-- card intrinsic events -->
<!-- card field types -->
<!-- ampersand -->
<!-- 
Copyright Wireless Application Protocol Forum Ltd., 1998,1999.
                      All rights reserved. 
-->
<wml>
  <card id="a">
    <p>
      Hello.
    </p>
  </card>
</wml>    

I want to Xalan to copy the <!DOCTYPE> declaration, and not
replace with the DTD definition.
Can I do this in Xalan?

And if I do not put the <!DOCTYPE> declaration, and put some entity like
&nbsp; the Xalan show the following error:
 
  XSLT: The entity "nbsp" was referenced, but not declared.
  Xalan: was not successful.

Well, I need the entity referenced and declared, but I can't put the DTD
definition in the document, I wante only the <!DOCTYPE> declaration.

Any ideas?
Thank you very much in advance.

_________________________
Edierley Messias
www.dcc.ufmg.br/~edierley
icq 32943484


DOCTYPE

Posted by Edierley Messias <ed...@dcc.ufmg.br>.
Hello Xalan people,

In my xml document a have the doctype declaration:
--------------------------------------------------------------------
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://www.wapforum.org/DTD/wml_1.1.xml">
<wml>
  <card id="a">
    <p>
      Hello.
    </p>
  </card>
</wml>

When a use the XalanJ-1.2 processor to copy the xml document, the Xalan
contacts the site wapforum and take the DTD definition to the document,
like this (I took of many lines to show better in the email):

<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- 
Wireless Markup Language (WML) Document Type Definition.
Copyright Wireless Application Protocol Forum Ltd., 1998,1999.
                      All rights reserved.
<!-- Navigation and event elements -->
<!-- card intrinsic events -->
<!-- card field types -->
<!-- ampersand -->
<!-- 
Copyright Wireless Application Protocol Forum Ltd., 1998,1999.
                      All rights reserved. 
-->
<wml>
  <card id="a">
    <p>
      Hello.
    </p>
  </card>
</wml>    

I want to Xalan to copy the <!DOCTYPE> declaration, and not
replace with the DTD definition.
Can I do this in Xalan?

And if I do not put the <!DOCTYPE> declaration, and put some entity like
&nbsp; the Xalan show the following error:
 
  XSLT: The entity "nbsp" was referenced, but not declared.
  Xalan: was not successful.

Well, I need the entity referenced and declared, but I can't put the DTD
definition in the document, I wante only the <!DOCTYPE> declaration.

Any ideas?
Thank you very much in advance.

_________________________
Edierley Messias
www.dcc.ufmg.br/~edierley
icq 32943484


Re: Simple Servlet

Posted by Schaufler Andreas <an...@gmx.de>.
Hello,

have a look at this. It is not optimized code nor well structured, because 
it's code I'm playing with at the moment.

In the BaseServlet I put a method, that does xslTransform from a xml DOM, 
using a XSL File and putting the output into a OutputStream.

The inherited servlet transforms a ResultSet from a SQL Query into an XML 
structure. This strucure is then transformed by the inherited xslTransform 
method.

Hope this helps

-Andreas

public class BaseCDServlet extends HttpServlet {

    protected Connection conn;
    protected Properties cfg;
    private TransformerFactory tFactory;

    public void init()
          throws ServletException {
      super.init();
      try {
         cfg = new Properties();
	 cfg.load(new FileInputStream(new 
File(getClass().getResource("/cd-dat.properties").getFile())));

         Driver driver = 
(Driver)Class.forName(cfg.getProperty("jdbcDriver")).newInstance();
         DriverManager.registerDriver(driver);
         conn =
            DriverManager.getConnection(cfg.getProperty("jdbcURL"),
	                                cfg.getProperty("jdbcUser"),
					cfg.getProperty("jdbcPWD"));

	 tFactory = TransformerFactory.newInstance();


      }
      catch (Exception e) {
         e.printStackTrace();
      }
   }



   protected Document getNewDOMDocument() throws Exception {
      DocumentBuilderFactory dfactory;
      DocumentBuilder docBuilder;
      dfactory = DocumentBuilderFactory.newInstance();
      docBuilder = dfactory.newDocumentBuilder();
      return docBuilder.newDocument();
   }

   protected void xslTransform(Document xml, java.io.File xsl, 
java.io.OutputStream out) {

  try {
	 Source xslSource = new StreamSource(xsl);
              Transformer transformer = tFactory.newTransformer(xslSource);
	 transformer.transform(new DOMSource(xml), new StreamResult(out));
      }
      catch (Exception e) {
         e.printStackTrace();
      }
   }
}

public class QueryCDsServlet extends BaseCDServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

      response.setContentType("text/html");
      try {
         Statement s = conn.createStatement();
         ResultSet res = s.executeQuery("SELECT * FROM cd WHERE type='" + 
request.getParameter("type") + "' ORDER BY artist");

         Document xmldoc = getNewDOMDocument();
	 xmldoc.appendChild(xmldoc.createElement("ALLECDS"));
	 
xmldoc.getDocumentElement().setAttribute("type",request.getParameter("type"));

	 res.beforeFirst();
	 while(res.next()) {
            Element newCDElement = xmldoc.createElement("CD");
	    Element newArtistElement = xmldoc.createElement("ARTIST");
	    Element newAlbumElement = xmldoc.createElement("ALBUM");

	    
newArtistElement.appendChild(xmldoc.createTextNode(res.getString("artist")));
	    
newAlbumElement.appendChild(xmldoc.createTextNode(res.getString("albumtitel")));

            newCDElement.appendChild(newArtistElement);
	    newCDElement.appendChild(newAlbumElement);

	    xmldoc.getDocumentElement().appendChild(newCDElement);
         }
         xslTransform(xmldoc, new   
File(getClass().getResource("/XSL/QueryCDs.xsl").getFile()), 
response.getOutputStream());
       }
       catch (Exception e) {
	  e.printStackTrace();
       }
   }
}

On Saturday 27 January 2001 20:28, you wrote:
> Hi people,
>
> Does anyone has a simple Servlet code to transform a file.xml with a
> file.xsl to a response in HTML?
>
> The servlet-sample with the xalan distribution is very good, but I
> want to do a simple transform with xalan-servlet, without to wrote all
> that class.
>
> Thanks in advance.

Simple Servlet

Posted by Edierley Messias <ed...@dcc.ufmg.br>.
Hi people,

Does anyone has a simple Servlet code to transform a file.xml with a
file.xsl to a response in HTML?

The servlet-sample with the xalan distribution is very good, but I 
want to do a simple transform with xalan-servlet, without to wrote all
that class.

Thanks in advance.