ContentHandlerToXMLStreamWriter.java in  » XML » stax-utils » javanet » staxutils » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Home
Java Source Code / Java Documentation
1.6.0 JDK Core
2.6.0 JDK Modules
3.6.0 JDK Modules com.sun
4.6.0 JDK Modules com.sun.java
5.6.0 JDK Modules sun
6.6.0 JDK Platform
7.Ajax
8.Apache Harmony Java SE
9.Aspect oriented
10.Authentication Authorization
11.Blogger System
12.Build
13.Byte Code
14.Cache
15.Chart
16.Chat
17.Code Analyzer
18.Collaboration
19.Content Management System
20.Database Client
21.Database DBMS
22.Database JDBC Connection Pool
23.Database ORM
24.Development
25.EJB Server
26.ERP CRM Financial
27.ESB
28.Forum
29.Game
30.GIS
31.Graphic 3D
32.Graphic Library
33.Groupware
34.HTML Parser
35.IDE
36.IDE Eclipse
37.IDE Netbeans
38.Installer
39.Internationalization Localization
40.Inversion of Control
41.Issue Tracking
42.J2EE
43.J2ME
44.JBoss
45.JMS
46.JMX
47.Library
48.Mail Clients
49.Music
50.Net
51.Parser
52.PDF
53.Portal
54.Profiler
55.Project Management
56.Report
57.RSS RDF
58.Rule Engine
59.Science
60.Scripting
61.Search Engine
62.Security
63.Sevlet Container
64.Source Control
65.Swing Library
66.Template Engine
67.Test Coverage
68.Testing
69.UML
70.Web Crawler
71.Web Framework
72.Web Mail
73.Web Server
74.Web Services
75.Web Services apache cxf 2.2.6
76.Web Services AXIS2
77.Wiki Engine
78.Workflow Engines
79.XML
80.XML UI
Java Source Code / Java Documentation » XML » stax utils » javanet.staxutils 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


        /* $Id: ContentHandlerToXMLStreamWriter.java,v 1.6 2005/10/25 18:36:24 ryan_shoemaker Exp $
         *
         * Copyright (c) 2004, Sun Microsystems, Inc.
         * All rights reserved.
         *
         * Redistribution and use in source and binary forms, with or without
         * modification, are permitted provided that the following conditions are
         * met:
         *
         *     * Redistributions of source code must retain the above copyright
         *      notice, this list of conditions and the following disclaimer.
         *
         *     * Redistributions in binary form must reproduce the above
         *      copyright notice, this list of conditions and the following
         *       disclaimer in the documentation and/or other materials provided
         *       with the distribution.
         *
         *     * Neither the name of Sun Microsystems, Inc. nor the names of its
         *       contributors may be used to endorse or promote products derived
         *       from this software without specific prior written permission.
         *
         * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
         * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
         * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
         * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
         * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
         * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
         * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
         * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
         * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
         * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
         * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
         */
        package javanet.staxutils;

        import org.xml.sax.Attributes;
        import org.xml.sax.Locator;
        import org.xml.sax.SAXException;
        import org.xml.sax.helpers.DefaultHandler;

        import javax.xml.stream.XMLStreamException;
        import javax.xml.stream.XMLStreamWriter;
        import java.util.Stack;

        /**
         * This is a simple utility class that adapts SAX events into StAX
         * {@link javax.xml.stream.XMLStreamWriter} events, bridging between
         * the two parser technologies.
         *
         * This ContentHandler does not own the XMLStreamWriter.  Therefore, it will
         * not close or flush the writer at any point.
         * 
         * @author [email protected]
         * @version 1.0
         */
        public class ContentHandlerToXMLStreamWriter extends DefaultHandler {

            // SAX events will be sent to this XMLStreamWriter
            private final XMLStreamWriter staxWriter;

            // storage for prefix bindings
            private final Stack prefixBindings;

            public ContentHandlerToXMLStreamWriter(XMLStreamWriter staxCore) {
                this .staxWriter = staxCore;
                prefixBindings = new Stack(); // default of 10 seems reasonable
            }

            /*
             * (non-Javadoc)
             * 
             * @see org.xml.sax.ContentHandler#endDocument()
             */
            public void endDocument() throws SAXException {
                try {
                    staxWriter.writeEndDocument();
                    staxWriter.flush();
                } catch (XMLStreamException e) {
                    throw new SAXException(e);
                }
            }

            /*
             * (non-Javadoc)
             * 
             * @see org.xml.sax.ContentHandler#startDocument()
             */
            public void startDocument() throws SAXException {
                try {
                    staxWriter.writeStartDocument();
                } catch (XMLStreamException e) {
                    throw new SAXException(e);
                }
            }

            /*
             * (non-Javadoc)
             * 
             * @see org.xml.sax.ContentHandler#characters(char[], int, int)
             */
            public void characters(char[] ch, int start, int length)
                    throws SAXException {

                try {
                    staxWriter.writeCharacters(ch, start, length);
                } catch (XMLStreamException e) {
                    throw new SAXException(e);
                }

            }

            /*
             * (non-Javadoc)
             * 
             * @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int)
             */
            public void ignorableWhitespace(char[] ch, int start, int length)
                    throws SAXException {

                characters(ch, start, length);
            }

            /*
             * (non-Javadoc)
             * 
             * @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String)
             */
            public void endPrefixMapping(String prefix) throws SAXException {
                // TODO: no-op?

                // I think we can ignore these SAX events because StAX
                // automatically scopes the prefix bindings.
            }

            /*
             * (non-Javadoc)
             * 
             * @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String)
             */
            public void skippedEntity(String name) throws SAXException {
                try {
                    staxWriter.writeEntityRef(name);
                } catch (XMLStreamException e) {
                    throw new SAXException(e);
                }
            }

            /*
             * (non-Javadoc)
             * 
             * @see org.xml.sax.ContentHandler#setDocumentLocator(org.xml.sax.Locator)
             */
            public void setDocumentLocator(Locator locator) {
                // TODO: no-op?
                // there doesn't seem to be any way to pass location info
                // along to the XMLStreamWriter. On the XMLEventWriter side, you
                // can set the location info on the event objects.
            }

            /*
             * (non-Javadoc)
             * 
             * @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String,
             *      java.lang.String)
             */
            public void processingInstruction(String target, String data)
                    throws SAXException {

                try {
                    staxWriter.writeProcessingInstruction(target, data);
                } catch (XMLStreamException e) {
                    throw new SAXException(e);
                }

            }

            /*
             * (non-Javadoc)
             * 
             * @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String,
             *      java.lang.String)
             */
            public void startPrefixMapping(String prefix, String uri)
                    throws SAXException {

                if (prefix.equals("xml")) {
                    return;
                }

                // defend against parsers that pass null in for "xmlns" prefix
                if (prefix == null) {
                    prefix = "";
                }

                prefixBindings.add(prefix);
                prefixBindings.add(uri);
            }

            /*
             * (non-Javadoc)
             * 
             * @see org.xml.sax.ContentHandler#endElement(java.lang.String,
             *      java.lang.String, java.lang.String)
             */
            public void endElement(String namespaceURI, String localName,
                    String qName) throws SAXException {

                try {
                    // TODO: is this all we have to do?
                    staxWriter.writeEndElement();
                } catch (XMLStreamException e) {
                    throw new SAXException(e);
                }
            }

            /*
             * (non-Javadoc)
             * 
             * @see org.xml.sax.ContentHandler#startElement(java.lang.String,
             *      java.lang.String, java.lang.String, org.xml.sax.Attributes)
             */
            public void startElement(String namespaceURI, String localName,
                    String qName, Attributes atts) throws SAXException {

                try {
                    staxWriter.writeStartElement(getPrefix(qName), localName,
                            namespaceURI);

                    String uri, prefix;
                    while (prefixBindings.size() != 0) {
                        uri = (String) prefixBindings.pop();
                        prefix = (String) prefixBindings.pop();
                        if (prefix.length() == 0) {
                            staxWriter.setDefaultNamespace(uri);
                        } else {
                            staxWriter.setPrefix(prefix, uri);
                        }

                        // this method handles "", null, and "xmlns" prefixes properly
                        staxWriter.writeNamespace(prefix, uri);
                    }

                    writeAttributes(atts);
                } catch (XMLStreamException e) {
                    throw new SAXException(e);
                }

            }

            /**
             * Generate a StAX writeAttribute event for each attribute
             * 
             * @param atts
             *                attributes from the SAX event
             */
            private void writeAttributes(Attributes atts)
                    throws XMLStreamException {
                for (int i = 0; i < atts.getLength(); i++) {
                    final String prefix = getPrefix(atts.getQName(i));
                    if (!prefix.equals("xmlns")) { // defend againts broken transformers that report xmlns decls as attrs
                        staxWriter.writeAttribute(prefix, atts.getURI(i), atts
                                .getLocalName(i), atts.getValue(i));
                    }
                }
            }

            /**
             * Pull the prefix off of the specified QName.
             * 
             * @param qName
             *                the QName
             * @return the prefix or the empty string if it doesn't exist.
             */
            private String getPrefix(String qName) {
                int idx = qName.indexOf(':');
                if (idx == -1) {
                    return "";
                } else {
                    return qName.substring(0, idx);
                }
            }

        }
ww_w___.j__a__v___a_2_s___._c_o___m__ | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.