xmlgraphics-batik-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Karl_Lars...@salvationarmy.org
Subject RE: NullPointerException
Date Wed, 08 Jan 2003 14:11:17 GMT

Hi Thomas,

TD> Doh! You didn't print out 'parser'. I wanted to know if it was NULL. :)

Nope :-)

XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.crimson.parser.XMLReaderImpl");
XMLResourceDescriptor.setXMLParserClassName("org.apache.crimson.parser.XMLReaderImpl");
System.out.println(parser);

Gives:

"org.apache.crimson.parser.XMLReaderImpl@6b3f271c"

TD> Hmm, your line numbers aren't matching my source (not even close enoguht to help really)...
 What version of Batik
are you using? (or easier for me can you send me the SAXDocumentFactory.java and SAXSVGDocumentFactory.java
you are
using).

I downloaded 'batik-src-1.1.1.zip  18-Dec-2001 01:49' and built the jar files using the debug
option.

Here's SAXDocumentFactory.java (C:\Batik\xml-batik\sources\org\apache\batik\dom\util):

/*****************************************************************************
 * Copyright (C) The Apache Software Foundation. All rights reserved.        *
 * ------------------------------------------------------------------------- *
 * This software is published under the terms of the Apache Software License *
 * version 1.1, a copy of which has been included with this distribution in  *
 * the LICENSE file.                                                         *
 *****************************************************************************/

package org.apache.batik.dom.util;

import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.IOException;
import java.io.Reader;

import org.apache.batik.css.ElementWithID;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.DOMException;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

/**
 * This class contains methods for creating Document instances
 * from an URI using SAX2.
 *
 * @author <a href="mailto:stephane@hillion.org">Stephane Hillion</a>
 * @version $Id: SAXDocumentFactory.java,v 1.5 2001/11/06 09:40:34 hillion Exp $
 */
public class SAXDocumentFactory
    extends    DefaultHandler
    implements LexicalHandler,
               DocumentFactory {

    /**
     * The DOM implementation used to create the document.
     */
    protected DOMImplementation implementation;

    /**
     * The SAX2 parser classname.
     */
    protected String parserClassName;

    /**
     * The created document.
     */
    protected Document document;

    /**
     * The created document descriptor.
     */
    protected DocumentDescriptor documentDescriptor;

    /**
     * Whether a document descriptor must be generated.
     */
    protected boolean createDocumentDescriptor;

    /**
     * The current node.
     */
    protected Node currentNode;

    /**
     * The locator.
     */
    protected Locator locator;

    /**
     * Whether the parser currently parses a CDATA section.
     */
    protected boolean inCDATA;

    /**
     * Whether the parser currently parses a DTD.
     */
    protected boolean inDTD;

    /**
     * Whether the parser is in validating mode.
     */
    protected boolean isValidating;

    /**
     * Whether the document element has been parsed.
     */
    protected boolean documentElementParsed;

    /**
     * The stack used to store the namespace URIs.
     */
    protected HashTableStack namespaces;

    /**
     * Creates a new SAXDocumentFactory object.
     * No document descriptor will be created while generating a document.
     * @param impl The DOM implementation to use for building the DOM tree.
     * @param parser The SAX2 parser classname.
     */
    public SAXDocumentFactory(DOMImplementation impl,
                              String parser) {
      implementation           = impl;
      parserClassName          = parser;
    }

    /**
     * Creates a new SAXDocumentFactory object.
     * @param impl The DOM implementation to use for building the DOM tree.
     * @param parser The SAX2 parser classname.
     * @param dd Whether a document descriptor must be generated.
     */
    public SAXDocumentFactory(DOMImplementation impl,
                              String parser,
                              boolean dd) {
      implementation           = impl;
      parserClassName          = parser;
        createDocumentDescriptor = dd;
    }

    /**
     * Creates a Document instance.
     * @param ns The namespace URI of the root element of the document.
     * @param root The name of the root element of the document.
     * @param uri The document URI.
     * @exception IOException if an error occured while reading the document.
     */
    public Document createDocument(String ns, String root, String uri)
        throws IOException {
        return createDocument(ns, root, uri, new InputSource(uri));
    }

    /**
     * Creates a Document instance.
     * @param ns The namespace URI of the root element of the document.
     * @param root The name of the root element of the document.
     * @param uri The document URI.
     * @param is The document input stream.
     * @exception IOException if an error occured while reading the document.
     */
    public Document createDocument(String ns, String root, String uri,
                           InputStream is) throws IOException {
        InputSource inp = new InputSource(is);
        inp.setSystemId(uri);
        return createDocument(ns, root, uri, inp);
    }

    /**
     * Creates a Document instance.
     * @param ns The namespace URI of the root element of the document.
     * @param root The name of the root element of the document.
     * @param uri The document URI.
     * @param r The document reader.
     * @exception IOException if an error occured while reading the document.
     */
    public Document createDocument(String ns, String root, String uri, Reader r)
        throws IOException {
        InputSource inp = new InputSource(r);
        inp.setSystemId(uri);
        return createDocument(ns, root, uri, inp);
    }

    /**
     * Creates a GenericDocument.
     * @param ns The namespace URI of the root element.
     * @param root The name of the root element.
     * @param uri The document URI.
     * @param is  The document input source.
     * @exception IOException if an error occured while reading the document.
     */
    protected Document createDocument(String ns, String root, String uri,
                                      InputSource is)
      throws IOException {
      document = implementation.createDocument(ns, root, null);

      try {
            XMLReader parser = XMLReaderFactory.createXMLReader(parserClassName);

            parser.setContentHandler(this);
            parser.setDTDHandler(this);
            parser.setEntityResolver(this);
            parser.setErrorHandler(this);

            parser.setFeature("http://xml.org/sax/features/namespaces",
                        true);
            parser.setFeature("http://xml.org/sax/features/namespace-prefixes",
                              true);
          parser.setFeature("http://xml.org/sax/features/validation",
                        isValidating);
          parser.setProperty("http://xml.org/sax/properties/lexical-handler",
                         this);
            parser.parse(is);
      } catch (SAXException e) {
            Exception ex = e.getException();
            if (ex != null && ex instanceof InterruptedIOException) {
                throw (InterruptedIOException)ex;
            }
            throw new IOException(e.getMessage());
      }

      return document;
    }

    /**
     * Returns the document descriptor associated with the latest created
     * document.
     * @return null if no document or descriptor was previously generated.
     */
    public DocumentDescriptor getDocumentDescriptor() {
        return documentDescriptor;
    }

    /**
     * <b>SAX</b>: Implements {@link
     * org.xml.sax.ContentHandler#setDocumentLocator(Locator)}.
     */
    public void setDocumentLocator(Locator l) {
        locator = l;
    }

    /**
     * Sets whether or not the XML parser will validate the XML document
     * depending on the specified parameter.
     *
     * @param isValidating indicates that the XML parser will validate the XML
     * document
     */
    public void setValidating(boolean isValidating) {
      this.isValidating = isValidating;
    }

    /**
     * Returns true if the XML parser validates the XML stream, false otherwise.
     */
    public boolean isValidating() {
      return isValidating;
    }

    /**
     * <b>SAX</b>: Implements {@link
     * org.xml.sax.ContentHandler#startDocument()}.
     */
    public void startDocument() throws SAXException {
        namespaces = new HashTableStack();
      namespaces.put("xml", XMLSupport.XML_NAMESPACE_URI);
      namespaces.put("xmlns", XMLSupport.XMLNS_NAMESPACE_URI);
      namespaces.put("", null);

      documentElementParsed = false;
        inCDATA = false;
        inDTD = false;
      currentNode = document;

        if (createDocumentDescriptor) {
            documentDescriptor = new DocumentDescriptor();
        } else {
            documentDescriptor = null;
        }
    }

    /**
     * <b>SAX</b>: Implements {@link
     * ContentHandler#startElement(String,String,String,Attributes)}.
     */
    public void startElement(String     uri,
                       String     localName,
                       String     rawName,
                       Attributes attributes) throws SAXException {
        // Check for interruption.
        if (Thread.currentThread().isInterrupted()) {
            throw new SAXException(new InterruptedIOException());
        }

      // Namespaces resolution
      int len = attributes.getLength();
      namespaces.push();
      for (int i = 0; i < len; i++) {
          String aname = attributes.getQName(i);
          if (aname.equals("xmlns")) {
            namespaces.put("", attributes.getValue(i));
          } else {
            if (aname.startsWith("xmlns:")) {
                int idx = aname.indexOf(':');
                namespaces.put(aname.substring(idx + 1),
                           attributes.getValue(i));
            }
          }
      }

      // Element creation
      Element e;
      int idx = rawName.indexOf(':');
      String nsp = (idx == -1 || idx == rawName.length()-1)
          ? ""
          : rawName.substring(0, idx);
      String nsURI = namespaces.get(nsp);

      if (currentNode == document) {
          e = document.getDocumentElement();
          String lname = rawName;
          if (idx != -1 && idx != rawName.length()-1) {
            lname = rawName.substring(idx+1);
          }
          if (e.getNamespaceURI() != null && nsp.length() != 0) {
            if (!e.getLocalName().equals(lname)) {
                throw new SAXException("Bad root element");
            }
            e.setPrefix(nsp);
          }
          String xmlns;
          Attr attr = (nsp.equals(""))
            ? e.getAttributeNodeNS(XMLSupport.XMLNS_NAMESPACE_URI,
                               xmlns = "xmlns")
            : e.getAttributeNodeNS(XMLSupport.XMLNS_NAMESPACE_URI,
                               xmlns = "xmlns:" + nsp);
          if (attr != null) {
            namespaces.put(nsp, attr.getValue());
          }
          documentElementParsed = true;
      } else {
          e = document.createElementNS(nsURI, rawName);
          currentNode.appendChild(e);
      }
      currentNode = e;

        // Storage of the line number.
        if (createDocumentDescriptor && locator != null) {
            documentDescriptor.setLocationLine(e, locator.getLineNumber());
        }

      // Attributes creation
      for (int i = 0; i < len; i++) {
          String aname = attributes.getQName(i);
          if (aname.equals("xmlns")) {
            e.setAttributeNS(XMLSupport.XMLNS_NAMESPACE_URI,
                         aname,
                         attributes.getValue(i));
          } else {
            idx = aname.indexOf(':');
            nsURI = (idx == -1)
                    ? null
                    : namespaces.get(aname.substring(0, idx));
            e.setAttributeNS(nsURI, aname, attributes.getValue(i));
            if (attributes.getType(i).equals("ID") &&
                e instanceof ElementWithID) {
                String s = (idx == -1 || idx == aname.length()-1)
                  ? aname
                  : aname.substring(idx + 1);
                ((ElementWithID)e).setIDName(nsURI, s);
            }
          }
      }
    }

    /**
     * <b>SAX</b>: Implements {@link
     * org.xml.sax.ErrorHandler#error(SAXParseException)}.
     */
    public void error(SAXParseException ex) throws SAXException {
      throw ex;
    }

    /**
     * <b>SAX</b>: Implements {@link
     * org.xml.sax.ErrorHandler#warning(SAXParseException)}.
     */
    public void warning(SAXParseException ex) throws SAXException {
      throw ex;
    }

    /**
     * <b>SAX</b>: Implements {@link
     * org.xml.sax.ContentHandler#endElement(String,String,String)}.
     */
    public void endElement(String uri, String localName, String rawName)
      throws SAXException {
      currentNode = currentNode.getParentNode();
      namespaces.pop();
    }

    /**
     * <b>SAX</b>: Implements {@link
     * org.xml.sax.ContentHandler#characters(char[],int,int)}.
     */
    public void characters(char ch[], int start, int length)
        throws SAXException {
      String data = new String(ch, start, length);
      Node n = (inCDATA)
          ? document.createCDATASection(data)
          : document.createTextNode(data);
      currentNode.appendChild(n);
    }

    /**
     * <b>SAX</b>: Implements {@link
     * org.xml.sax.ContentHandler#processingInstruction(String,String)}.
     */
    public void processingInstruction(String target, String data)
        throws SAXException {
      if (!inDTD) {
          Node n = document.createProcessingInstruction(target, data);
          if (currentNode == document && !documentElementParsed) {
            currentNode.insertBefore(n, document.getDocumentElement());
          } else {
            currentNode.appendChild(n);
          }
      }
    }

    // LexicalHandler /////////////////////////////////////////////////////////

    /**
     * <b>SAX</b>: Implements {@link
     * org.xml.sax.ext.LexicalHandler#startDTD(String,String,String)}.
     */
    public void startDTD(String name, String publicId, String systemId)
      throws SAXException {
      inDTD = true;
    }

    /**
     * <b>SAX</b>: Implements {@link org.xml.sax.ext.LexicalHandler#endDTD()}.
     */
    public void endDTD() throws SAXException {
      inDTD = false;
    }

    /**
     * <b>SAX</b>: Implements
     * {@link org.xml.sax.ext.LexicalHandler#startEntity(String)}.
     */
    public void startEntity(String name) throws SAXException {
    }

    /**
     * <b>SAX</b>: Implements
     * {@link org.xml.sax.ext.LexicalHandler#endEntity(String)}.
     */
    public void endEntity(String name) throws SAXException {
    }

    /**
     * <b>SAX</b>: Implements {@link
     * org.xml.sax.ext.LexicalHandler#startCDATA()}.
     */
    public void startCDATA() throws SAXException {
      inCDATA = true;
    }

    /**
     * <b>SAX</b>: Implements {@link
     * org.xml.sax.ext.LexicalHandler#endCDATA()}.
     */
    public void endCDATA() throws SAXException {
      inCDATA = false;
    }

    /**
     * <b>SAX</b>: Implements
     * {@link org.xml.sax.ext.LexicalHandler#comment(char[],int,int)}.
     */
    public void comment(char ch[], int start, int length) throws SAXException {
      if (!inDTD) {
          Node n = document.createComment(new String(ch, start, length));
          if (currentNode == document && !documentElementParsed) {
            currentNode.insertBefore(n, document.getDocumentElement());
          } else {
            currentNode.appendChild(n);
          }
      }
    }
}

and here's SAXSVGDocumentFactory.java (C:\Batik\xml-batik\sources\org\apache\batik\dom\svg):

/*****************************************************************************
 * Copyright (C) The Apache Software Foundation. All rights reserved.        *
 * ------------------------------------------------------------------------- *
 * This software is published under the terms of the Apache Software License *
 * version 1.1, a copy of which has been included with this distribution in  *
 * the LICENSE file.                                                         *
 *****************************************************************************/

package org.apache.batik.dom.svg;

import java.io.InputStream;
import java.io.IOException;
import java.io.Reader;

import java.net.MalformedURLException;
import java.net.URL;

import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import java.util.zip.GZIPInputStream;

import org.apache.batik.dom.util.SAXDocumentFactory;
import org.apache.batik.util.ParsedURL;
import org.apache.batik.util.MimeTypeConstants;

import org.w3c.dom.Document;
import org.w3c.dom.DOMException;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * This class contains methods for creating SVGDocument instances
 * from an URI using SAX2.
 *
 * @author <a href="mailto:stephane@hillion.org">Stephane Hillion</a>
 * @version $Id: SAXSVGDocumentFactory.java,v 1.12 2001/11/06 09:40:34 hillion Exp $
 */
public class SAXSVGDocumentFactory
    extends    SAXDocumentFactory
    implements SVGDocumentFactory {

    /**
     * The dtd public IDs resource bundle class name.
     */
    protected final static String DTDIDS =
        "org.apache.batik.dom.svg.resources.dtdids";

    /**
     * Constant for HTTP content type header charset field.
     */
    protected final static String HTTP_CHARSET = "charset";

    /**
     * The accepted DTD public IDs.
     */
    protected static String dtdids;

    /**
     * Creates a new SVGDocumentFactory object.
     * @param parser The SAX2 parser classname.
     */
    public SAXSVGDocumentFactory(String parser) {
        super(ExtensibleSVGDOMImplementation.getDOMImplementation(), parser);
    }

    /**
     * Creates a new SVGDocumentFactory object.
     * @param parser The SAX2 parser classname.
     * @param dd Whether a document descriptor must be generated.
     */
    public SAXSVGDocumentFactory(String parser, boolean dd) {
        super(ExtensibleSVGDOMImplementation.getDOMImplementation(), parser, dd);
    }

    /**
     * Creates a SVGOMDocument instance.<br>
     * This method supports gzipped sources.
     * @param uri The document URI.
     * @exception IOException if an error occured while reading the document.
     */
    public SVGOMDocument createDocument(String uri) throws IOException {
        ParsedURL purl = new ParsedURL(uri);

        InputStream is = purl.openStream(MimeTypeConstants.MIME_TYPES_SVG);

        InputSource isrc = new InputSource(is);

        // now looking for a charset encoding in the content type such
        // as "image/svg+xml; charset=iso8859-1" this is not official
        // for image/svg+xml yet! only for text/xml and maybe
        // for application/xml
        String contentType = purl.getContentType();
        int cindex = -1;
        if (contentType != null) {
            contentType = contentType.toLowerCase();
            cindex = contentType.indexOf(HTTP_CHARSET);
        }

        if (cindex != -1) {
            int i                 = cindex + HTTP_CHARSET.length();
            int eqIdx = contentType.indexOf('=', i);
            if (eqIdx != -1) {
                eqIdx++; // no one is interested in the equals sign...

                String charset;
                // The patch had ',' as the terminator but I suspect
                // that is the delimiter between possible charsets,
                // but if another 'attribute' were in the accept header
                // charset would be terminated by a ';'.  So I look
                // for both and take to closer of the two.
                int idx     = contentType.indexOf(',', eqIdx);
                int semiIdx = contentType.indexOf(';', eqIdx);
                if ((semiIdx != -1) && ((semiIdx < idx) || (idx == -1)))
                    idx = semiIdx;
                if (idx != -1)
                    charset = contentType.substring(eqIdx, idx);
                else
                    charset = contentType.substring(eqIdx);
                isrc.setEncoding(charset.trim());
            }
        }

        isrc.setSystemId(uri);

        SVGOMDocument doc = (SVGOMDocument)super.createDocument
            (SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", uri, isrc);
        try {
            doc.setURLObject(new URL(purl.toString()));
        } catch (MalformedURLException mue) {
            // Not very likely to happen given we already opened the stream.
            throw new IOException("Malformed URL: " + uri);
        }

        return doc;
    }

    /**
     * Creates a SVGOMDocument instance.
     * @param uri The document URI.
     * @param is The document input stream.
     * @exception IOException if an error occured while reading the document.
     */
    public SVGOMDocument createDocument(String uri, InputStream inp) throws IOException {
        SVGOMDocument doc;
        InputSource is = new InputSource(inp);
        is.setSystemId(uri);

        try {
            doc = (SVGOMDocument)super.createDocument
                (SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", uri, is);
            if (uri != null) {
                doc.setURLObject(new URL(uri));
            }
        } catch (MalformedURLException e) {
            throw new IOException(e.getMessage());
        }
        return doc;
    }

    /**
     * Creates a SVGOMDocument instance.
     * @param uri The document URI.
     * @param r The document reader.
     * @exception IOException if an error occured while reading the document.
     */
    public SVGOMDocument createDocument(String uri, Reader r) throws IOException {
        SVGOMDocument doc;
        InputSource is = new InputSource(r);
        is.setSystemId(uri);

        try {
            doc = (SVGOMDocument)super.createDocument
                (SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", uri, is);
            if (uri != null) {
                doc.setURLObject(new URL(uri));
            }
        } catch (MalformedURLException e) {
            throw new IOException(e.getMessage());
        }
        return doc;
    }

    /**
     * Creates a Document instance.
     * @param ns The namespace URI of the root element of the document.
     * @param root The name of the root element of the document.
     * @param uri The document URI.
     * @exception IOException if an error occured while reading the document.
     */
    public Document createDocument(String ns, String root, String uri)
        throws IOException {
        if (!SVGDOMImplementation.SVG_NAMESPACE_URI.equals(ns) ||
            !"svg".equals(root)) {
            throw new RuntimeException("Bad root element");
        }
        return createDocument(uri);
    }

    /**
     * Creates a Document instance.
     * @param ns The namespace URI of the root element of the document.
     * @param root The name of the root element of the document.
     * @param uri The document URI.
     * @param is The document input stream.
     * @exception IOException if an error occured while reading the document.
     */
    public Document createDocument(String ns, String root, String uri, InputStream is)
        throws IOException {
        if (!SVGDOMImplementation.SVG_NAMESPACE_URI.equals(ns) ||
            !"svg".equals(root)) {
            throw new RuntimeException("Bad root element");
        }
        return createDocument(uri, is);
    }

    /**
     * Creates a Document instance.
     * @param ns The namespace URI of the root element of the document.
     * @param root The name of the root element of the document.
     * @param uri The document URI.
     * @param r The document reader.
     * @exception IOException if an error occured while reading the document.
     */
    public Document createDocument(String ns, String root, String uri, Reader r)
        throws IOException {
        if (!SVGDOMImplementation.SVG_NAMESPACE_URI.equals(ns) ||
            !"svg".equals(root)) {
            throw new RuntimeException("Bad root element");
        }
        return createDocument(uri, r);
    }

    /**
     * <b>SAX2</b>: Implements {@link
     * org.xml.sax.EntityResolver#resolveEntity(String,String)}.
     */
    public InputSource resolveEntity(String publicId, String systemId)
        throws SAXException {
        try {
            if (dtdids == null) {
                ResourceBundle rb;
                rb = ResourceBundle.getBundle(DTDIDS,
                                              Locale.getDefault());
                dtdids = rb.getString("publicIds");
            }
            if (dtdids.indexOf(publicId) != -1) {
                return new InputSource
                    (getClass().getResource
                     ("resources/svg10.dtd").toString());
            }
        } catch (MissingResourceException e) {
            throw new SAXException(e);
        }
        // Let the SAX parser find the entity.
        return null;
    }
}

Sorry about the long message!

Karl


This email and any files transmitted with it are confidential and intended solely for the
use of individuals or entity to whom they are addressed.

If you have received this email in error, please notify The Salvation Army International Headquarters
Helpdesk on +44 (0) 20 7398 5466 or the originator of the message.

Any views expressed in this message are those of the individual sender, except where the sender
specifies and with the authority, states them to be the views of The Salvation Army International
Trustee Company.

[v3.5.1]

---------------------------------------------------------------------
To unsubscribe, e-mail: batik-users-unsubscribe@xml.apache.org
For additional commands, e-mail: batik-users-help@xml.apache.org


Mime
View raw message