SAXTransformerFactory

Hello Specialists,
I've following problem (the same as described in: [; ...)
A java mapping for rendering PDF based on apache's FOP throws an exception:
javax.xml.transform.TransformerException: java.lang.ClassCastException:
class com.sap.aii.ib.server.mapping.execution.jaxpfactories.MappingTransformerFactory:sap.com/com.sap.xi.repository com.sap.engine.boot.loader.ResourceMultiParentClassLoader ... alive
incompatible with class javax.xml.transform.sax.SAXTransformerFactory:null at
com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:670) at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:300) at de.cceag.pi.mapping.fo.java.FOPHandler.transformPDF(FOPHandler.java:85)
For developing I use NWDS 7.1 and JDK 1.5.0_17 ... I also tried JDK 1.5.0_22. Finally, I tried using the rt.jar from SAPs jvm (.../sapjvm_5/jre/lib).
Here a code snippet:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.MimeConstants;
     public ByteArrayOutputStream transformPDF(ByteArrayInputStream in, ByteArrayOutputStream out)
          throws FOPException, TransformerException {
          // Step 2: Set up output stream.
          // Note: Using BufferedOutputStream for performance reasons (helpful with FileOutputStreams).
          try {
               // Step 3: Construct fop with desired output format
               Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, this.foUserAgent, out);
               // Step 4: Setup JAXP using identity transformer
               TransformerFactory factory = TransformerFactory.newInstance();
               // TransformerFactory factory = TransformerFactoryImpl.newInstance();
               // SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
               // identity transformer
               Transformer transformer = factory.newTransformer();
               // Step 5: Setup input and output for XSLT transformation
               // Setup input stream
               Source src = new StreamSource(in);
               // Resulting SAX events (the generated FO) must be piped through to FOP
               Result res = new SAXResult(fop.getDefaultHandler());
               // Step 6: Start XSLT transformation and FOP processing
               transformer.transform(src, res);
We use PI 7.11 SP6. The 'Use SAP XML Toolkit' option in operation mapping is deactivated.
Any ideas?
Thanks and Regards
André

Hi André,
I'm facing same issue. Did you solve this issue ;if yes,please let me know how you did it.
Regards,
Alok

Similar Messages

  • XSL problem with javax.xml.transform.sax.SAXTransformerFactory

    Dear sirs,
    I use SAXTransformerFactory in order to transform a Hashtable to SAX Event and apply a XSL.
    I try this code with the lastest version of apache parser.
    It run well.
    But, I put this software to WEBLOGIC 6.2 server and no run.
    this check is true:
              if (transFact.getFeature(javax.xml.transform.sax.SAXTransformerFactory.FEATURE)&&transFact.getFeature(javax.xml.transform.sax.SAXSource.FEATURE))
    Some one can help me.
    Thank in avance
    The code:
    java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream();
              com.cajarural.xml.HashtableParser parser = new com.cajarural.xml.HashtableParser(hashtable);
              // Codigo para el TansformerHandler
              // set the destination for the XSLT transformation
                   javax.xml.transform.TransformerFactory transFact = javax.xml.transform.TransformerFactory.newInstance();
                   if (transFact.getFeature(javax.xml.transform.sax.SAXTransformerFactory.FEATURE)&&transFact.getFeature(javax.xml.transform.sax.SAXSource.FEATURE))
    javax.xml.transform.sax.SAXTransformerFactory saxTransFact = (javax.xml.transform.sax.SAXTransformerFactory) transFact;
    javax.xml.transform.sax.TransformerHandler transHand = saxTransFact.newTransformerHandler(templates);
    transHand.setResult(new javax.xml.transform.stream.StreamResult(bout));
    parser.setContentHandler(transHand);
    // attach the XSLT processor to the           parser.parse();
              return new String(bout.toByteArray());

    put Xalan in your war file then try using this kind of commands:     System.setProperty("org.xml.sax.parser", "org.apache.xerces.parsers.SAXParser");
    System.setProperty("javax.xml.parsers.SAXParserFactory", "org.apache.xerces.jaxp.SAXParserFactoryImpl");
    System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
    System.setProperty("javax.xml.transform.TransformerFactory", "org.apache.xalan.processor.TransformerFactoryImpl");This tells JAXP what implementations it should use without even asking your administrator to modify the WebLogic setup...
    It's what I've done with the WLS7.0 server I am using ;-)

  • SAXTransformerFactory.newXMLFilter has no way to setParameter!

    HI friends,
    When doing xslt chain transformation by filter, it seems JXAP's API SAXTransformerFactory.newXMLFilter() has no way to setParameter to transformer!
    Let's see this:
    TransformerFactory tFactory = TransformerFactory.newInstance();
    //check TransformerFactory supports the use of SAXSource ommitted here
    SAXTransformerFactory saxTFactory = ((SAXTransformerFactory) tFactory);
    XMLFilter xsltFilter = saxTFactory.newXMLFilter(new StreamSource("foo.xsl"));But there is no way for this filter to setParameter() to the Transformer.
    I checked the TrAXFilter class in org.apache.xalan.transformer which extends XMLFilterImpl, in its constructor, it simply create Transformer like this:
    m_transformer = (TransformerImpl)templates.newTransformer();
    I am wondering why JAXP does not have newXMLFilter(Source src, String[] parameter) and newXMLFilter(Template template, String[] parameter)methods? It should be very easy to add.
    At this moment, which is the best way to setParameter to newXMLFilter?
    Thanks!

    I have the same problem...
    Download Xalan (xslt processor) and can see two examples:
    1. Pipe
    2. Filters
    "Pipe and UseXMLFilters illustrate two strategies for using the output of one transformation as the input for another transformation. The Pipe sample incorporates a 'push' model -- Transformer1 'pushes' its output to Transformer2, and so on -- whereas in the UseXMLFilters sample, Transformer3 'pulls' its input from Transformer2, and so on."

  • Creating an xml file from java.

    I trying to create an xml file using a java program. I just wondering what is the best way to go about it and what should i use jdom ,xerces sax etc.

    Use JAXP+SAX.
    Here an example:import java.io.*;
    // SAX classes.
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    //JAXP 1.1
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.stream.*;
    import javax.xml.transform.sax.*;
    // PrintWriter from a Servlet
    PrintWriter out = response.getWriter();
    StreamResult streamResult = new StreamResult(out);
    SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    // SAX2.0 ContentHandler.
    TransformerHandler hd = tf.newTransformerHandler();
    Transformer serializer = hd.getTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
    serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"users.dtd");
    serializer.setOutputProperty(OutputKeys.INDENT,"yes");
    hd.setResult(streamResult);
    hd.startDocument();
    AttributesImpl atts = new AttributesImpl();
    // USERS tag.
    hd.startElement("","","USERS",atts);
    // USER tags.
    String[] id = {"PWD122","MX787","A4Q45"};
    String[] type = {"customer","manager","employee"};
    String[] desc = {"Tim@Home","Jack&Moud","John D'o�"};
    for (int i=0;i<id.length;i++)
      atts.clear();
      atts.addAttribute("","","ID","CDATA",id);
    atts.addAttribute("","","TYPE","CDATA",type[i]);
    hd.startElement("","","USER",atts);
    hd.characters(desc[i].toCharArray(),0,desc[i].length());
    hd.endElement("","","USER");
    hd.endElement("","","USERS");
    hd.endDocument();
    [i]This xml generation program might be the best solution because it uses JAXP 1.1 so it will work under JDK 1.4 or JDK 1.2/1.3 with XALAN2 library (or any XML library JAXP 1.1 compliant). It's also memory-friendly because it doesn't need DOM.
    See http://www.javazoom.net/services/newsletter/xmlgeneration.html
    Hope That Helps                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to create new XML file using retreived XML content by using SAX API?

    hi all,
    * How to create new XML file using retreived XML content by using SAX ?
    * I have tried my level best, but output is coming invalid format, my code is follows,
    XMLFileParser.java class :-
    import java.io.StringReader;
    import java.io.StringWriter;
    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerConfigurationException;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMResult;
    import javax.xml.transform.sax.SAXSource;
    import javax.xml.transform.sax.SAXTransformerFactory;
    import javax.xml.transform.sax.TransformerHandler;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import org.xml.sax.Attributes;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.XMLFilterImpl;
    public class PdfParser extends XMLFilterImpl {
        private TransformerHandler handler;
        Document meta_data;
        private StringWriter meta_data_text = new StringWriter();
        public void startDocument() throws SAXException {
        void startValidation() throws SAXException {
            StreamResult streamResult = new StreamResult(meta_data_text);
            SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
            try
                handler = factory.newTransformerHandler();
                Transformer transformer = handler.getTransformer();
                transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                handler.setResult(streamResult);
                handler.startDocument();
            catch (TransformerConfigurationException tce)
                System.out.println("Error during the parse :"+ tce.getMessageAndLocation());
            super.startDocument();
        public void startElement(String namespaceURI, String localName,
                String qualifiedName, Attributes atts) throws SAXException {
            handler.startElement(namespaceURI, localName, qualifiedName, atts);
            super.startElement(namespaceURI, localName, qualifiedName, atts);
        public void characters(char[] text, int start, int length)
                throws SAXException {
            handler.characters(text, start, length);
            super.characters(text, start, length);
        public void endElement(String namespaceURI, String localName,
                String qualifiedName) throws SAXException {
            super.endElement("", localName, qualifiedName);
            handler.endElement("", localName, qualifiedName);
        public void endDocument() throws SAXException {
        void endValidation() throws SAXException {
            handler.endDocument();
            try {
                TransformerFactory transfactory = TransformerFactory.newInstance();
                Transformer trans = transfactory.newTransformer();
                SAXSource sax_source = new SAXSource(new InputSource(new StringReader(meta_data_text.toString())));
                DOMResult dom_result = new DOMResult();
                trans.transform(sax_source, dom_result);
                meta_data = (Document) dom_result.getNode();
                System.out.println(meta_data_text);
            catch (TransformerConfigurationException tce) {
                System.out.println("Error occurs during the parse :"+ tce.getMessageAndLocation());
            catch (TransformerException te) {
                System.out.println("Error in result transformation :"+ te.getMessageAndLocation());
    } CreateXMLFile.java class :-
    Sax.startDocument();
    Sax.startValidation();
    Sax.startElement("", "pdf", "pdf", new AttributesImpl());
    Sax.startElement("", "basic-metadata", "basic-metadata", new AttributesImpl());          
    String xmp_str = new String(meta_data.getByteArray(),"UTF8");
    char[] xmp_arr = xmp_str.toCharArray();
    Sax.characters(xmp_arr, 0, xmp_arr.length);
    Sax.endElement("", "pdf", "pdf");
    Sax.endValidation();
    Sax.endDocument();
    Sax.endElement("", "basic-metadata", "basic-metadata");* In CreateXMLFile.java
    class, I have retreived the xml content in the meta_data object, after that i have converted into character array and this will be sends to SAX
    * In this case , the XML file created successfully but the retreived XML content added as an text in between basic-metadata Element, that is, retreived XML content
    is not an XML type text, it just an Normal text Why that ?
    * Please help me what is the problem in my code?
    Cheers,
    JavaImran

    Sax.startDocument();
    Sax.startValidation();
    Sax.startElement("", "pdf", "pdf", new AttributesImpl());
    Sax.startElement("", "basic-metadata", "basic-metadata", new AttributesImpl());          
    String xmp_str = new String(meta_data.getByteArray(),"UTF8");
    char[] xmp_arr = xmp_str.toCharArray();
    Sax.characters(xmp_arr, 0, xmp_arr.length);
    </code><code>Sax.endElement("", "basic-metadata", "basic-metadata");</code>
    <code class="jive-code jive-java">Sax.endElement("", "pdf", "pdf");
    Sax.endValidation();
    Sax.endDocument();     
    * I HAVE CHANGED MY AS PER YOUR SUGGESTION, NOW SAME RESULT HAS COMING.
    * I AM NOT ABLE TO GET THE EXACT OUTPUT.,WHY THAT ?
    Thanks,
    JavaImran{code}

  • How to convert xslt file into string

    i'm writting a java program to use xslt to transform the xml file. i'm encountering the problem when i try to convert the xslt file into string. i've defined my utility class called 'XmlUtil' to carry out the operation of transform xml file through xslt. but in my main java program i need to convert both xml and xslt file into a string in order to input them in my function argument. my function argument is as follows:
    String htmlString = XmlUtil.applyXsltString(xmlContent, xsltString);
    i've already converted xmlcontent into string by using:
    xmlContent = xmlContentBuffer.toString();
    but i don't know how to convert 'xsltString' now ? i've searched the google for an hour but i cannot find the solution. anyone can help ?
    detail of my souce code is as follow:
    import java.io.*;
    import java.net.*;
    import java.lang.*;
    import java.io.StringReader;
    import java.lang.reflect.Array;
    import java.util.Properties;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.sax.SAXResult;
    import javax.xml.transform.sax.SAXSource;
    import javax.xml.transform.sax.SAXTransformerFactory;
    import javax.xml.transform.sax.TransformerHandler;
    import javax.xml.transform.stream.StreamSource;
    import org.apache.xml.serializer.OutputPropertiesFactory;
    import org.apache.xml.serializer.Serializer;
    import org.apache.xml.serializer.SerializerFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    import org.xml.sax.XMLReader;
    import org.xml.sax.helpers.XMLReaderFactory;
    import XmlUtil;
    public class FileDownload {
    public static void download(String address, String localFileName){
    OutputStream out = null;
    URLConnection conn = null;
    InputStream in = null;
    StringBuffer xmlContentBuffer = new StringBuffer();
    String temp = new String();
    String xmlContent;
    try {
    URL url = new URL(address);
    out = new BufferedOutputStream(
    new FileOutputStream(localFileName));
    conn = url.openConnection();
    in = conn.getInputStream();
    byte[] buffer = new byte[1024];
    int numRead;
    long numWritten = 0;
    System.out.println (in.toString ());
    while ((numRead = in.read(buffer)) != -1) {
    out.write(buffer, 0, numRead);
    numWritten += numRead;
    temp = new String(buffer);
    xmlContentBuffer.append(temp);
    System.out.println(localFileName + "\t" + numWritten);
    xmlContent = xmlContentBuffer.toString();
    String htmlString = XmlUtil.applyXsltString(xmlContent, xsltString);
    } catch (Exception exception) {
    exception.printStackTrace();
    } finally {
    try {
    if (in != null) {
    in.close();
    if (out != null) {
    out.close();
    } catch (IOException ioe) {
    public static void download(String address) {
    int lastSlashIndex = address.lastIndexOf('/');
    if (lastSlashIndex >= 0 &&
    lastSlashIndex < address.length() - 1) {
    download(address, address.substring(lastSlashIndex + 1));
    } else {
    System.err.println("Could not figure out local file name for " + address);
    public static void main(String[] args) {
    for (int i = 0; i < args.length; i++) {
    download(args);
    }

    I don't understand why you need load the XML and XLS files into a String. A Transformer can be constructed from a Source and there is a StreamSouce which can be constructed from an InputStream. The transform() method can take a Source as input and can produce a Result. There is no need to go near a String representation of either the input.

  • Detecting transform errors when using org.xml.sax.XMLFilter

    I am using javax.xml.transform.sax.SAXTransformerFactory.newXMLFilter to transform xml against a pipeline of stylesheets (See function testPipelineTransform in the example below). The process works okay, excepting that I cannot figure out how to detect errors in the transformation process.
    I would like to achieve the same result for the pipeline process as I would for a single transformation using javax.xml.transform.Transformer.setErrorListener. The example below demonstrates how the call to javax.xml.transform.Transformer.setErrorListener does not generate the same result when using org.xml.sax.XMLFilter as it does when using a single transformation.
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.SAXException;
    import org.xml.sax.InputSource;
    import org.xml.sax.XMLReader;
    import org.xml.sax.XMLFilter;
    import javax.xml.transform.ErrorListener;
    import javax.xml.transform.Source;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.TransformerConfigurationException;
    import javax.xml.transform.sax.SAXTransformerFactory;
    import javax.xml.transform.sax.SAXSource;
    import javax.xml.transform.stream.StreamSource;
    import javax.xml.transform.stream.StreamResult;
    import java.io.*;
    public class FilterChain {
        static private final String newline = System.getProperty("line.separator");
         public static void main(String argv[]) {
              System.out.println("Testing pipeline transform");
              testPipelineTransform();
              System.out.println("Testing single transform");
              testXsltSingleTransform();
         } // main
         static private void testPipelineTransform() {
              try {
                   // Set up the input stream
                   BufferedInputStream bis = new BufferedInputStream(
                             new ByteArrayInputStream(getExample().getBytes()));
                   InputSource input = new InputSource(bis);
                   // Set up to read the input file
                   SAXParserFactory spf = SAXParserFactory.newInstance();
                   SAXParser parser = spf.newSAXParser();
                   XMLReader reader = parser.getXMLReader();
                   // Create the filters
                   SAXTransformerFactory stf = (SAXTransformerFactory) TransformerFactory
                             .newInstance();
                   XMLFilter filter1 = stf.newXMLFilter(new StreamSource(new StringReader(getStylesheet1())));
                   XMLFilter filter2 = stf.newXMLFilter(new StreamSource(new StringReader(getStylesheet2())));
                   // Wire the output of the reader to filter1
                   // and the output of filter1 to filter2
                   filter1.setParent(reader);
                   filter2.setParent(filter1);
                   // Set up the output stream
                   StreamResult result = new StreamResult(System.out);
                   // Set up the transformer to process the SAX events generated
                   // by the last filter in the chain
                   Transformer transformer = stf.newTransformer();
                   transformer.setErrorListener(new ErrorListener() {
                        public void error(TransformerException te)
                                  throws TransformerException {
                             System.out.println("Transform generated Transform Error");
                             System.out.println(te.getMessage());
                        public void fatalError(TransformerException te)
                                  throws TransformerException {
                             System.out
                                       .println("Transform generated Transform Fatal Error");
                             System.out.println(te.getMessage());
                        public void warning(TransformerException te)
                                  throws TransformerException {
                             System.out.println("Transform generated Transform Warning");
                             System.out.println(te.getMessage());
                   SAXSource transformSource = new SAXSource(filter2, input);
                   transformer.transform(transformSource, result);
              } catch (TransformerConfigurationException tce) {
                   // Error generated by the parser
                   System.out.println("\n** Transformer Factory error");
                   System.out.println("   " + tce.getMessage());
                   // Use the contained exception, if any
                   Throwable x = tce;
                   if (tce.getException() != null)
                        x = tce.getException();
                   x.printStackTrace();
              } catch (TransformerException te) {
                   // Error generated by the parser
                   System.out.println("\n** Transformation error");
                   System.out.println("   " + te.getMessage());
                   // Use the contained exception, if any
                   Throwable x = te;
                   if (te.getException() != null)
                        x = te.getException();
                   x.printStackTrace();
              } catch (SAXException sxe) {
                   // Error generated by this application
                   // (or a parser-initialization error)
                   Exception x = sxe;
                   if (sxe.getException() != null)
                        x = sxe.getException();
                   x.printStackTrace();
              } catch (ParserConfigurationException pce) {
                   // Parser with specified options can't be built
                   pce.printStackTrace();
         static private void testXsltSingleTransform() {
              try {
                   BufferedInputStream bis = new BufferedInputStream(
                             new ByteArrayInputStream(getExample().getBytes()));
                   // Set up the output stream
                   StreamResult result = new StreamResult(System.out);
                   InputSource input = new InputSource(bis);
                   TransformerFactory factory = TransformerFactory.newInstance();
                   Source source = new StreamSource(new StringReader(getStylesheet2()));
                   Transformer stylesheet = factory.newTransformer(source);
                   stylesheet.setErrorListener(new ErrorListener() {
                        public void error(TransformerException te)
                                  throws TransformerException {
                             System.out.println("Transform generated Transform Error");
                             System.out.println(te.getMessage());
                        public void fatalError(TransformerException te)
                                  throws TransformerException {
                             System.out
                                       .println("Transform generated Transform Fatal Error");
                             System.out.println(te.getMessage());
                        public void warning(TransformerException te)
                                  throws TransformerException {
                             System.out.println("Transform generated Transform Warning");
                             System.out.println(te.getMessage());
                   SAXSource transformSource = new SAXSource(input);
                   stylesheet.transform(transformSource, result);
              } catch (Exception exc) {
                   exc.printStackTrace();
         private static String getStylesheet1() {
              return
                     "<?xml version='1.0' encoding='ISO-8859-1'?>" + newline
                   + "<xsl:stylesheet" + newline
                   + "xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" + newline
                   + "version='1.0'>" + newline
                   + "<xsl:output method='xml'/>" + newline
                   + "<xsl:template match='/'>" + newline
                   + "<DontCareAboutContent></DontCareAboutContent>" + newline
                   + "</xsl:template>" + newline
                   + "</xsl:stylesheet>" + newline;
         private static String getStylesheet2() {
              return
                     "<?xml version='1.0' encoding='ISO-8859-1'?>" + newline
                   + "<xsl:stylesheet" + newline
                   + "xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" + newline
                   + "version='1.0'>" + newline
                   + "<xsl:output method='html'/>" + newline
                   + "<xsl:template match='/'>" + newline
                  + "<html><body>" + newline
                 + "<xsl:message>" + newline
                 + "Error Message for the xslt processor" + newline
                 + "</xsl:message>" + newline
                 + "Dont care about the xslt content," + newline
                 + "The only significant part is the xsl:message element" + newline
                 + "which results in a error to be handled by the xslt" + newline
                 + "processor" + newline
                   + "</body></html>" + newline
                   + "</xsl:template>" + newline
                   + "</xsl:stylesheet>" + newline;
         private static String getExample() {
              return
                     "<?xml version='1.0' encoding='ISO-8859-1'?>" + newline
                   + "<DontCareAboutContent>" + newline
                   + "</DontCareAboutContent>" + newline;
    }

    I made the following change which solves the problem but the sollution is tightly coupled to Xalan. If anyone has any ideas, I would still like to find a way to achieve the desired result using JAXP API's.
                   XMLFilter filter1 = stf.newXMLFilter(new StreamSource(new StringReader(getStylesheet1())));
                   if (filter1 instanceof org.apache.xalan.transformer.TrAXFilter) {
                        ((org.apache.xalan.transformer.TrAXFilter)filter1).getTransformer().setErrorListener(...);
    ...

  • Java stored procedure deployment : resolution problem

    Hi,
    I am trying to upload a Java class (to be able to send mail with attached files).
    At deployment, I have many errors of this type :
    errors : class javax/xml/transform/sax/SAXTransformerFactory
    ORA-29521: referenced name org/xml/sax/XMLFilter could not be found
    This is due to the "upload" of J2EE in the database but I do not find the options to bypass this in the "Deployment Profile Settings".
    I tried to uncheck "-resolve", to check "-noverify", to check "-force" options.
    I tried many combinations of those options but there is nothing to do !
    I even tried to "exclude package tree" in the "Dependency Analyzer Filters" but nothing is working.
    Does anyone has any idea ??
    Thanks,
    Ju.

    Hi everybody.
    I found the solution myself.
    I am posting it because I am sure I am not the onlyone that got that problem...
    The trick is to upload jar files manually by successive calls like
    "loadjava -user [user]/[passwd]@[tnsentry] mail.jar -resolve".
    The result of the commmand could list some errors but we do not care, the upload is done anyway...
    Then, you can upload your classes through JDeveloper.
    I did not managed to upload source files (it produces errors), I only uploaded class files (choose deploy "As Compiled Output Only").
    Also take care to uncheck everything in the "Dependency Analyzer" (you have already uploaded dependencies manually).
    In the "loadjava options", do NOT use "-force" param but use "-resolve" param.
    The only thing you still need to do is to click on "Deploy"...
    That's all folks !

  • Generating XML content with SAX including schema reference

    Hi all, XML newbie question here.
    I'm trying to generate an XML document from a certain file format using SAX, but I can't figure out how to get the generated XML document to include a schema reference.
    Here's the code, it's taken from posts on this forum, so it should be familiar:
    StreamResult streamResult = new StreamResult(out);
            SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
            try {
                TransformerHandler hd = tf.newTransformerHandler();
                Transformer serializer = hd.getTransformer();
                serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
                serializer.setOutputProperty(OutputKeys.INDENT, "yes");
                hd.setResult(streamResult);
                hd.startDocument();
                AttributesImpl atts = new AttributesImpl();
                hd.startElement("http://maul.ddm.apm.bpm.eds.com", "DTR_XML", "DTR_XML", atts);
                hd.endElement("http://maul.ddm.apm.bpm.eds.com", "DTR_XML", "DTR_XML");
                hd.endDocument();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (TransformerConfigurationException e) {
                e.printStackTrace();
            }Here's the output I get:
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <DTR_XML/>
    And I'm looking for output like this (I think - basically I have this dtr_xml.xsd located at the root web directory on http://maul.ddm.apm.bpm.eds.com and I want the generated XML file to reference that schema for validation when parsing):
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <DTR_XML xmlns="http://maul.ddm.apm.bpm.eds.com"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maul.ddm.apm.bpm.eds.com dtr_xml.xsd"/>

    Yes, you've led me along the right track with the attributes stuff. Here's what I've got right now...
    StreamResult streamResult = new StreamResult(out);
            SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
            try {
                TransformerHandler hd = tf.newTransformerHandler();
                Transformer serializer = hd.getTransformer();
                serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
                serializer.setOutputProperty(OutputKeys.INDENT, "yes");
                hd.setResult(streamResult);
                hd.startDocument();
                AttributesImpl atts = new AttributesImpl();
                atts.addAttribute("", "xmlns", "xmlns", "CDATA", "http://maul.ddm.apm.bpm.eds.com");
                atts.addAttribute("", "xsi", "xmlns:xsi", "CDATA", "http://www.w3.org/2001/XMLSchema-instance");
                atts.addAttribute("", "schemaLocation", "xsi:schemaLocation", "CDATA", "http://maul.ddm.apm.bpm.eds.com dtr_xml.xsd");
                hd.startElement("", "DTR_XML", "DTR_XML", atts);
                hd.endElement("", "DTR_XML", "DTR_XML");
                hd.endDocument();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (TransformerConfigurationException e) {
                e.printStackTrace();
            }This produces the output I wanted earlier...
    As for the org.xml.sax.helpers.NamespaceSupport, I can't seem to find any documentation on using it anywhere, and the javadoc is cryptic to me. Maybe it's used internally in SAX for tracking namespaces or something like that.
    Another interesting thing to me is that if I use the code you gave:
    atts.addAttribute("http://www.w3.org/2001/XMLSchema-instance", "schemaLocation",
         "xsi:schemaLocation", "CDATA", "http://maul.ddm.apm.bpm.eds.com dtr_xml.xsd");I don't see "http://www.w3.org/2001/XMLSchema-instance" anywhere in the output. Is SAX ignoring the namespace uri argument? It appears so. The javadoc states that the uri argument is "The Namespace URI, or the empty string if none is available or Namespace processing is not being performed." It would appear that Namespace processing is not being done... but I don't know how to turn it on.

  • Awkward NullPointerException in Xalan transformations

    L.S,
    I'm having a serious problem with XSL transformations using Apache Xalan 2.6.0: a transformation works once, but multiple calls to the method will cause a null-pointer exception to occur within the TrAXFilter object taking care of the transformation.
    The class responsible for transforming any XML messages in our system looks like this (class MessageWriter appearing at line 14 is a JAXB marshalling class we've developed; class FilterManager appearing at line 21 returns an array of 1 hard-coded XMLFilter object):
    public class MessageBuilder {
      private final static SAXParserFactory XML_PARSER = SAXParserFactory.newInstance();
      public static String getXmlMessage(MessageSDO message) {
        String xml = MessageWriter.doMarshal(message);
        try {
          SAXParser parser = XML_PARSER.newSAXParser();
          XMLReader reader = XMLReaderFactory.createXMLReader();
          InputSource srcInput = new InputSource(new StringReader(xml));
          FilterManager ftrManager = (FilterManager) ConfigurationManager.
            getInstance(ConfigurationManager.BOUNDARY).getBean(FilterManager.class);
          XMLFilter[] filters = ftrManager.getOutputFilters(message);
          if (filters.length > 0) {
            for (int i=0;i<filters.length;i++) {
              filters.setParent((i==0)? reader : filters[i-1]);
    Serializer serializer = SerializerFactory.getSerializer(OutputPropertiesFactory.getDefaultMethodProperties("xml"));
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    serializer.setOutputStream(output);
    filters[filters.length-1].setContentHandler(serializer.asContentHandler());
    filters[filters.length-1].parse(srcInput);
    xml = output.toString();
    } catch (Exception e) {
    throw new RuntimeException(e);
    return xml;
    The test I've run (if 2nd block commented out test succeeds, otherwise it fails on that 2nd attempt):
    public void testTransformedOutput() {
      System.out.println("Transformed output test:\n\n");
      MessageSDO msg = MockSDOFactory.getInstance().getMessageSDO();
      String xmlMsg = MessageBuilder.getXmlMessage(msg);
      /*System.out.println("Transformed output test, 2nd pass:\n\n");
        MessageSDO msg2 = MockSDOFactory.getInstance().getMessageSDO();
        String xmlMsg2 = MessageBuilder.getXmlMessage(msg2);*/
    }The exception message:
    java.lang.RuntimeException: java.lang.NullPointerException
    at org.apache.crimson.parser.Parser2.parseInternal(Parser2.java:658)
    at org.apache.crimson.parser.Parser2.parse(Parser2.java:334)
    at org.apache.crimson.parser.XMLReaderImpl.parse(XMLReaderImpl.java:448)
    at org.apache.xalan.transformer.TrAXFilter.parse(TrAXFilter.java:134)
    at org.boundary.helper.MessageBuilder.getXmlMessage(MessageBuilder.java:36)
    // Line 36 in MessageBuilder is:
    // filters[filters.length-1].parse(srcInput);What I don't yet understand is how TrAXFilter manages to somehow not have a parent in the 2nd pass of the test, while it does in the 1st pass. I've tried a few things already, but so far haven't been able to find a solution.
    Does anyone know of a bug like this? Or is it clear to someone what I'm doing completely wrong here? I'd appreciate any help you can offer.

    I've been able to solve this problem and since others might be interested, I thought I'd post the solution here as well.
    It turns out that XMLFilter objects cannot be reused. This isn't documented very well, and undoubtedly doesn't come as a surprise to the more experienced XML specialists out there, but it's something you need to know. As a result, instead of using XMLFilter objects for repetetive transformations, you need to use an alternative, namely [url http://java.sun.com/j2se/1.4.2/docs/api/javax/xml/transform/Templates.html]Templates objects:
    final SAXTransformerFactory FACTORY = (SAXTransformerFactory) TransformerFactory.newInstance();
    File xslFile = new File("someStylesheet.xsl");
    StreamSource src = new StreamSource(xslFile);
    Templates template = FACTORY.newTemplates(src);
    // Later on, you can repeatedly do this:
    String xml = getSomeXMLDocument();
    InputSource srcInput = new InputSource(new StringReader(xml));
    XMLFilter filter = FACTORY.newXMLFilter(template); // Use cached template instead of parsing XSL file every time...
    XMLReader reader = XMLReaderFactory.createXMLReader();
    filter.setParent(reader);
    Serializer serializer = SerializerFactory.getSerializer(OutputPropertiesFactory.getDefaultMethodProperties("xml"));
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    serializer.setOutputStream(output);
    filter.setContentHandler(serializer.asContentHandler());
    filter.parse(srcInput);
    String xml = output.toString();

  • Server to Rich Client sending XML over Http

    I need to send XML data from a Servlet to a rich client over http.
    Currently I am using HttpURLConnection and SaxTransformerFactory to do this.
    Is it better to use SOAP or XML-RPC in this scenario?
    Are there any good online tutorials comparing SOAP, XML-RPC and AXP-Java Net API?
    What are the factors that I need to consider for choosing between these alternatives?
    Please advice. Thanks in advance.

    XML-RPC and SOAP use XML as a way to communicate, but they are used to invoke certain function calls in an application independend manner, not to be used to send XML data. So I'd say it depends on:
    a) what do you do with the XML data?
    b) will you be expanding the application?
    c) how difficult is it to rework the current implementation?

  • Setting Namespace for Xalan

    I'm using JAXP 1.2
    I have a custom sax parser (implements XMLReader) that reads csv files then sends SAX events to a stylesheet for translation. My problem is that Xalan requires a namespace-aware SAX parser. The SAXParserFactory has a method (setNamespaceAware()) which allows you to change this to "true", since the default is "false". Since I'm not using the SAXParserFactory to create my reader, I'm not sure how to set this using my custom parser. I have implemented the setFeature and getFeature by storing the values in a HashMap. See code below. I then execute the setFeature for my parser before I use the translator to set namespace to true.
    csvReader.setFeature("http://xml.org/sax/features/namespace-prefixes",true);
    csvReader.setFeature("http://xml.org/sax/features/namespace",true);
    I'm not sure how to get Xalan to recognize these Features without creating a parser from the Factory. Any ideas?
    /***************** CODE SAMPLE *****************/
    private Map featureMap = new HashMap();
    public boolean getFeature(String name)
    throws SAXNotRecognizedException, SAXNotSupportedException {
    Boolean featureValue = (Boolean) this.featureMap.get(name);
    return (featureValue == null) ? false
    : featureValue.booleanValue();
    public void setFeature(String name, boolean value)
    throws SAXNotRecognizedException, SAXNotSupportedException {
    this.featureMap.put(name, new Boolean(value));
    }

    Here's some code I have in production:SAXParserFactory spf = SAXParserFactory.newInstance();
    XMLReader reader = spf.newSAXParser().getXMLReader();
    reader.setContentHandler(handler);
    reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
    reader.setFeature("http://xml.org/sax/features/namespaces", true);
    reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);And here's the method that produces the "handler" object:private synchronized TransformerHandler getHandler(String xslFile) throws TransformerConfigurationException {
      SAXTransformerFactory factory = (SAXTransformerFactory)TransformerFactory.newInstance();
      Templates t = (Templates)templates.get(xslFile);
      if (t == null) {
        t = factory.newTemplates(new StreamSource(new File(getServletContext().getRealPath(xslFile))));
        templates.put(xslFile, t);
      return factory.newTransformerHandler(t);
    }This works for me. The difference is that I am using Saxon instead of Xalan to do the transformation, and possibly that is a significant difference.

  • SAX Transformation

    Hi,
    I have a problem with creating a SAX Parser on the PI 7.1 server. I get the following error in the log when I test the code in the repository and in the message flow. 
    com.sap.aii.ib.server.mapping.execution.jaxpfactories.MappingTransformerFactory:sap.com/com.sap.xi.repository[AT]com.sap.engine.boot.loader.ResourceMultiParentClassLoader[AT]42c4e790[AT]alive incompatible with class javax.xml.transform.sax.SAXTransformerFactory:null
    [AT]= @
    When I run the code on my local computer I dont get any problems. Does anybody know how I set up a SAX parser.
    I currently use the following code.
         public void execute(InputStream is, OutputStream out)
         throws StreamTransformationException {
              try{
                   //setup output handler
                    SAXTransformerFactory factory =
                            (SAXTransformerFactory) SAXTransformerFactory.newInstance();
                 th = factory.newTransformerHandler();
                 Result r = new StreamResult(out);
                 th.setResult(r);
                   // create parser
                   DefaultHandler handler = this;
                   SAXParserFactory parserFactory = SAXParserFactory.newInstance();
                   SAXParser saxParser = parserFactory.newSAXParser();
                   saxParser.parse(is, handler);
              }catch(Exception e){
                   trace.addWarning(e.toString());
    Best regards
    Daniel Graversen.
    [Figaf|http://figaf.com]

    It seems like will work on PI 7.31 systems.
    com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl
         factoryParser = new com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl();

  • Writing XML files

    Hello all
    There's a vast amount of information on the java.sun.com site about parsing XML files:
    * creating DOM trees in memory from an XML file
    * setting up event handlers to be called when an XML file is parsed
    * transforming XML files using XSL.
    However, I can find very little information anywhere about writing XML files in the first place! I'm already aware of two ways to do this:
    (1) create a DOM in memory and write this to a file. If the data is large, though, this isn't feasible.
    (2) just output the XML elements directly to some file as text. This doesn't take account of the encoding, or special characters, and the document is not necessarily then syntactically valid.
    Is there some API which I haven't yet come across that is designed specifically for writing XML data to files? If it's built in to Java 2, then goodness knows how I've missed it all this time; if it's third-party, I'd be grateful for any links.
    Thanks for your help
    Rich Fearn

    I know pastes can be horrible, but this is a working example which I find useful: SAX XML output ;)
    import java.io.*;
    // SAX classes.
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    //JAXP 1.1
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.stream.*;
    import javax.xml.transform.sax.*;
                    //AlphabetXMLOut(file, alphabets);
    class AlphabetXMLOut {
            public void run(){
                    try{
                            FileOutputStream fos = new FileOutputStream("output.xml");
                            PrintWriter out = new PrintWriter(fos);
                            StreamResult streamResult = new StreamResult(out);
                            // PrintWriter from a Servlet
                            //PrintWriter out = response.getWriter();
                            //StreamResult streamResult = new StreamResult(out);
                            SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
                            // SAX2.0 ContentHandler.
                            TransformerHandler hd = tf.newTransformerHandler();
                            Transformer serializer = hd.getTransformer();
                            serializer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
                            serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"users.dtd");
                            serializer.setOutputProperty(OutputKeys.INDENT,"yes");
                            hd.setResult(streamResult);
                            hd.startDocument();
                            AttributesImpl atts = new AttributesImpl();
                            // USERS tag.
                            hd.startElement("","","USERS",atts);
                            // USER tags.
                            String[] id = {"PWD122","MX787","A4Q45"};
                            String[] type = {"customer","manager","employee"};
                            String[] desc = {"Tim@Home","Jack&Moud","John D'oe"};
                            for (int i=0;i<id.length;i++){
                                    atts.clear();
                                    atts.addAttribute("","","ID","CDATA",id);
    atts.addAttribute("","","TYPE","CDATA",type[i]);
    hd.startElement("","","USER",atts);
    hd.characters(desc[i].toCharArray(),0,desc[i].length());
    hd.endElement("","","USER");
    hd.endElement("","","USERS");
    hd.endDocument();
    fos.close();
    }catch (IOException e){
    System.err.println ("Unable to write to file");
    System.exit(-1);
    }catch (TransformerConfigurationException tce){
    System.err.println("Error in: TransformerConfigurationException");
    }catch (SAXException spe) {
    // Error generated by the parser
    System.err.println("Error in: (SAXException");
    // Use the contained exception, if any
    Exception x = spe;
    if (spe.getException() != null)
    x = spe.getException();
    x.printStackTrace();
    -Hope this helps

  • What to do with SAX events

    I want to iterate over a database recordset and generate sax events to create a virtual xml document. But I'm struggling to see how the events are consumed.
    What do I do with the events that are generated by the strart/end document and element handlers. How do I send to a file, or better still, pass the events onto some tool to output as html/xml pages?
    Cheers again
    -thanks 4earlier code @Trejkaz

    All the examples I have ever seen of SAX are like this:
    You take an XML document and give it to a SAX parser. The SAX parser turns it into a stream of SAX events and calls your handler's startElement() etc. methods, which generally write to a file or something like that.
    Your requirement is the reverse, namely you want to input from the "something like that", make a stream of SAX events, and have those turned into an XML document. I have never seen a decent example of this so I had to work it out for myself. I posted my solution in this forum several months ago but I can't find it now. So here it is again:SAXTransformerFactory factory = (SAXTransformerFactory)TransformerFactory.newInstance();
    TransformerHandler handler = factory.newTransformerHandler();
    // if you want to use XSL to transform what you produce then
    // you need the version that takes a Templates argument.
    handler.setResult(new StreamResult(response.getWriter()));
    // in my case I send the resulting XML document to the servlet
    // response, but you could send it somewhere else.
    SAXParserFactory spf = SAXParserFactory.newInstance();
    XMLReader reader = spf.newSAXParser().getXMLReader();
    reader.setContentHandler(handler);
    reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
    reader.setFeature("http://xml.org/sax/features/namespaces", true);
    reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
    handler.startDocument();
    startElement(handler, "Doc");
    // I am producing an XML document whose root is a Doc element.
    // Send more SAX events here.
    endElement(handler, "Doc");
    handler.endDocument();

Maybe you are looking for