LICENSE0000644000175000017500000000314210423740506010630 0ustar tonytonyCopyright (c) 2004, Christian Niles, unit12.net Copyright (c) 2004, Sun Microsystems, Inc. Copyright (c) 2006, John Kristian 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 the listed copyright holders 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. build.xml0000644000175000017500000001435211535776260011464 0ustar tonytony src/0000755000175000017500000000000011542302320010401 5ustar tonytonysrc/javanet/0000755000175000017500000000000011542302310012030 5ustar tonytonysrc/javanet/staxutils/0000755000175000017500000000000011542302312014072 5ustar tonytonysrc/javanet/staxutils/EmptyNamespaceContext.java0000644000175000017500000000555310073255126021235 0ustar tonytony/* * $Id: EmptyNamespaceContext.java,v 1.2 2004-07-08 14:29:42 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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 java.util.Collections; import java.util.Iterator; import javax.xml.namespace.NamespaceContext; /** * {@link ExtendedNamespaceContext} that contains no namespaces. * * @author Christian Niles * @version $Revision: 1.2 $ */ public final class EmptyNamespaceContext implements ExtendedNamespaceContext, StaticNamespaceContext { public static final EmptyNamespaceContext INSTANCE = new EmptyNamespaceContext(); public static final NamespaceContext getInstance() { return INSTANCE; } public String getNamespaceURI(String prefix) { return null; } public String getPrefix(String nsURI) { return null; } public Iterator getPrefixes(String nsURI) { return Collections.EMPTY_SET.iterator(); } public NamespaceContext getParent() { return null; } public boolean isPrefixDeclared(String prefix) { return false; } public Iterator getPrefixes() { return Collections.EMPTY_LIST.iterator(); } public Iterator getDeclaredPrefixes() { return Collections.EMPTY_LIST.iterator(); } }src/javanet/staxutils/StaxUtilsXMLOutputFactory.java0000644000175000017500000001214210424446060022036 0ustar tonytony/* Copyright (c) 2006, John Kristian * 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 StAX-Utils 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 javanet.staxutils.helpers.FilterXMLOutputFactory; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; /** * An output factory that optionally wraps a filter around each writer. The * property {@link #INDENTING} controls indentation of output. */ public class StaxUtilsXMLOutputFactory extends FilterXMLOutputFactory { /** * A Boolean property controlling whether to indent output. If true, output * is indented by {@link IndentingXMLEventWriter} or * {@link IndentingXMLStreamWriter}. The default is false. */ public static final String INDENTING = "net.java.staxutils.indenting"; /** * A String property whose value indents one level. The default is * {@link Indentation#DEFAULT_INDENT}. */ public static final String INDENT = "net.java.staxutils.indent"; /** * A String property whose value introduces a new line for indentation. The * default is {@link Indentation#NORMAL_END_OF_LINE}. */ public static final String NEW_LINE = "net.java.staxutils.newLine"; public StaxUtilsXMLOutputFactory() { } public StaxUtilsXMLOutputFactory(XMLOutputFactory source) { super(source); } private boolean indenting = false; private String indent = Indentation.DEFAULT_INDENT; private String newLine = Indentation.NORMAL_END_OF_LINE; protected XMLEventWriter filter(XMLEventWriter writer) { if (indenting) { IndentingXMLEventWriter indenter = new IndentingXMLEventWriter(writer); indenter.setNewLine(newLine); indenter.setIndent(indent); writer = indenter; } return writer; } protected XMLStreamWriter filter(XMLStreamWriter writer) { if (indenting) { IndentingXMLStreamWriter indenter = new IndentingXMLStreamWriter(writer); indenter.setNewLine(newLine); indenter.setIndent(indent); writer = indenter; } return writer; } public boolean isPropertySupported(String name) { return INDENTING.equals(name) || INDENT.equals(name) || NEW_LINE.equals(name) // || super.isPropertySupported(name); } public void setProperty(String name, Object value) throws IllegalArgumentException { if (INDENTING.equals(name)) { indenting = ((Boolean) value).booleanValue(); } else if (INDENT.equals(name)) { indent = (String) value; } else if (NEW_LINE.equals(name)) { newLine = (String) value; } else { super.setProperty(name, value); } } public Object getProperty(String name) throws IllegalArgumentException { if (INDENTING.equals(name)) { return indenting ? Boolean.TRUE : Boolean.FALSE; } else if (INDENT.equals(name)) { return indent; } else if (NEW_LINE.equals(name)) { return newLine; } else { return super.getProperty(name); } } public int hashCode() { return super.hashCode() + (indenting ? 1 : 0) + hashCode(indent) + hashCode(newLine); } public boolean equals(Object o) { if (!(o instanceof StaxUtilsXMLOutputFactory)) return false; StaxUtilsXMLOutputFactory that = (StaxUtilsXMLOutputFactory) o; return super.equals(that) && (indenting == that.indenting) && equals(indent, that.indent) && equals(newLine, that.newLine); } } src/javanet/staxutils/ExtendedLocation.java0000644000175000017500000000442410072360022020171 0ustar tonytony/* * $Id: ExtendedLocation.java,v 1.1 2004-07-05 23:11:13 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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 javax.xml.stream.Location; /** * Extended the {@link Location} interface that exposes nested {@link Location}s. * * @author Christian Niles * @version $Revision: 1.1 $ */ public interface ExtendedLocation extends Location { /** * Returns a nested {@link Location}. Nested locations can be used to locate * errors in linked files. This is useful when working with external entities, * included files, and so forth. * * @return The nested {@link Location}, or null. */ public Location getNestedLocation(); }src/javanet/staxutils/ExtendedNamespaceContext.java0000644000175000017500000000606610072357766021713 0ustar tonytony/* * $Id: ExtendedNamespaceContext.java,v 1.1 2004-07-05 23:10:46 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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 java.util.Iterator; import javax.xml.namespace.NamespaceContext; /** * Extended namespace context interface that allows the context tree to be navigated * and to list all known prefixes. * * @author Christian Niles * @version $Revision: 1.1 $ */ public interface ExtendedNamespaceContext extends NamespaceContext { /** * Returns a reference to the parent of this context. * * @return The parent context, or null if this is a root * context. */ public NamespaceContext getParent(); /** * Determines if the specified prefix is declared within this context, * irrespective of any ancestor contexts. * * @param prefix The prefix to check. * @return true if the prefix is declared in this context, * false otherwise. */ public boolean isPrefixDeclared(String prefix); /** * Returns an {@link Iterator} of all namespace prefixes in scope within this * context, including those inherited from ancestor contexts. * * @return An {@link Iterator} of prefix {@link String}s. */ public Iterator getPrefixes(); /** * Returns an {@link Iterator} of all namespace prefixes declared within * this context, irrespective of any ancestor contexts. * * @return An {@link Iterator} of prefix {@link String}s. */ public Iterator getDeclaredPrefixes(); }src/javanet/staxutils/XMLEventConsumerDelegate.java0000644000175000017500000005454310111147032021556 0ustar tonytony/* * $Id: XMLEventConsumerDelegate.java,v 1.4 2004-08-19 15:58:17 cniles Exp $ * * Copyright (c) 2004, Christian Niles, Unit12 * 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 Christian Niles, Unit12, 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 java.util.Iterator; import javax.xml.namespace.NamespaceContext; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.*; import javax.xml.stream.util.XMLEventConsumer; /** * Writes all events to a wrapped {@link XMLEventConsumer}, and provides * convenience methods for creating events written to the internal consumer. * * @author Christian Niles * @version $Revision: 1.4 $ */ public class XMLEventConsumerDelegate implements XMLEventConsumer { /** * The consumer instance to which events are written. */ private XMLEventConsumer consumer; /** * The factory used to create events. */ private XMLEventFactory factory; public XMLEventConsumerDelegate(XMLEventConsumer consumer) { this.consumer = consumer; this.factory = XMLEventFactory.newInstance(); } public XMLEventConsumerDelegate(XMLEventConsumer consumer, XMLEventFactory factory) { this.consumer = consumer; this.factory = (factory == null ? XMLEventFactory.newInstance() : factory); } /** * Returns a reference to the underlying {@link XMLEventConsumer} to which * events are added. * * @return The underlying {@link XMLEventConsumer} to which events are * added. */ public XMLEventConsumer getConsumer() { return consumer; } /** * Sets the underlying {@link XMLEventConsumer} to which events are added. * * @param consumer The new {@link XMLEventConsumer}. */ public void setConsumer(XMLEventConsumer consumer) { this.consumer = consumer; } /** * Returns a reference to the {@link XMLEventFactory} used to construct * events. * * @return The {@link XMLEventFactory} used to construct events. */ public XMLEventFactory getEventFactory() { return factory; } /** * Sets the {@link XMLEventFactory} used to construct events. * * @param factory The new {@link XMLEventFactory}. */ public void setEventFactory(XMLEventFactory factory) { this.factory = factory; } public void add(XMLEvent event) throws XMLStreamException { consumer.add(event); } /** * Creates and adds a {@link DTD} event. * * @param dtd The DTD content, as per * {@link XMLEventFactory#createDTD(String)}. * @throws XMLStreamException If an error occurs adding the event. */ public void addDTD(String dtd) throws XMLStreamException { add(factory.createDTD(dtd)); } /** * Creates and adds a CDATA {@link Characters} event. * * @param content The CDATA content, as per * {@link XMLEventFactory#createCData(String)}. * @throws XMLStreamException If an error occurs adding the event. */ public void addCData(String content) throws XMLStreamException { add(factory.createCData(content)); } /** * Creates and adds a {@link Characters} event. * * @param content The text content, as per * {@link XMLEventFactory#createCharacters(String)}. * @throws XMLStreamException If an error occurs adding the event. */ public void addText(String content) throws XMLStreamException { add(factory.createCharacters(content)); } /** * Creates and adds an ignorable space {@link Characters} event. * * @param content The ignorable whitespace, as per * {@link XMLEventFactory#createIgnorableSpace(String)}. * @throws XMLStreamException If an error occurs adding the event. */ public void addIgnorableSpace(String content) throws XMLStreamException { add(factory.createIgnorableSpace(content)); } /** * Creates and adds a whitespace {@link Characters} event. * * @param content The whitespace, as per * {@link XMLEventFactory#createIgnorableSpace(String)}. * @throws XMLStreamException If an error occurs adding the event. */ public void addSpace(String content) throws XMLStreamException { add(factory.createSpace(content)); } /** * Creates and adds a {@link Comment} event. * * @param comment The comment text, as per * {@link XMLEventFactory#createComment(String)}. * @throws XMLStreamException If an error occurs adding the event. */ public void addComment(String comment) throws XMLStreamException { add(factory.createComment(comment)); } /** * Creates and adds a {@link StartDocument} event. * * @see XMLEventFactory#createStartDocument() * @throws XMLStreamException If an error occurs adding the event. */ public void addStartDocument() throws XMLStreamException { add(factory.createStartDocument()); } /** * Creates and adds a {@link StartDocument} event. * * @param encoding The encoding to specify in the xml declaration. * @see XMLEventFactory#createStartDocument(String) * @throws XMLStreamException If an error occurs adding the event. */ public void addStartDocument(String encoding) throws XMLStreamException { add(factory.createStartDocument(encoding)); } /** * Creates and adds a {@link StartDocument} event. * * @param encoding The encoding to include in the xml declaration. * @param version The XML version to include in the xml declaration. * @see XMLEventFactory#createStartDocument(String, String) * @throws XMLStreamException If an error occurs adding the event. */ public void addStartDocument(String encoding, String version) throws XMLStreamException { add(factory.createStartDocument(encoding, version)); } /** * Creates and adds a {@link StartDocument} event. * * @param encoding The encoding to include in the xml declaration. * @param version The XML version to include in the xml declaration. * @param standalone The standalone value to include in the xml declaration. * @see XMLEventFactory#createStartDocument(String, String, boolean) * @throws XMLStreamException If an error occurs adding the event. */ public void addStartDocument(String encoding, String version, boolean standalone) throws XMLStreamException { add(factory.createStartDocument(encoding, version, standalone)); } /** * Creates and adds an {@link EndDocument} event. * * @see XMLEventFactory#createEndDocument() * @throws XMLStreamException If an error occurs adding the event. */ public void addEndDocument() throws XMLStreamException { add(factory.createEndDocument()); } /** * Creates and adds a {@link StartElement} event. * * @param localName The local name of the element. * @param context The element's {@link NamespaceContext}, or null. * @throws XMLStreamException If an error occurs adding the event. */ public void addStartElement(String localName, NamespaceContext context) throws XMLStreamException { addStartElement(localName, null, null, context); } /** * Creates and adds a {@link StartElement} event. * * @param localName The local name of the element. * @param attributes An {@link Iterator} over the element's attributes. * @param namespaces An {@link Iterator} over the element's namespaces. * @param context The element's {@link NamespaceContext}, or null. * @throws XMLStreamException If an error occurs adding the event. */ public void addStartElement(String localName, Iterator attributes, Iterator namespaces, NamespaceContext context) throws XMLStreamException { add(factory.createStartElement("", "", localName, attributes, namespaces, context)); } /** * Creates and adds a {@link StartElement} event. * * @param ns The element's namespace URI. * @param localName The local name of the element. * @param context The element's {@link NamespaceContext}, or null. * @throws XMLStreamException If an error occurs adding the event. */ public void addStartElement(String ns, String localName, NamespaceContext context) throws XMLStreamException { addStartElement(ns, localName, null, null, context); } /** * Creates and adds a {@link StartElement} event. * * @param ns The element's namespace URI. * @param localName The local name of the element. * @param attributes An {@link Iterator} over the element's attributes. * @param namespaces An {@link Iterator} over the element's namespaces. * @param context The element's {@link NamespaceContext}, or null. * @throws XMLStreamException If an error occurs adding the event. */ public void addStartElement(String ns, String localName, Iterator attributes, Iterator namespaces, NamespaceContext context) throws XMLStreamException { add(factory.createStartElement("", ns, localName, attributes, namespaces, context)); } /** * Creates and adds a {@link StartElement} event. * * @param name The qualified element name. * @param context The element's {@link NamespaceContext}, or null. * @throws XMLStreamException If an error occurs adding the event. */ public void addStartElement(QName name, NamespaceContext context) throws XMLStreamException { addStartElement(name, null, null, context); } /** * Creates and adds a {@link StartElement} event. * * @param name The qualified element name. * @param attributes An {@link Iterator} over the element's attributes. * @param namespaces An {@link Iterator} over the element's namespaces. * @param context The element's {@link NamespaceContext}, or null. * @throws XMLStreamException If an error occurs adding the event. */ public void addStartElement(QName name, Iterator attributes, Iterator namespaces, NamespaceContext context) throws XMLStreamException { add(factory.createStartElement(name.getPrefix(), name.getNamespaceURI(), name.getLocalPart(), attributes, namespaces, context)); } /** * Creates and adds an {@link EndElement} event. * * @param localName The unqualified element name. * @throws XMLStreamException If an error occurs adding the event. */ public void addEndElement(String localName) throws XMLStreamException { addEndElement(localName, (Iterator) null); } /** * Creates and adds an {@link EndElement} event. * * @param localName The unqualified element name. * @param namespaces An {@link Iterator} over the element's namespaces that * are going out of scope. * @throws XMLStreamException If an error occurs adding the event. */ public void addEndElement(String localName, Iterator namespaces) throws XMLStreamException { add(factory.createEndElement(null, null, localName, namespaces)); } /** * Creates and adds an {@link EndElement} event. * * @param ns The element namespace. * @param localName The element name. * @throws XMLStreamException If an error occurs adding the event. */ public void addEndElement(String ns, String localName) throws XMLStreamException { addEndElement(ns, localName, (Iterator) null); } /** * Creates and adds an {@link EndElement} event. * * @param ns The element namespace. * @param localName The element name. * @param namespaces An {@link Iterator} over the element's namespaces that * are going out of scope. * @throws XMLStreamException If an error occurs adding the event. */ public void addEndElement(String ns, String localName, Iterator namespaces) throws XMLStreamException { add(factory.createEndElement(null, ns, localName, namespaces)); } /** * Creates and adds an {@link EndElement} event. * * @param name The element name. * @see XMLEventFactory#createEndElement(QName, Iterator) * @throws XMLStreamException If an error occurs adding the event. */ public void addEndElement(QName name) throws XMLStreamException { addEndElement(name, (Iterator) null); } /** * Creates and adds an {@link EndElement} event. * * @param name The element name. * @param namespaces An {@link Iterator} over the element's namespaces that * are going out of scope. * @see XMLEventFactory#createEndElement(QName, Iterator) * @throws XMLStreamException If an error occurs adding the event. */ public void addEndElement(QName name, Iterator namespaces) throws XMLStreamException { add(factory.createEndElement(name, namespaces)); } /** * Adds a simple text element with no attributes or namespace declarations. * * @param name The unqualified element name. * @param text The text content, which may be null * @param context The element's {@link NamespaceContext}, or null. * @throws XMLStreamException If an error occurs adding an event. */ public void addTextElement(String name, String text, NamespaceContext context) throws XMLStreamException { addStartElement(name, context); if (text != null) { addText(text); } addEndElement(name); } /** * Adds a simple text element with no attributes or namespace declarations. * * @param name The element name. * @param text The text content, which may be null * @param context The element's {@link NamespaceContext}, or null. * @throws XMLStreamException If an error occurs adding an event. */ public void addTextElement(QName name, String text, NamespaceContext context) throws XMLStreamException { addStartElement(name, context); if (text != null) { addText(text); } addEndElement(name); } /** * Adds a boolean text element with no attributes or namespace declarations. * * @param name The unqualified element name. * @param text The boolean content. * @param context The element's {@link NamespaceContext}, or null. * @throws XMLStreamException If an error occurs adding an event. */ public void addTextElement(String name, boolean text, NamespaceContext context) throws XMLStreamException { addTextElement(name, Boolean.toString(text), context); } /** * Adds a boolean text element with no attributes or namespace declarations. * * @param name The element name. * @param text The boolean content. * @param context The element's {@link NamespaceContext}, or null. * @throws XMLStreamException If an error occurs adding an event. */ public void addTextElement(QName name, boolean text, NamespaceContext context) throws XMLStreamException { addTextElement(name, Boolean.toString(text), context); } /** * Adds a text element with no attributes or namespace declarations. * * @param name The unqualified element name. * @param text The element content. * @param context The element's {@link NamespaceContext}, or null. * @throws XMLStreamException If an error occurs adding an event. */ public void addTextElement(String name, int text, NamespaceContext context) throws XMLStreamException { addTextElement(name, Integer.toString(text), context); } /** * Adds a text element with no attributes or namespace declarations. * * @param name The element name. * @param text The element content. * @param context The element's {@link NamespaceContext}, or null. * @throws XMLStreamException If an error occurs adding an event. */ public void addTextElement(QName name, int text, NamespaceContext context) throws XMLStreamException { addTextElement(name, Integer.toString(text), context); } /** * Adds a text element with no attributes or namespace declarations. * * @param name The unqualified element name. * @param text The element content. * @param context The element's {@link NamespaceContext}, or null. * @throws XMLStreamException If an error occurs adding an event. */ public void addTextElement(String name, long text, NamespaceContext context) throws XMLStreamException { addTextElement(name, Long.toString(text), context); } /** * Adds a text element with no attributes or namespace declarations. * * @param name The element name. * @param text The element content. * @param context The element's {@link NamespaceContext}, or null. * @throws XMLStreamException If an error occurs adding an event. */ public void addTextElement(QName name, long text, NamespaceContext context) throws XMLStreamException { addTextElement(name, Long.toString(text), context); } /** * Adds a text element with no attributes or namespace declarations. * * @param name The unqualified element name. * @param text The element content. * @param context The element's {@link NamespaceContext}, or null. * @throws XMLStreamException If an error occurs adding an event. */ public void addTextElement(String name, float text, NamespaceContext context) throws XMLStreamException { addTextElement(name, Float.toString(text), context); } /** * Adds a text element with no attributes or namespace declarations. * * @param name The element name. * @param text The element content. * @param context The element's {@link NamespaceContext}, or null. * @throws XMLStreamException If an error occurs adding an event. */ public void addTextElement(QName name, float text, NamespaceContext context) throws XMLStreamException { addTextElement(name, Float.toString(text), context); } /** * Adds a text element with no attributes or namespace declarations. * * @param name The unqualified element name. * @param text The element content. * @param context The element's {@link NamespaceContext}, or null. * @throws XMLStreamException If an error occurs adding an event. */ public void addTextElement(String name, double text, NamespaceContext context) throws XMLStreamException { addTextElement(name, Double.toString(text), context); } /** * Adds a text element with no attributes or namespace declarations. * * @param name The element name. * @param text The element content. * @param context The element's {@link NamespaceContext}, or null. * @throws XMLStreamException If an error occurs adding an event. */ public void addTextElement(QName name, double text, NamespaceContext context) throws XMLStreamException { addTextElement(name, Double.toString(text), context); } /** * Adds a text element with no attributes or namespace declarations. * * @param name The unqualified element name. * @param text The element content. * @param context The element's {@link NamespaceContext}, or null. * @throws XMLStreamException If an error occurs adding an event. */ public void addTextElement(String name, Number text, NamespaceContext context) throws XMLStreamException { if (text != null) { addTextElement(name, text.toString(), context); } else { addTextElement(name, (String) null, context); } } /** * Adds a text element with no attributes or namespace declarations. * * @param name The element name. * @param text The element content. * @param context The element's {@link NamespaceContext}, or null. * @throws XMLStreamException If an error occurs adding an event. */ public void addTextElement(QName name, Number text, NamespaceContext context) throws XMLStreamException { if (text != null) { addTextElement(name, text.toString(), context); } else { addTextElement(name, (String) null, context); } } }src/javanet/staxutils/XMLStreamEventReader.java0000644000175000017500000001316410074530136020711 0ustar tonytony/* * $Id: XMLStreamEventReader.java,v 1.3 2004-07-12 15:38:06 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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 javanet.staxutils.events.EventAllocator; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.util.XMLEventAllocator; /** * {@link XMLEventReader} implementation based on a {@link XMLStreamReader} and * an {@link XMLEventAllocator}. * * @author Christian Niles * @version $Revision: 1.3 $ */ public class XMLStreamEventReader implements XMLEventReader { /** The underlying stream reader. */ private XMLStreamReader reader; /** The event allocator used to create events. */ private XMLEventAllocator allocator; /** Field used to cache peek()ed events. */ private XMLEvent nextEvent; /** Whether the reader is closed or not. */ private boolean closed; public XMLStreamEventReader(XMLStreamReader reader) { this.reader = reader; this.allocator = new EventAllocator(); } public XMLStreamEventReader(XMLStreamReader reader, XMLEventAllocator allocator) { this.reader = reader; this.allocator = (allocator == null ? new EventAllocator() : allocator); } /** * No properties are supported, so this always throws * {@link IllegalArgumentException}. */ public Object getProperty(String name) throws IllegalArgumentException { throw new IllegalArgumentException("Unknown property: " + name); } public synchronized boolean hasNext() { if (closed) { return false; } try { return reader.hasNext(); } catch (XMLStreamException e) { // TODO how to handle inconsistency? return false; } } public synchronized XMLEvent nextTag() throws XMLStreamException { if (closed) { throw new XMLStreamException("Stream has been closed"); } nextEvent = null; reader.nextTag(); return nextEvent(); } public synchronized String getElementText() throws XMLStreamException { if (closed) { throw new XMLStreamException("Stream has been closed"); } // null the peeked event this.nextEvent = null; return reader.getElementText(); } public synchronized XMLEvent nextEvent() throws XMLStreamException { if (closed) { throw new XMLStreamException("Stream has been closed"); } XMLEvent event; if (nextEvent != null) { event = nextEvent; nextEvent = null; } else { event = allocateEvent(); reader.next(); } return event; } public synchronized XMLEvent peek() throws XMLStreamException { if (closed) { throw new XMLStreamException("Stream has been closed"); } if (nextEvent == null) { nextEvent = allocateEvent(); reader.next(); } return nextEvent; } public Object next() { try { return nextEvent(); } catch (XMLStreamException e) { // TODO throw a more descriptive exception? throw new RuntimeException(e); } } public void remove() { throw new UnsupportedOperationException(); } public synchronized void close() throws XMLStreamException { if (!closed) { reader.close(); closed = true; nextEvent = null; reader = null; allocator = null; } } /** * Reads the next event from the underlying reader. * * @return The allocated {@link XMLEvent}. * @throws XMLStreamException If an error occurs reading the underlying stream. */ protected XMLEvent allocateEvent() throws XMLStreamException { return allocator.allocate(reader); } }src/javanet/staxutils/IndentingXMLEventWriter.java0000644000175000017500000003162310424446144021453 0ustar tonytony/* 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 java.io.IOException; import java.io.Writer; import java.util.Arrays; import java.util.regex.Pattern; import javanet.staxutils.events.AbstractCharactersEvent; import javanet.staxutils.helpers.EventWriterDelegate; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Characters; import javax.xml.stream.events.XMLEvent; /** * A filter that indents an XML stream. To apply it, construct a filter that * contains another {@link XMLEventWriter}, which you pass to the constructor. * Then call methods of the filter instead of the contained stream. For example: * *
 * {@link XMLEventWriter} stream = ...
 * stream = new {@link IndentingXMLEventWriter}(stream);
 * stream.add(...);
 * 
* *

* The filter inserts characters to format the document as an outline, with * nested elements indented. Basically, it inserts a line break and whitespace * before: *

* This works well with 'data-oriented' XML, wherein each element contains * either data or nested elements but not both. It can work badly with other * styles of XML. For example, the data in a 'mixed content' document are apt to * be polluted with indentation characters. *

* Indentation can be adjusted by setting the newLine and indent properties. But * set them to whitespace only, for best results. Non-whitespace is apt to cause * problems, for example when this class attempts to insert newLine before the * root element. * * @author Kohsuke Kawaguchi * @author John Kristian */ public class IndentingXMLEventWriter extends EventWriterDelegate implements Indentation { public IndentingXMLEventWriter(XMLEventWriter out) { super(out); } /** How deeply nested the current scope is. The root element is depth 1. */ private int depth = 0; // document scope /** stack[depth] indicates what's been written into the current scope. */ private int[] stack = new int[] { 0, 0, 0, 0 }; // nothing written yet private static final int WROTE_MARKUP = 1; private static final int WROTE_DATA = 2; /** An object that produces a line break and indentation. */ private final PrefixCharacters newLineEvent = new PrefixCharacters(); public void setIndent(String indent) { newLineEvent.setIndent(indent); } public void setNewLine(String newLine) { newLineEvent.setNewLine(newLine); } public String getIndent() { return newLineEvent.getIndent(); } public String getNewLine() { return newLineEvent.getNewLine(); } /** * @return System.getProperty("line.separator"); or * {@link #NORMAL_END_OF_LINE} if that fails. */ public static String getLineSeparator() { return IndentingXMLStreamWriter.getLineSeparator(); } public void add(XMLEvent event) throws XMLStreamException { switch (event.getEventType()) { case XMLStreamConstants.CHARACTERS: case XMLStreamConstants.CDATA: case XMLStreamConstants.SPACE: out.add(event); afterData(); return; case XMLStreamConstants.START_ELEMENT: beforeStartElement(); out.add(event); afterStartElement(); return; case XMLStreamConstants.END_ELEMENT: beforeEndElement(); out.add(event); afterEndElement(); return; case XMLStreamConstants.START_DOCUMENT: case XMLStreamConstants.PROCESSING_INSTRUCTION: case XMLStreamConstants.COMMENT: case XMLStreamConstants.DTD: beforeMarkup(); out.add(event); afterMarkup(); return; case XMLStreamConstants.END_DOCUMENT: out.add(event); afterEndDocument(); break; default: out.add(event); return; } } /** Prepare to write markup, by writing a new line and indentation. */ protected void beforeMarkup() { int soFar = stack[depth]; if ((soFar & WROTE_DATA) == 0 // no data in this scope && (depth > 0 || soFar != 0)) // not the first line { try { newLineEvent.write(out, depth); if (depth > 0 && getIndent().length() > 0) { afterMarkup(); // indentation was written } } catch (Exception e) { } } } /** Note that markup or indentation was written. */ protected void afterMarkup() { stack[depth] |= WROTE_MARKUP; } /** Note that data were written. */ protected void afterData() { stack[depth] |= WROTE_DATA; } /** Prepare to start an element, by allocating stack space. */ protected void beforeStartElement() { beforeMarkup(); if (stack.length <= depth + 1) { // Allocate more space for the stacks: int[] newWrote = new int[stack.length * 2]; System.arraycopy(stack, 0, newWrote, 0, stack.length); stack = newWrote; } stack[depth + 1] = 0; // nothing written yet } /** Note that an element was started. */ protected void afterStartElement() { afterMarkup(); ++depth; } /** Prepare to end an element, by writing a new line and indentation. */ protected void beforeEndElement() { if (depth > 0 && stack[depth] == WROTE_MARKUP) { // but not data try { newLineEvent.write(out, depth - 1); } catch (Exception ignored) { } } } /** Note that an element was ended. */ protected void afterEndElement() { if (depth > 0) { --depth; } } /** Note that a document was ended. */ protected void afterEndDocument() { depth = 0; if (stack[0] == WROTE_MARKUP) { // but not data try { newLineEvent.write(out, 0); } catch (Exception ignored) { } } stack[0] = 0; // start fresh } private static class PrefixCharacters extends AbstractCharactersEvent implements Indentation { PrefixCharacters() { super((String) null); } /** String used for indentation. */ private String indent = DEFAULT_INDENT; /** String for EOL. */ private String newLine = NORMAL_END_OF_LINE; /** * Various combinations of newLine and indent, used to begin and indent * a line. The appropriate prefix for a given depth is prefixes[depth % * prefixes.length]. This array is managed as a ring buffer, containing * the prefix for the current depth and recently used adjacent prefixes. *

* This structure uses memory proportional to the maximum depth. * Retaining prefixes for all depths would be faster, but require memory * proportional the square of the maximum depth. */ private final String[] prefixes = new String[] { null, null, null, null, null, null }; /** * The depth of the shortest String in prefixes (which is located at * prefixes[minimumPrefix % prefixes.length]). */ private int minimumPrefix = 0; public String getIndent() { return indent; } public String getNewLine() { return newLine; } public void setIndent(String indent) { if (!indent.equals(this.indent)) { Arrays.fill(prefixes, null); } this.indent = indent; } public void setNewLine(String newLine) { if (!newLine.equals(this.newLine)) { Arrays.fill(prefixes, null); } this.newLine = newLine; } void write(XMLEventWriter out, int depth) throws XMLStreamException { this.depth = depth; // so getData knows what to do. out.add(this); } /** An implicit parameter to getData(). */ private int depth = 0; public String getData() { while (depth >= minimumPrefix + prefixes.length) { prefixes[minimumPrefix++ % prefixes.length] = null; } while (depth < minimumPrefix) { prefixes[--minimumPrefix % prefixes.length] = null; } final int p = depth % prefixes.length; String data = prefixes[p]; if (data == null) { StringBuffer b = new StringBuffer(newLine.length() + (indent.length() * depth)); b.append(newLine); for (int d = 0; d < depth; ++d) { b.append(indent); } data = prefixes[p] = b.toString(); } return data; } public int getEventType() { // it's not clear if we are supposed to return SPACES return XMLStreamConstants.CHARACTERS; } public Characters asCharacters() { return this; } public boolean isCData() { return false; } public boolean isIgnorableWhiteSpace() { return isWhiteSpace(); } private static final Pattern ENCODABLE = Pattern.compile("[&<>]"); public void writeAsEncodedUnicode(Writer writer) throws XMLStreamException { // Similar to super.writeAsEncodedUnicode; // but '\r' is not encoded. // TODO? memoize the encoded string. try { String s = getData(); if (!ENCODABLE.matcher(s).find()) { writer.write(s); } else { final char[] data = s.toCharArray(); int first = 0; for (int d = first; d < data.length; ++d) { switch (data[d]) { case '&': writer.write(data, first, d - first); writer.write("&"); first = d + 1; break; case '<': writer.write(data, first, d - first); writer.write("<"); first = d + 1; break; case '>': writer.write(data, first, d - first); writer.write(">"); first = d + 1; break; default: } } writer.write(data, first, data.length - first); } } catch (IOException e) { throw new XMLStreamException(e); } } } } src/javanet/staxutils/StAXStreamContentHandler.java0000644000175000017500000001537510072360400021573 0ustar tonytony/* * $Id: StAXStreamContentHandler.java,v 1.5 2004-07-05 23:15:11 cniles Exp $ * * Copyright (c) 2004, Christian Niles, Unit12 * 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 Christian Niles, Unit12, 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 java.util.Iterator; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * SAX ContentHandler that writes events to a StAX {@link XMLStreamWriter}. * * @author Christian Niles * @version $Revision: 1.5 $ */ public class StAXStreamContentHandler extends StAXContentHandler { /** The StAX stream to which SAX events will be written. */ private XMLStreamWriter writer; public StAXStreamContentHandler() { } /** * Constructs an instance that writes SAX events to the specified StAX * stream. * * @param writer The StAX stream to which events will be written. */ public StAXStreamContentHandler(XMLStreamWriter writer) { this.writer = writer; } /** * Returns a reference to the {@link XMLStreamWriter}to which SAX events * are written. * * @return The {@link XMLStreamWriter}to which SAX events are written. */ public XMLStreamWriter getStreamWriter() { return writer; } /** * Sets the {@link XMLStreamWriter}to which SAX events will be written. * * @param writer The {@link XMLStreamWriter}to which SAX events will be * written. */ public void setStreamWriter(XMLStreamWriter writer) { this.writer = writer; } public void startDocument() throws SAXException { super.startDocument(); try { writer.writeStartDocument(); } catch (XMLStreamException e) { throw new SAXException(e); } } public void endDocument() throws SAXException { try { writer.writeEndDocument(); } catch (XMLStreamException e) { throw new SAXException(e); } super.endDocument(); } public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { try { String[] qname = {null, null}; parseQName(qName, qname); writer.writeStartElement(qname[0], qname[1], uri); // copy namespaces if (namespaces != null) { Iterator prefixes = namespaces.getDeclaredPrefixes(); while (prefixes.hasNext()) { String prefix = (String) prefixes.next(); String nsURI = namespaces.getNamespaceURI(prefix); if (prefix.length() == 0) { writer.setDefaultNamespace(nsURI); } else { writer.setPrefix(prefix, nsURI); } writer.writeNamespace(prefix, nsURI); } } // write attributes for (int i = 0, s = attributes.getLength(); i < s; i++) { parseQName(attributes.getQName(i), qname); String attrPrefix = qname[0]; String attrLocal = qname[1]; String attrQName = attributes.getQName(i); String attrValue = attributes.getValue(i); String attrURI = attributes.getURI(i); if ("xmlns".equals(attrQName) || "xmlns".equals(attrPrefix)) { // namespace declaration disguised as an attribute. If the // namespace has already been declared, skip it, otherwise // write it as an namespace String nsURI = namespaces.getNamespaceURI(attrPrefix); if (nsURI == null) { if (attrPrefix.length() == 0) { writer.setDefaultNamespace(attrValue); } else { writer.setPrefix(attrPrefix, attrValue); } writer.writeNamespace(attrPrefix, attrValue); } } else if (attrPrefix.length() > 0) { writer.writeAttribute(attrPrefix, attrURI, attrLocal, attrValue); } else { writer.writeAttribute(attrQName, attrValue); } } } catch (XMLStreamException e) { throw new SAXException(e); } finally { super.startElement(uri, localName, qName, attributes); } } public void endElement(String uri, String localName, String qName) throws SAXException { try { writer.writeEndElement(); } catch (XMLStreamException e) { throw new SAXException(e); } finally { super.endElement(uri, localName, qName); } } public void comment(char[] ch, int start, int length) throws SAXException { super.comment(ch, start, length); try { writer.writeComment(new String(ch, start, length)); } catch (XMLStreamException e) { throw new SAXException(e); } } public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); try { if (!isCDATA) { writer.writeCharacters(ch, start, length); } } catch (XMLStreamException e) { throw new SAXException(e); } } public void endCDATA() throws SAXException { try { writer.writeCData(CDATABuffer.toString()); } catch (XMLStreamException e) { throw new SAXException(e); } super.endCDATA(); } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { super.ignorableWhitespace(ch, start, length); try { writer.writeCharacters(ch, start, length); } catch (XMLStreamException e) { throw new SAXException(e); } } public void processingInstruction(String target, String data) throws SAXException { super.processingInstruction(target, data); try { writer.writeProcessingInstruction(target, data); } catch (XMLStreamException e) { throw new SAXException(e); } } } src/javanet/staxutils/XMLEventPipe.java0000644000175000017500000002213210072364154017226 0ustar tonytony/* * $Id: XMLEventPipe.java,v 1.2 2004-07-05 23:46:51 cniles Exp $ * * Copyright (c) 2004, Christian Niles, Unit12 * 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 Christian Niles, Unit12, 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 java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.XMLEvent; /** * Provides the ability to pipe the {@link XMLEvent}s written to one * {@link XMLEventWriter} to be read from a {@link XMLEventReader}. The * implementation is based on a bounded-buffer with a specifiable maximum * capacity. When that capacity is reached, the write end of the pipe will * block until events are read from the read end. Similarly, when an attempt is * made to read from an empty queue, the operation will block until more events * are written to the buffer. The write end of the pipe will repair namespaces * and buffer attribute/namespace events as defined in the specification of * the {@link XMLEventWriter} interface. *

* Both the read and write ends of this pipe are fully synchronized to allow * multiple threads to read or write events to the pipe. However, care must be * taken that the order of events is consistent, and that the stream is properly * closed when writing is complete. If the write end is never closed the read * end may block indefinitely, waiting for further events. To help prevent * this, the write end will automatically close when an END_DOCUMENT event is * written. *

* To properly obey the expected behaviour of {@link XMLEventReader} and * {@link javax.xml.stream.XMLStreamWriter}, methods such as * {@link XMLEventReader#peek()} and {@link XMLEventReader#hasNext()} may block. * This is necessary to prevent {@link XMLEventReader#hasNext()} from returning * true just before the write end is closed, or false * just before additional events are added. If the read end is closed before the * writer, then the write end will silently discard all elements written to it * until it is closed. * * @author Christian Niles * @version $Revision: 1.2 $ */ public class XMLEventPipe { /** * Default maximum number of events that may be stored by this pipe until * the write end blocks. */ public static final int QUEUE_CAPACITY = 16; /** List of events ready to be read. */ private List eventQueue = new LinkedList(); /** The maximum capacity of the queue, after which the pipe should block. */ private int capacity = QUEUE_CAPACITY; /** Whether the read end has been closed. */ private boolean readEndClosed; /** Whether the write end has been closed. */ private boolean writeEndClosed; /** * The read end of the pipe. This will be null until * {@link #getReadEnd()} is called for the first time. */ private PipedXMLEventReader readEnd = new PipedXMLEventReader(this); /** * The write end of the pipe. This will be null until * {@link #getWriteEnd()} is called for the first time. */ private PipedXMLEventWriter writeEnd = new PipedXMLEventWriter(this); /** * Constructs a new XMLEventPipe with the default capacity. */ public XMLEventPipe() { } /** * Constructs a new XMLEventPipe with the specified capacity. * * @param capacity The number of events to buffer until the pipe will block. * A number less than or equal to 0 means the pipe will buffer an * unbounded number of events. */ public XMLEventPipe(int capacity) { this.capacity = capacity; } /** * Returns the read end of the pipe, from which events written to the write * end of the pipe will be available. * * @return The read end of the pipe. */ public synchronized XMLEventReader getReadEnd() { if (readEnd == null) { readEnd = new PipedXMLEventReader(this); } return readEnd; } /** * Returns the write end of the pipe, whose events will be available from * the read end of this pipe. * * @return The write end of the pipe. */ public synchronized XMLEventWriter getWriteEnd() { if (writeEnd == null) { writeEnd = new PipedXMLEventWriter(this); } return writeEnd; } /** * {@link XMLEventWriter} implementation used to provide the write end of * the pipe. * * @author christian * @version $Revision: 1.2 $ */ private static final class PipedXMLEventWriter extends BaseXMLEventWriter { /** The pipe we're connected to. */ private XMLEventPipe pipe; public PipedXMLEventWriter(XMLEventPipe pipe) { this.pipe = pipe; } public synchronized void close() throws XMLStreamException { super.close(); synchronized (pipe) { if (pipe.readEndClosed) { pipe.eventQueue.clear(); } pipe.writeEndClosed = true; pipe.notifyAll(); } } protected void sendEvent(XMLEvent event) throws XMLStreamException { synchronized (pipe) { if (pipe.readEndClosed) { // if read end is closed, throw away event return; } if (pipe.capacity > 0) { while (pipe.eventQueue.size() >= pipe.capacity) { try { pipe.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } pipe.eventQueue.add(event); if (pipe.eventQueue.size() == 1) { pipe.notifyAll(); } if (event.isEndDocument()) { close(); } } } } /** * {@link XMLEventReader} implementation used to provide the read end of * the pipe. * * @author christian * @version $Revision: 1.2 $ */ private static final class PipedXMLEventReader extends BaseXMLEventReader { /** THe pipe this stream is connected to. */ private XMLEventPipe pipe; public PipedXMLEventReader(XMLEventPipe pipe) { this.pipe = pipe; } public synchronized XMLEvent nextEvent() throws XMLStreamException { if (closed) { throw new XMLStreamException("Stream has been closed"); } synchronized (pipe) { while (pipe.eventQueue.size() == 0) { if (pipe.writeEndClosed) { throw new NoSuchElementException("Stream has completed"); } try { pipe.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } boolean notify = pipe.capacity > 0 && pipe.eventQueue.size() >= pipe.capacity; // remove next event from the queue XMLEvent nextEvent = (XMLEvent) pipe.eventQueue.remove(0); if (notify) { pipe.notifyAll(); } return nextEvent; } } public synchronized boolean hasNext() { if (closed) { return false; } synchronized (pipe) { while (pipe.eventQueue.size() == 0) { if (pipe.writeEndClosed) { break; } try { pipe.wait(); } catch (InterruptedException e) { } } return pipe.eventQueue.size() > 0; } } public synchronized XMLEvent peek() throws XMLStreamException { if (closed) { return null; } synchronized (pipe) { // wait until the queue has more events while (pipe.eventQueue.size() == 0) { if (pipe.writeEndClosed) { return null; } try { pipe.wait(); } catch (InterruptedException e) { } } return (XMLEvent) pipe.eventQueue.get(0); } } public synchronized void close() throws XMLStreamException { if (closed) { return; } synchronized (pipe) { pipe.readEndClosed = true; pipe.notifyAll(); } super.close(); } public void finalize() { if (!closed) { synchronized (pipe) { pipe.readEndClosed = true; pipe.notifyAll(); } } } } } src/javanet/staxutils/StAXEventContentHandler.java0000644000175000017500000003102610072360400021410 0ustar tonytony/* * $Id: StAXEventContentHandler.java,v 1.5 2004-07-05 23:15:11 cniles Exp $ * * Copyright (c) 2004, Christian Niles, Unit12 * 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 Christian Niles, Unit12, 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 java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.*; import javax.xml.stream.util.XMLEventConsumer; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * SAX ContentHandler that writes events to a StAX {@link XMLEventConsumer}. * * @author Christian Niles * @version $Revision: 1.5 $ */ public class StAXEventContentHandler extends StAXContentHandler { /** The consumer to which events will be written. */ private XMLEventConsumer consumer; /** The factory used to construct events. */ private XMLEventFactory eventFactory; /** * A stack of {@link List}s, each containing {@link Namespace}events * constructed from a {@link StartElement}event. It is necessary to keep * these namespaces so we can report them to the {@link EndElement}event. */ private List namespaceStack = new ArrayList(); /** * Constructs a default instance with a default event factory. You must set * the {@link XMLEventConsumer}via the * {@link #setEventConsumer(XMLEventConsumer)}method. */ public StAXEventContentHandler() { eventFactory = XMLEventFactory.newInstance(); } /** * Constructs an instance that writes events to the provided * XMLEventConsumer. Events will be constructed from a default * XMLEventFactory instance. * * @param consumer The {@link XMLEventConsumer}to which events will be * written. */ public StAXEventContentHandler(XMLEventConsumer consumer) { this.consumer = consumer; eventFactory = XMLEventFactory.newInstance(); } /** * Constructs an instance that writes events constructed with the provided * XMLEventFactory to the provided XMLEventConsumer * * @param consumer The {@link XMLEventConsumer} to which events will be * written. * @param factory The {@link XMLEventFactory} used to construct events. If * null, a default instance will be constructed. */ public StAXEventContentHandler(XMLEventConsumer consumer, XMLEventFactory factory) { this.consumer = consumer; if (factory != null) { this.eventFactory = factory; } else { eventFactory = XMLEventFactory.newInstance(); } } /** * Returns a reference to the {@link XMLEventConsumer} to which events will * be written. * * @return The {@link XMLEventConsumer} to which events will be written. */ public XMLEventConsumer getEventConsumer() { return consumer; } /** * Sets the {@link XMLEventConsumer} to which events are written. * * @param consumer The {@link XMLEventConsumer} to which events will be * written. */ public void setEventConsumer(XMLEventConsumer consumer) { this.consumer = consumer; } /** * Returns a reference to the {@link XMLEventFactory} used to construct * events. * * @return The {@link XMLEventFactory} used to construct events. */ public XMLEventFactory getEventFactory() { return eventFactory; } /** * Sets the {@link XMLEventFactory} used to create events. * * @param factory The {@link XMLEventFactory} used to create events. */ public void setEventFactory(XMLEventFactory factory) { this.eventFactory = factory; } public void startDocument() throws SAXException { super.startDocument(); // clear the namespaces in case we ended in error before. namespaceStack.clear(); eventFactory.setLocation(getCurrentLocation()); try { consumer.add(eventFactory.createStartDocument()); } catch (XMLStreamException e) { throw new SAXException(e); } } public void endDocument() throws SAXException { eventFactory.setLocation(getCurrentLocation()); try { consumer.add(eventFactory.createEndDocument()); } catch (XMLStreamException e) { throw new SAXException(e); } super.endDocument(); // clear the namespaces namespaceStack.clear(); } public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // set document location eventFactory.setLocation(getCurrentLocation()); // create attribute and namespace events Collection[] events = {null, null}; createStartEvents(attributes, events); // save a reference to the namespace collection so we can use them // again // in the end element namespaceStack.add(events[0]); try { String[] qname = {null, null}; parseQName(qName, qname); consumer.add(eventFactory.createStartElement(qname[0], uri, qname[1], events[1].iterator(), events[0].iterator())); } catch (XMLStreamException e) { throw new SAXException(e); } finally { super.startElement(uri, localName, qName, attributes); } } public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); eventFactory.setLocation(getCurrentLocation()); // parse name String[] qname = {null, null}; parseQName(qName, qname); // get namespaces Collection nsList = (Collection) namespaceStack.remove(namespaceStack.size() - 1); Iterator nsIter = nsList.iterator(); try { consumer.add(eventFactory.createEndElement(qname[0], uri, qname[1], nsIter)); } catch (XMLStreamException e) { throw new SAXException(e); } } public void comment(char[] ch, int start, int length) throws SAXException { super.comment(ch, start, length); eventFactory.setLocation(getCurrentLocation()); try { consumer.add(eventFactory.createComment(new String(ch, start, length))); } catch (XMLStreamException e) { throw new SAXException(e); } } public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); try { if (!isCDATA) { eventFactory.setLocation(getCurrentLocation()); consumer.add(eventFactory.createCharacters(new String(ch, start, length))); } } catch (XMLStreamException e) { throw new SAXException(e); } } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { super.ignorableWhitespace(ch, start, length); characters(ch, start, length); } public void processingInstruction(String target, String data) throws SAXException { super.processingInstruction(target, data); try { consumer.add(eventFactory.createProcessingInstruction(target, data)); } catch (XMLStreamException e) { throw new SAXException(e); } } public void endCDATA() throws SAXException { eventFactory.setLocation(getCurrentLocation()); try { consumer.add(eventFactory.createCData(CDATABuffer.toString())); } catch (XMLStreamException e) { throw new SAXException(e); } super.endCDATA(); } /** * Creates the {@link Namespace}and {@link Attribute}events associated * with a {@link StartElement}. * * @param attributes The SAX attributes object. * @param events An array used to return the two collections of * {@link Namespace}and {@link Attribute}events. The * namespaces will be placed at events[0] and the * attributes as events[1]. */ protected void createStartEvents(Attributes attributes, Collection[] events) { Map nsMap = null; List attrs = null; // create namespaces if (namespaces != null) { Iterator prefixes = namespaces.getDeclaredPrefixes(); while (prefixes.hasNext()) { String prefix = (String) prefixes.next(); String uri = namespaces.getNamespaceURI(prefix); Namespace ns = createNamespace(prefix, uri); if (nsMap == null) { nsMap = new HashMap(); } nsMap.put(prefix, ns); } } // create attributes String[] qname = {null, null}; for (int i = 0, s = attributes.getLength(); i < s; i++) { parseQName(attributes.getQName(i), qname); String attrPrefix = qname[0]; String attrLocal = qname[1]; String attrQName = attributes.getQName(i); String attrValue = attributes.getValue(i); String attrURI = attributes.getURI(i); if ("xmlns".equals(attrQName) || "xmlns".equals(attrPrefix)) { // namespace declaration disguised as an attribute. If the // namespace has already been declared, skip it, otherwise // write it as an namespace if (!nsMap.containsKey(attrPrefix)) { Namespace ns = createNamespace(attrPrefix, attrValue); if (nsMap == null) { nsMap = new HashMap(); } nsMap.put(attrPrefix, ns); } } else { Attribute attribute; if (attrPrefix.length() > 0) { attribute = eventFactory.createAttribute(attrPrefix, attrURI, attrLocal, attrValue); } else { attribute = eventFactory.createAttribute(attrLocal, attrValue); } if (attrs == null) { attrs = new ArrayList(); } attrs.add(attribute); } } events[0] = (nsMap == null ? Collections.EMPTY_LIST : nsMap.values()); events[1] = (attrs == null ? Collections.EMPTY_LIST : attrs); } protected Namespace createNamespace(String prefix, String uri) { if (prefix == null || prefix.length() == 0) { return eventFactory.createNamespace(uri); } else { return eventFactory.createNamespace(prefix, uri); } } }src/javanet/staxutils/helpers/0000755000175000017500000000000011542302312015534 5ustar tonytonysrc/javanet/staxutils/helpers/FilterXMLOutputFactory.java0000644000175000017500000001144410424446060022771 0ustar tonytony/* Copyright (c) 2006, John Kristian * 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 StAX-Utils 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.helpers; import java.io.OutputStream; import java.io.Writer; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import javax.xml.transform.Result; /** * An output factory that transforms each writer from a contained factory. * Subclasses are required to implement the transformation. */ public abstract class FilterXMLOutputFactory extends XMLOutputFactory { public FilterXMLOutputFactory() { this(XMLOutputFactory.newInstance()); } public FilterXMLOutputFactory(XMLOutputFactory source) { this.source = source; } protected XMLOutputFactory source; /** Transform the given writer. */ protected abstract XMLEventWriter filter(XMLEventWriter writer); protected abstract XMLStreamWriter filter(XMLStreamWriter writer); /** Delegates to source. */ public boolean isPropertySupported(String name) { return source.isPropertySupported(name); } /** Delegates to source. */ public void setProperty(String name, Object value) throws IllegalArgumentException { source.setProperty(name, value); } /** Delegates to source. */ public Object getProperty(String name) throws IllegalArgumentException { return source.getProperty(name); } public XMLEventWriter createXMLEventWriter(Result result) throws XMLStreamException { return filter(source.createXMLEventWriter(result)); } public XMLEventWriter createXMLEventWriter(Writer writer) throws XMLStreamException { return filter(source.createXMLEventWriter(writer)); } public XMLEventWriter createXMLEventWriter(OutputStream stream) throws XMLStreamException { return filter(source.createXMLEventWriter(stream)); } public XMLEventWriter createXMLEventWriter(OutputStream stream, String encoding) throws XMLStreamException { return filter(source.createXMLEventWriter(stream, encoding)); } public XMLStreamWriter createXMLStreamWriter(Result result) throws XMLStreamException { return filter(source.createXMLStreamWriter(result)); } public XMLStreamWriter createXMLStreamWriter(Writer writer) throws XMLStreamException { return filter(source.createXMLStreamWriter(writer)); } public XMLStreamWriter createXMLStreamWriter(OutputStream stream) throws XMLStreamException { return filter(source.createXMLStreamWriter(stream)); } public XMLStreamWriter createXMLStreamWriter(OutputStream stream, String encoding) throws XMLStreamException { return filter(source.createXMLStreamWriter(stream, encoding)); } public int hashCode() { return hashCode(source); } protected static int hashCode(Object o) { return (o == null) ? 0 : o.hashCode(); } public boolean equals(Object o) { if (!(o instanceof FilterXMLOutputFactory)) return false; FilterXMLOutputFactory that = (FilterXMLOutputFactory) o; return equals(source, that.source); } protected static boolean equals(Object x, Object y) { return (x == null) ? (y == null) : x.equals(y); } } src/javanet/staxutils/helpers/UnknownLocation.java0000644000175000017500000000457211535774174021564 0ustar tonytony/* * Copyright (c) 2004, Christian Niles, unit12.net * 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 StAX-Utils 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. * */ /* * $Id: UnknownLocation.java,v 1.1 2004-07-08 14:30:23 cniles Exp $ */ package javanet.staxutils.helpers; import javanet.staxutils.StaticLocation; import javax.xml.stream.Location; /** * {@link Location} used to represent unknown locations. * * @author Christian Niles * @version $Revision: 1.1 $ */ public final class UnknownLocation implements Location, StaticLocation { public static final UnknownLocation INSTANCE = new UnknownLocation(); public int getLineNumber() { return -1; } public int getColumnNumber() { return -1; } public int getCharacterOffset() { return -1; } public String getPublicId() { return null; } public String getSystemId() { return null; } } src/javanet/staxutils/helpers/ListEventConsumer.java0000644000175000017500000000653610075335262022054 0ustar tonytony/* * $Id: ListEventConsumer.java,v 1.1 2004-07-14 22:58:58 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.helpers; import java.util.ArrayList; import java.util.List; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.util.XMLEventConsumer; /** * {@link XMLEventConsumer} that stores all added events in a {@link List}. * * @author Christian Niles * @version $Revision: 1.1 $ */ public class ListEventConsumer implements XMLEventConsumer { /** The list in which to store events. */ private List events; public ListEventConsumer() { } /** * Constructs an instance that adds events to the provided list. * * @param events The list to which events will be added, or null. */ public ListEventConsumer(List events) { this.events = events; } /** * Adds the event to the internal list. */ public void add(XMLEvent event) throws XMLStreamException { if (events == null) { events = new ArrayList(); } events.add(event); } /** * Returns the {@link List} of events added to this consumer. * * @return The {@link List} of events added to this consumer. */ public List getEvents() { return events; } /** * Sets the {@link List} to which events will be written. * * @param events The {@link List} to which events will be written. */ public void setEvents(List events) { this.events = events; } /** * Removes all events from the internal list, making it available for reuse. */ public void reset() { if (events != null) { events.clear(); } } }src/javanet/staxutils/helpers/XMLFilterImplEx.java0000644000175000017500000000775211535774174021364 0ustar tonytony/* * Copyright (c) 2006, Paul Sandoz * 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 StAX-Utils 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.helpers; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.XMLFilterImpl; /** * Extension to XMLFilterImpl that implements LexicalHandler. * * @author Paul.Sandoz@Sun.Com */ public class XMLFilterImplEx extends XMLFilterImpl implements LexicalHandler { protected LexicalHandler lexicalHandler; protected boolean namespacePrefixes; public void setNamespacePrefixes(boolean v) { namespacePrefixes = v; } public boolean getNamespacePrefixes() { return namespacePrefixes; } /** * Set the lexical event handler. * * @param handler the new lexical handler */ public void setLexicalHandler(LexicalHandler handler) { lexicalHandler = handler; } /** * Get the lexical event handler. * * @return The current lexical handler, or null if none was set. */ public LexicalHandler getLexicalHandler() { return lexicalHandler; } //////////////////////////////////////////////////////////////////// // Implementation of org.xml.sax.ext.LexicalHandler. //////////////////////////////////////////////////////////////////// public void startDTD(String name, String publicId, String systemId) throws SAXException { if (lexicalHandler != null) { lexicalHandler.startDTD(name, publicId, systemId); } } public void endDTD() throws SAXException { if (lexicalHandler != null) { lexicalHandler.endDTD(); } } public void startEntity(String name) throws SAXException { if (lexicalHandler != null) { lexicalHandler.startEntity(name); } } public void endEntity(String name) throws SAXException { if (lexicalHandler != null) { lexicalHandler.endEntity(name); } } public void startCDATA() throws SAXException { if (lexicalHandler != null) { lexicalHandler.startCDATA(); } } public void endCDATA() throws SAXException { if (lexicalHandler != null) { lexicalHandler.endCDATA(); } } public void comment(char ch[], int start, int length) throws SAXException { if (lexicalHandler != null) { lexicalHandler.comment(ch, start, length); } } } src/javanet/staxutils/helpers/ListEventReader.java0000644000175000017500000000620210075335262021451 0ustar tonytony/* * $Id: ListEventReader.java,v 1.1 2004-07-14 22:58:58 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.helpers; import java.util.List; import java.util.NoSuchElementException; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.XMLEvent; import javanet.staxutils.BaseXMLEventReader; /** * {@link XMLEventReader} that reads events from a {@link List}. * * @author Christian Niles * @version $Revision: 1.1 $ */ public class ListEventReader extends BaseXMLEventReader { /** The index of the next event. */ private int nextEvent = 0; /** The {@link List} from which events are read. */ private List events; /** * Constructs a ListEventReader that reads events from the * provided {@link List}. * * @param events The {@link List} of events to read. */ public ListEventReader(List events) { this.events = events; } public XMLEvent nextEvent() throws XMLStreamException { if (hasNext()) { XMLEvent event = (XMLEvent) events.get(nextEvent); nextEvent++; return event; } else { throw new NoSuchElementException("End of stream reached"); } } public boolean hasNext() { return (nextEvent < events.size()); } public XMLEvent peek() throws XMLStreamException { if (hasNext()) { return (XMLEvent) events.get(nextEvent); } else { return null; } } }src/javanet/staxutils/helpers/StreamWriterDelegate.java0000644000175000017500000001467210424446144022506 0ustar tonytony/* * Copyright (c) 2006, John Kristian * 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 StAX-Utils 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.helpers; import javax.xml.namespace.NamespaceContext; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; /** * Abstract class for writing filtered XML streams. This class provides methods * that merely delegate to the contained stream. Subclasses should override some * of these methods, and may also provide additional methods and fields. * * @author John Kristian */ public abstract class StreamWriterDelegate implements XMLStreamWriter { protected StreamWriterDelegate(XMLStreamWriter out) { this.out = out; } protected XMLStreamWriter out; public Object getProperty(String name) throws IllegalArgumentException { return out.getProperty(name); } public NamespaceContext getNamespaceContext() { return out.getNamespaceContext(); } public void setNamespaceContext(NamespaceContext context) throws XMLStreamException { out.setNamespaceContext(context); } public void setDefaultNamespace(String uri) throws XMLStreamException { out.setDefaultNamespace(uri); } public void writeStartDocument() throws XMLStreamException { out.writeStartDocument(); } public void writeStartDocument(String version) throws XMLStreamException { out.writeStartDocument(version); } public void writeStartDocument(String encoding, String version) throws XMLStreamException { out.writeStartDocument(encoding, version); } public void writeDTD(String dtd) throws XMLStreamException { out.writeDTD(dtd); } public void writeProcessingInstruction(String target) throws XMLStreamException { out.writeProcessingInstruction(target); } public void writeProcessingInstruction(String target, String data) throws XMLStreamException { out.writeProcessingInstruction(target, data); } public void writeComment(String data) throws XMLStreamException { out.writeComment(data); } public void writeEmptyElement(String localName) throws XMLStreamException { out.writeEmptyElement(localName); } public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { out.writeEmptyElement(namespaceURI, localName); } public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { out.writeEmptyElement(prefix, localName, namespaceURI); } public void writeStartElement(String localName) throws XMLStreamException { out.writeStartElement(localName); } public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { out.writeStartElement(namespaceURI, localName); } public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { out.writeStartElement(prefix, localName, namespaceURI); } public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { out.writeDefaultNamespace(namespaceURI); } public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { out.writeNamespace(prefix, namespaceURI); } public String getPrefix(String uri) throws XMLStreamException { return out.getPrefix(uri); } public void setPrefix(String prefix, String uri) throws XMLStreamException { out.setPrefix(prefix, uri); } public void writeAttribute(String localName, String value) throws XMLStreamException { out.writeAttribute(localName, value); } public void writeAttribute(String namespaceURI, String localName, String value) throws XMLStreamException { out.writeAttribute(namespaceURI, localName, value); } public void writeAttribute(String prefix, String namespaceURI, String localName, String value) throws XMLStreamException { out.writeAttribute(prefix, namespaceURI, localName, value); } public void writeCharacters(String text) throws XMLStreamException { out.writeCharacters(text); } public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { out.writeCharacters(text, start, len); } public void writeCData(String data) throws XMLStreamException { out.writeCData(data); } public void writeEntityRef(String name) throws XMLStreamException { out.writeEntityRef(name); } public void writeEndElement() throws XMLStreamException { out.writeEndElement(); } public void writeEndDocument() throws XMLStreamException { out.writeEndDocument(); } public void flush() throws XMLStreamException { out.flush(); } public void close() throws XMLStreamException { out.close(); } } src/javanet/staxutils/helpers/ElementContext.java0000644000175000017500000003404210075364142021351 0ustar tonytony/* * $Id: ElementContext.java,v 1.1 2004-07-15 02:13:54 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.helpers; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.xml.namespace.NamespaceContext; import javax.xml.namespace.QName; import javanet.staxutils.SimpleNamespaceContext; /** * Encapsulates access to contextual element information, such as the element name, * attributes, and namespaces. This class is useful for recording element information * in a stack to keep track of the current element c[position in a document. * * @author Christian Niles * @version $Revision: 1.1 $ */ public class ElementContext extends SimpleNamespaceContext { /** The element name. */ private QName name; /** The encapsulating context. */ private ElementContext parent; /** Ordered list of attributes. */ private List attributeNames; /** Attribute values, keyed by their names. */ private Map attributes; /** Ordered list of namespace prefixes. */ private List namespacePrefixes; /** Whether the element is an empty element or not. */ private boolean isEmpty; /** Whether the context has been closed for further edits. */ private boolean readOnly; /** * Constructs a new ElementContext with the provided name and no * enclosing context. * * @param name The element name. */ public ElementContext(QName name) { this.name = name; } /** * Constructs a new ElementContext with the provided name and empty * value, and no enclosing context. * * @param name The element name. * @param isEmpty Whether the element is an empty element or not. */ public ElementContext(QName name, boolean isEmpty) { this.name = name; this.isEmpty = isEmpty; } /** * Constructs a new ElementContext with the provided name and * namespace context. * * @param name The element name. * @param context The enclosing namespace context. */ public ElementContext(QName name, NamespaceContext context) { super(context); this.name = name; } /** * Constructs a new ElementContext with the provided name and * enclosing context. * * @param name The element name. * @param parent The enclosing element context. */ public ElementContext(QName name, ElementContext parent) { super(parent); this.name = name; this.parent = parent; } /** * Constructs a new ElementContext with the provided name and * enclosing context. * * @param name The element name. * @param parent The enclosing element context. * @param isEmpty Whether the element is an empty element or not. */ public ElementContext(QName name, ElementContext parent, boolean isEmpty) { super(parent); this.name = name; this.parent = parent; this.isEmpty = isEmpty; } /** * Returns a reference to the enclosing ElementContext. * * @return The enclosing context, or null. */ public ElementContext getParentContext() { return parent; } /** * Determines if this context has an enclosing context or not. * * @return true if this context is the root context and has no * enclosing context, false otherwise. */ public boolean isRoot() { return parent == null; } /** * Returns the qualified name associated with the context. * * @return The qualified name of the context. */ public QName getName() { return name; } /** * Returns the current context path. * * @return A string representing the context path. */ public String getPath() { return appendPath(new StringBuffer()).toString(); } /** * @see #getPath() */ public String toString() { return getPath(); } /** * Appends the current context path to a {@link StringBuffer}. * * @param buffer The buffer to which to append the context path. * @return The provided buffer. */ public StringBuffer appendPath(StringBuffer buffer) { if (parent != null) { parent.appendPath(buffer); } return buffer.append('/').append(name); } /** * Determines the number of enclosing contexts. * * @return The number of enclosing contexts. */ public int getDepth() { if (parent == null) { return 0; } else { return parent.getDepth() + 1; } } /** * Constructs a new child ElementContext with the specified name. * * @param name The name associated with the child context. * @return The newly constructed child context. * @throws IllegalStateException If this context is empty. */ public ElementContext newSubContext(QName name) { if (!isEmpty()) { return new ElementContext(name, this); } else { throw new IllegalStateException("ElementContext is empty"); } } /** * Constructs a new child ElementContext with the specified name * and empty value. * * @param name The name associated with the child context. * @param isEmpty Whether the child context represents an empty element. * @return The newly constructed child context. * @throws IllegalStateException If this context is empty. */ public ElementContext newSubContext(QName name, boolean isEmpty) { if (!isEmpty()) { return new ElementContext(name, this, isEmpty); } else { throw new IllegalStateException("ElementContext is empty"); } } /** * Adds an attribute to the context with the specified name and value. * * @param name The attribute name. * @param value The attribute value. * @throws IllegalStateException If the context is read-only. */ public void putAttribute(QName name, String value) { if (isReadOnly()) { throw new IllegalStateException("ElementContext is readOnly"); } else if (attributes == null) { attributes = new HashMap(); attributeNames = new ArrayList(); } attributeNames.add(name); attributes.put(name, value); } /** * Adds a namespace declaration to this context with the specified prefix and * namespace uri. * * @param prefix The namespace prefix. * @param nsURI The namespace uri. */ public void putNamespace(String prefix, String nsURI) { if (isReadOnly()) { throw new IllegalStateException("ElementContext is readOnly"); } if (namespacePrefixes == null) { namespacePrefixes = new ArrayList(); } if (prefix.length() == 0) { // default namespace namespacePrefixes.add(prefix); super.setDefaultNamespace(nsURI); } else { namespacePrefixes.add(prefix); super.setPrefix(prefix, nsURI); } } /** * Returns the number of attributes defined in this context. * * @return The number of attributes defined in the context. */ public int attributeCount() { if (attributes != null) { return attributes.size(); } else { return 0; } } /** * Returns the value of the idxth attribute defined on * the context. * * @param idx The zero-based index of the attribute value to retrieve. * @return The value of the idxth attribute defined on * the context. * @throws IndexOutOfBoundsException If the index is out of bounds. */ public String getAttribute(int idx) { return getAttribute(getAttributeName(idx)); } /** * Returns the name of the idxth attribute defined on * the context. * * @param idx The zero-based index of the attribute name to retrieve. * @return The name of the idxth attribute defined on * the context. * @throws IndexOutOfBoundsException If the index is out of bounds. */ public QName getAttributeName(int idx) { if (attributeNames != null) { return (QName) attributeNames.get(idx); } else { throw new IndexOutOfBoundsException("Attribute index " + idx + " doesn't exist"); } } /** * Returns the value of a named attribute. * * @param name The name of the attribute value to retrieve. * @return The value of the named attribute, or null. */ public String getAttribute(QName name) { if (attributes != null) { return (String) attributes.get(name); } else { return null; } } /** * Determines if an attribute with the specified name exists in this context. * * @param name The name of the attribute. * @return true if an attribute with the specified name has been * defined in this context, false otherwise. */ public boolean attributeExists(QName name) { if (attributes != null) { return attributes.containsKey(name); } else { return false; } } /** * Returns an {@link Iterator} over the names of all attributes defined in this * context. The returned iterator will not support the {@link Iterator#remove()} * operation. * * @return An {@link Iterator} over the names of all attributes defined in this * context. */ public Iterator attributeNames() { if (attributeNames != null) { return Collections.unmodifiableList(attributeNames).iterator(); } else { return Collections.EMPTY_LIST.iterator(); } } /** * Determines the number of namespaces declared in this context. * * @return The number of namespaces declared in this context. */ public int namespaceCount() { if (namespacePrefixes != null) { return namespacePrefixes.size(); } else { return 0; } } /** * Returns the URI of the idxth namespace declaration * defined in this context. * * @param idx The index of the namespace URI to return. * @return The URI of the idxth namespace declaration * defined in this context. * @throws IndexOutOfBoundsException If the index is out of bounds. */ public String getNamespaceURI(int idx) { return this.getNamespaceURI(getNamespacePrefix(idx)); } /** * Returns the prefix of the idxth namespace declaration * defined in this context. * * @param idx The index of the namespace prefix to return. * @return The prefix of the idxth namespace declaration * defined in this context. * @throws IndexOutOfBoundsException If the index is out of bounds. */ public String getNamespacePrefix(int idx) { if (namespacePrefixes != null) { return (String) namespacePrefixes.get(idx); } else { throw new IndexOutOfBoundsException("Namespace index " + idx + " doesn't exist"); } } /** * Whether this context may be edited or not. * * @return true if no additional modifications may be made to this * context, false otherwise. */ public boolean isReadOnly() { return readOnly; } /** * Prevents any further additions to this context. */ public void setReadOnly() { this.readOnly = true; } /** * Whether this context represents an emtpy element. Empty contexts may not * enclose any other contexts. * * @return true if this context represents an emtpy element, * false otherwise. */ public boolean isEmpty() { return isEmpty; } }src/javanet/staxutils/helpers/EventMatcher.java0000644000175000017500000004343010074545702021003 0ustar tonytony/* * $Id: EventMatcher.java,v 1.2 2004-07-12 17:34:54 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.helpers; import java.util.Iterator; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.Characters; import javax.xml.stream.events.Comment; import javax.xml.stream.events.DTD; import javax.xml.stream.events.EndDocument; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.EntityDeclaration; import javax.xml.stream.events.EntityReference; import javax.xml.stream.events.Namespace; import javax.xml.stream.events.NotationDeclaration; import javax.xml.stream.events.ProcessingInstruction; import javax.xml.stream.events.StartDocument; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; /** * Provides utility methods useful for comparing two {@link XMLEvent} instances. * These methods compare only location/type-independent information, and thus don't * perform strict equality testing, which would include the event's location, * schema-type and dtd-type. * * @author Christian Niles * @version $Revision: 1.2 $ */ public final class EventMatcher { /** * Prevent instantiation */ private EventMatcher() { } /** * Compares two {@link XMLEvent} instances. This method delegates actual * matching to the appropriate overloaded method. * * @param a The first event. * @param b The second event. * @return true if the events match, false otherwise. */ public static boolean eventsMatch(XMLEvent a, XMLEvent b) { if (a == b) { return true; } else if (a == null || b == null) { return false; } else if (a.getEventType() == b.getEventType()) { switch (a.getEventType()) { case XMLEvent.START_ELEMENT : return eventsMatch(a.asStartElement(), b.asStartElement()); case XMLEvent.END_ELEMENT : return eventsMatch(a.asEndElement(), b.asEndElement()); case XMLEvent.CDATA : case XMLEvent.SPACE : case XMLEvent.CHARACTERS : return eventsMatch(a.asCharacters(), b.asCharacters()); case XMLEvent.COMMENT : return eventsMatch((Comment) a, (Comment) b); case XMLEvent.ENTITY_REFERENCE : return eventsMatch((EntityReference) a, (EntityReference) b); case XMLEvent.ATTRIBUTE : return eventsMatch((Attribute) a, (Attribute) b); case XMLEvent.NAMESPACE : return eventsMatch((Namespace) a, (Namespace) b); case XMLEvent.START_DOCUMENT : return eventsMatch((StartDocument) a, (StartDocument) b); case XMLEvent.END_DOCUMENT : return eventsMatch((EndDocument) a, (EndDocument) b); case XMLEvent.PROCESSING_INSTRUCTION : return eventsMatch((ProcessingInstruction) a, (ProcessingInstruction) b); case XMLEvent.DTD : return eventsMatch((DTD) a, (DTD) b); case XMLEvent.ENTITY_DECLARATION : return eventsMatch((EntityDeclaration) a, (EntityDeclaration) b); case XMLEvent.NOTATION_DECLARATION : return eventsMatch((NotationDeclaration) a, (NotationDeclaration) b); } } return false; } /** * Compares two {@link Attribute}s, returning true if their names * and values are the same. * * @param a The first event. * @param b The second event. * @return true if the events match, false otherwise. */ public static boolean eventsMatch(Attribute a, Attribute b) { if (a == b) { return true; } else if (a == null || b == null) { return false; } else if (a.getName().equals(b.getName())) { return a.getValue().equals(b.getValue()); } else { return false; } } /** * Compares two {@link Characters}s. This method will return true * only if they have the same event type ({@link XMLEvent#CHARACTERS}, * {@link XMLEvent#CDATA}, or {@link XMLEvent#SPACE}), and their text content * matches. * * @param a The first event. * @param b The second event. * @return true if the events match, false otherwise. */ public static boolean eventsMatch(Characters a, Characters b) { if (a == b) { return true; } else if (a == null || b == null) { return false; } else if (a.getEventType() == b.getEventType()) { return a.getData().equals(b.getData()); } else { return false; } } /** * Compares two {@link Comment}s. This method will return true * only if their text content matches. * * @param a The first event. * @param b The second event. * @return true if the events match, false otherwise. */ public static boolean eventsMatch(Comment a, Comment b) { if (a == b) { return true; } else if (a == null || b == null) { return false; } else { return a.getText().equals(b.getText()); } } /** * Compares two {@link DTD}s. This method will return true * only if their declarations are identical. * * @param a The first event. * @param b The second event. * @return true if the events match, false otherwise. */ public static boolean eventsMatch(DTD a, DTD b) { if (a == b) { return true; } else if (a == null || a == null) { return false; } else { // TODO determine the best way to compare DTD events return a.getDocumentTypeDeclaration().equals( b.getDocumentTypeDeclaration()); } } /** * Compares two {@link EndDocument}s. Because {@link EndDocument} events have no * real state, two instances always match. * * @param a The first event. * @param b The second event. * @return true if the events match, false otherwise. */ public static boolean eventsMatch(EndDocument a, EndDocument b) { return (a != null && b != null); } /** * Compares two {@link EndElement}s. This method will return true * only if their names match. * * @param a The first event. * @param b The second event. * @return true if the events match, false otherwise. */ public static boolean eventsMatch(EndElement a, EndElement b) { if (a == b) { return true; } else if (a == null || b == null) { return false; } else { return a.getName().equals(b.getName()); } } /** * Compares two {@link EntityDeclaration}s. This method will return * true only if the two events' names, replacement text, public IDs, * system IDs, and notations are the same. * * @param a The first event. * @param b The second event. * @return true if the events match, false otherwise. */ public static boolean eventsMatch(EntityDeclaration a, EntityDeclaration b) { if (a == b) { return true; } else if (a == null || b == null) { return false; } // compare names if (!a.getName().equals(b.getName())) { return false; } // compare base uris String baseURI = a.getBaseURI(); if (!(baseURI == null ? b.getBaseURI() == null : baseURI.equals(b.getBaseURI()))) { return false; } // compare replacement text String text = a.getReplacementText(); if (!(text == null ? b.getReplacementText() == null : text.equals(b.getReplacementText()))) { return false; } // compare public Ids String publicId = a.getPublicId(); if (!(publicId == null ? b.getPublicId() == null : publicId.equals(b.getPublicId()))) { return false; } // compare system ids String systemId = a.getSystemId(); if (!(systemId == null ? b.getSystemId() == null : systemId.equals(b.getSystemId()))) { return false; } // compare notations String ndata = a.getNotationName(); if (!(ndata == null ? b.getNotationName() == null : ndata.equals(b.getNotationName()))) { return false; } return true; } /** * Compares two {@link EntityReference}s. This method will return * true only if the two references have the same name, and their * declarations also match. * * @param a The first event. * @param b The second event. * @return true if the events match, false otherwise. */ public static boolean eventsMatch(EntityReference a, EntityReference b) { if (a == b) { return true; } else if (a == null || b == null) { return false; } if (a.getName().equals(b.getName())) { return eventsMatch(a.getDeclaration(), b.getDeclaration()); } else { return false; } } /** * Compares two {@link Namespace}s. This method will return true * only if the two namespaces have identical prefixes and namespace URIs. * * @param a The first event. * @param b The second event. * @return true if the events match, false otherwise. */ public static boolean eventsMatch(Namespace a, Namespace b) { if (a == b) { return true; } else if (a == null || b == null) { return false; } return (a.getPrefix().equals(b.getPrefix()) && a.getNamespaceURI() .equals(b.getNamespaceURI())); } /** * Compares two {@link NotationDeclaration}s. This method will return * true only if the two namespaces have identical names, public IDs, * and system IDs. * * @param a The first event. * @param b The second event. * @return true if the events match, false otherwise. */ public static boolean eventsMatch(NotationDeclaration a, NotationDeclaration b) { if (a == b) { return true; } else if (a == null || b == null) { return false; } // compare names if (!a.getName().equals(b.getName())) { return false; } // compare public Ids String publicId = a.getPublicId(); if (!(publicId == null ? b.getPublicId() == null : publicId.equals(b.getPublicId()))) { return false; } // compare system ids String systemId = a.getSystemId(); if (!(systemId == null ? b.getSystemId() == null : systemId.equals(b.getSystemId()))) { return false; } return true; } /** * Compares two {@link ProcessingInstruction}s. This method will return * true only if the two events have identical targets and data. * * @param a The first event. * @param b The second event. * @return true if the events match, false otherwise. */ public static boolean eventsMatch(ProcessingInstruction a, ProcessingInstruction b) { if (a == b) { return true; } else if (a == null || b == null) { return false; } return (a.getTarget().equals(b.getTarget()) && a.getData().equals( b.getData())); } /** * Compares two {@link StartDocument}s. This method will return * true only if the two events have identical encodings, versions, * and have the same standalone setting. * * @param a The first event. * @param b The second event. * @return true if the events match, false otherwise. */ public static boolean eventsMatch(StartDocument a, StartDocument b) { if (a == b) { return true; } else if (a == null || b == null) { return false; } if (!a.getCharacterEncodingScheme().equals( b.getCharacterEncodingScheme())) { return false; } else if (a.isStandalone() != b.isStandalone()) { return false; } else if (!a.getVersion().equals(b.getVersion())) { return false; } else { // TODO match the two system ID fields? return true; } } /** * Compares two {@link StartElement}s. This method will return * true only if the two events have identical names, attributes, and * namespaces. * * @param a The first event. * @param b The second event. * @return true if the events match, false otherwise. */ public static boolean eventsMatch(StartElement a, StartElement b) { if (a == b) { return true; } else if (a == null || b == null) { return false; } if (!a.getName().equals(b.getName())) { return false; } else if (!matchAttributes(a.getAttributes(), b.getAttributes())) { return false; } else if (!matchNamespaces(a.getNamespaces(), b.getNamespaces())) { return false; } else { return true; } } /** * Iterates over two sets of {@link Attribute}s and determines if both contain * matching attributes. * * @param a The first set of {@link Attribute}s. * @param b The second set of {@link Attribute}s. * @return true if the two iterators iterate over matching * attributes, false otherwise. */ public static boolean matchAttributes(Iterator a, Iterator b) { // TODO Update attribute matching to allow attributes to appear in different // order if (a == b) { return true; } else if (a == null || b == null) { return false; } while (a.hasNext() && b.hasNext()) { Attribute A = (Attribute) a.next(); Attribute B = (Attribute) b.next(); if (!eventsMatch(A, B)) { return false; } } return a.hasNext() == b.hasNext(); } /** * Iterates over two sets of {@link Namespace}s and determines if both contain * matching namespaces. * * @param a The first set of {@link Namespace}s. * @param b The second set of {@link Namespace}s. * @return true if the two iterators iterate over matching * namespaces, false otherwise. */ public static boolean matchNamespaces(Iterator a, Iterator b) { // TODO Update namespace matching to allow attributes to appear in different // order if (a == b) { return true; } else if (a == null || b == null) { return false; } while (a.hasNext() && b.hasNext()) { Namespace A = (Namespace) a.next(); Namespace B = (Namespace) b.next(); if (!eventsMatch(A, B)) { return false; } } return a.hasNext() == b.hasNext(); } }src/javanet/staxutils/helpers/package.html0000644000175000017500000000072410074545702020033 0ustar tonytony stax-utils Helper Package Provides helpful implementations of StAX interfaces, along with utility classes for performing various useful operations. src/javanet/staxutils/helpers/EventWriterDelegate.java0000644000175000017500000000667710424446144022342 0ustar tonytony/* * Copyright (c) 2006, John Kristian * 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 StAX-Utils 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.helpers; import javax.xml.namespace.NamespaceContext; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.XMLEvent; /** * Abstract class for implementing XML filters. This class provides methods that * merely delegate to a contained XMLEventWriter. Subclasses should override * some of these methods, and may also provide additional methods and fields. * * @author John Kristian */ public abstract class EventWriterDelegate implements XMLEventWriter { protected EventWriterDelegate(XMLEventWriter out) { this.out = out; } /** The downstream writer, to which events are delegated. */ protected final XMLEventWriter out; public void setNamespaceContext(NamespaceContext context) throws XMLStreamException { out.setNamespaceContext(context); } public NamespaceContext getNamespaceContext() { return out.getNamespaceContext(); } public void setDefaultNamespace(String uri) throws XMLStreamException { out.setDefaultNamespace(uri); } public void setPrefix(String prefix, String uri) throws XMLStreamException { out.setPrefix(prefix, uri); } public String getPrefix(String uri) throws XMLStreamException { return out.getPrefix(uri); } public void add(XMLEvent event) throws XMLStreamException { out.add(event); } /** Add events from the given reader, one by one. */ public void add(XMLEventReader reader) throws XMLStreamException { while (reader.hasNext()) { add(reader.nextEvent()); } } public void flush() throws XMLStreamException { out.flush(); } public void close() throws XMLStreamException { out.close(); } } src/javanet/staxutils/XMLEventStreamWriter.java0000644000175000017500000002231010415006464020755 0ustar tonytony/* * Copyright (c) 2006, John Kristian * 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 StAX-Utils 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 java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import javax.xml.namespace.NamespaceContext; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.Namespace; import javax.xml.stream.events.StartElement; /** * An {@link javax.xml.stream.XMLStreamWriter} that writes events to a * {@link javax.xml.stream.XMLEventWriter}. * * @author John Kristian */ public class XMLEventStreamWriter implements XMLStreamWriter { public XMLEventStreamWriter(XMLEventWriter out) { this(out, XMLEventFactory.newInstance()); } public XMLEventStreamWriter(XMLEventWriter out, XMLEventFactory factory) { this.out = out; this.factory = factory; } private XMLEventWriter out; private XMLEventFactory factory; private static final String DEFAULT_ENCODING = "UTF-8"; /** The number of elements that have been started but not ended. */ private int depth = 0; /** * Markup that matches previously started elements. stack[depth - 1] matches * the element that was started most recently. */ private EndElement[] stack = { null, null, null, null }; private void write(StartElement start) throws XMLStreamException { if (stack.length <= depth) { // Grow the stack: EndElement[] newStack = new EndElement[stack.length * 2]; System.arraycopy(stack, 0, newStack, 0, stack.length); stack = newStack; } out.add(start); // If that succeeded: stack[depth++] = factory.createEndElement(start.getName(), null); } private void write(Namespace space) throws XMLStreamException { EndElement end; { Collection spaces = new ArrayList(); EndElement oldEnd = stack[depth - 1]; Iterator oldSpaces = oldEnd.getNamespaces(); if (oldSpaces != null) { while (oldSpaces.hasNext()) { spaces.add(oldSpaces.next()); } } spaces.add(space); end = factory.createEndElement(oldEnd.getName(), spaces.iterator()); } out.add(space); // If that succeeded: stack[depth - 1] = end; } public Object getProperty(String name) throws IllegalArgumentException { throw new IllegalArgumentException(); // not supported } public void setNamespaceContext(NamespaceContext context) throws XMLStreamException { out.setNamespaceContext(context); } public NamespaceContext getNamespaceContext() { return out.getNamespaceContext(); } public void setDefaultNamespace(String uri) throws XMLStreamException { out.setDefaultNamespace(uri); } public String getPrefix(String uri) throws XMLStreamException { return out.getPrefix(uri); } public void setPrefix(String prefix, String uri) throws XMLStreamException { out.setPrefix(prefix, uri); } public void writeStartDocument() throws XMLStreamException { out.add(factory.createStartDocument(DEFAULT_ENCODING)); } public void writeStartDocument(String version) throws XMLStreamException { writeStartDocument(DEFAULT_ENCODING, version); } public void writeStartDocument(String encoding, String version) throws XMLStreamException { out.add(factory.createStartDocument(encoding, version)); } public void writeDTD(String dtd) throws XMLStreamException { out.add(factory.createDTD(dtd)); } public void writeComment(String data) throws XMLStreamException { out.add(factory.createComment(data)); } public void writeProcessingInstruction(String target) throws XMLStreamException { writeProcessingInstruction(target, ""); } public void writeProcessingInstruction(String target, String data) throws XMLStreamException { out.add(factory.createProcessingInstruction(target, data)); } public void writeEmptyElement(String localName) throws XMLStreamException { writeStartElement(localName); writeEndElement(); } public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { writeStartElement(namespaceURI, localName); writeEndElement(); } public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { writeStartElement(prefix, localName, namespaceURI); writeEndElement(); } public void writeStartElement(String localName) throws XMLStreamException { write(factory.createStartElement(new QName(localName), null, null)); } public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { write(factory.createStartElement(new QName(namespaceURI, localName), null, null)); } public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { write(factory.createStartElement(new QName(namespaceURI, localName, prefix), null, null)); } public void writeAttribute(String localName, String value) throws XMLStreamException { out.add(factory.createAttribute(localName, value)); } public void writeAttribute(String namespaceURI, String localName, String value) throws XMLStreamException { out.add(factory.createAttribute(new QName(namespaceURI, localName), value)); } public void writeAttribute(String prefix, String namespaceURI, String localName, String value) throws XMLStreamException { out.add(factory.createAttribute(prefix, namespaceURI, localName, value)); } public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { write(factory.createNamespace(namespaceURI)); } public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { write(factory.createNamespace(prefix, namespaceURI)); } public void writeCharacters(String text) throws XMLStreamException { out.add(factory.createCharacters(text)); } public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { writeCharacters(new String(text, start, len)); } public void writeCData(String data) throws XMLStreamException { out.add(factory.createCData(data)); } public void writeEntityRef(String name) throws XMLStreamException { out.add(factory.createEntityReference(name, null /* EventDeclaration */)); } public void writeEndElement() throws XMLStreamException { if (depth <= 0) { // erroneous // Let this.out throw the exception: out.add(factory.createEndElement(new QName("unknown"), null)); } else { out.add(stack[depth - 1]); // If that succeeded: --depth; stack[depth] = null; // to enable garbage collection } } public void writeEndDocument() throws XMLStreamException { try { while (depth > 0) { writeEndElement(); } } catch (Exception ignored) { } out.add(factory.createEndDocument()); // If that succeeded: depth = 0; } public void flush() throws XMLStreamException { out.flush(); } public void close() throws XMLStreamException { out.close(); } } src/javanet/staxutils/BaseXMLEventWriter.java0000644000175000017500000004572210213674772020421 0ustar tonytony/* * $Id: BaseXMLEventWriter.java,v 1.9 2005-03-09 22:34:34 cniles Exp $ * * Copyright (c) 2004, Christian Niles, Unit12 * 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 Christian Niles, Unit12, 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 java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.xml.namespace.NamespaceContext; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.*; /** * Base class for {@link XMLEventWriter} implementations. This implemenation * buffers Attribute and Namespace events as specified in the specification, * maintains a stack of NamespaceContext instances based on the events it * receives, and repairs any missing namespaces. Subclasses should implement the * {@link #sendEvent(XMLEvent)} method to receive the processed events and * perform additional processing. * * @author Christian Niles * @version $Revision: 1.9 $ */ public abstract class BaseXMLEventWriter implements XMLEventWriter { /** * XMLEventFactory used to construct XMLEvent instances. */ protected XMLEventFactory factory; /** list of {@link SimpleNamespaceContext}s. */ protected List nsStack = new ArrayList(); /** * Reference to the last StartElement sent. This will be null if no * StartElement has been sent, or after a non Attribute/Namespace * event is received. */ protected StartElement lastStart; /** * LinkedHashMap of attribute events sent surrounding the last * StartElement. By using LinkedHashMap, the attributes will stay in the * order they were defined. */ protected Map attrBuff = new LinkedHashMap(); /** * LinkedHashMap of namespace events sent surrounding the last * StartElement. By using LinkedHashMap, the namespaces will stay in the * order they were defined. */ protected Map nsBuff = new LinkedHashMap(); /** * Whether this writer has been closed or not. */ protected boolean closed; protected BaseXMLEventWriter() { this(null, null); } protected BaseXMLEventWriter(XMLEventFactory eventFactory, NamespaceContext nsCtx) { if (nsCtx != null) { nsStack.add(new SimpleNamespaceContext(nsCtx)); } else { nsStack.add(new SimpleNamespaceContext()); } if (eventFactory != null) { factory = eventFactory; } else { factory = XMLEventFactory.newInstance(); } } public synchronized void flush() throws XMLStreamException { if (!closed) { sendCachedEvents(); } } /** * Sends any events that have been cached in anticipation of further events. * * @throws XMLStreamException If an error occurs sending the events. */ private void sendCachedEvents() throws XMLStreamException { if (lastStart != null) { // A StartElement, and possibly attributes and namespaces, have been // cached. We need to combine them all into a single StartElement // event to send to sendEvent(XMLEvent) // First, construct the new NamespaceContext for the tag SimpleNamespaceContext nsCtx = this.pushNamespaceStack(); // List used to store any defaulted/rewritten namespaces List namespaces = new ArrayList(); // merge namespaces mergeNamespaces(lastStart.getNamespaces(), namespaces); mergeNamespaces(nsBuff.values().iterator(), namespaces); nsBuff.clear(); // merge attributes List attributes = new ArrayList(); mergeAttributes(lastStart.getAttributes(), namespaces, attributes); mergeAttributes(attrBuff.values().iterator(), namespaces, attributes); attrBuff.clear(); // determine the name of the new start tag QName tagName = lastStart.getName(); QName newName = processQName(tagName, namespaces); // construct new element StartElement newStart = factory.createStartElement( newName.getPrefix(), newName.getNamespaceURI(), newName.getLocalPart(), attributes.iterator(), namespaces.iterator(), nsCtx); lastStart = null; sendEvent(newStart); } else { // no start element was cached, but we may have cached some // namespaces and attributes that need to be written. for (Iterator i = nsBuff.values().iterator(); i.hasNext();) { XMLEvent evt = (XMLEvent) i.next(); sendEvent(evt); } nsBuff.clear(); for (Iterator i = attrBuff.values().iterator(); i.hasNext();) { XMLEvent evt = (XMLEvent) i.next(); sendEvent(evt); } attrBuff.clear(); } } /** * Merges a set of {@link Attribute} events, possibly adding additional * {@link Namespace} events if the attribute's prefix isn't bound in the * provided context. * * @param iter An {@link Iterator} of {@link Attribute} events. * @param namespaces A {@link List} to which any new {@link Namespace} * events should be added. * @param attributes A {@link List} to which all {@link Attributes} events * should be merged. */ private void mergeAttributes(Iterator iter, List namespaces, List attributes) { while (iter.hasNext()) { Attribute attr = (Attribute) iter.next(); // check if the attribute QName has the proper mapping QName attrName = attr.getName(); QName newName = processQName(attrName, namespaces); if (!attrName.equals(newName)) { // need to generate a new attribute with the new qualified name Attribute newAttr = factory.createAttribute(newName, attr.getValue()); attributes.add(newAttr); } else { // the attribute is fine attributes.add(attr); } } } /** * Merges a set of {@link Namespaces} events into the provided {@link List}. * * @param iter An {@link Iterator} of {@link Namespace}s to merge. * @param namespaces A {@link List} containing all added {@link Namespace} * events. * @throws XMLStreamException If a conflicting namespace binding is * encountered. */ private void mergeNamespaces(Iterator iter, List namespaces) throws XMLStreamException { // for each namespace, add it to the context, and place it in the list while (iter.hasNext()) { Namespace ns = (Namespace) iter.next(); String prefix = ns.getPrefix(); String nsURI = ns.getNamespaceURI(); SimpleNamespaceContext nsCtx = this.peekNamespaceStack(); if (!nsCtx.isPrefixDeclared(prefix)) { // mapping doesn't exist, so add it to the context/list if (prefix == null || prefix.length() == 0) { nsCtx.setDefaultNamespace(nsURI); } else { nsCtx.setPrefix(prefix, nsURI); } namespaces.add(ns); } else if (!nsCtx.getNamespaceURI(prefix).equals(nsURI)) { throw new XMLStreamException("Prefix already declared: " + ns, ns.getLocation()); } else { // duplicate namespace declaration } } } /** * Processes a {@link QName}, possibly rewriting it to match the current * namespace context. * * @param name The {@link QName} to process. * @param namespaces A {@link List} of {@link Namespace} events to which any * new namespace bindings should be added. * @return The new name, or the name parameter if no changes * were necessary. */ private QName processQName(QName name, List namespaces) { // get current context SimpleNamespaceContext nsCtx = this.peekNamespaceStack(); // get name parts String nsURI = name.getNamespaceURI(); String prefix = name.getPrefix(); if (prefix != null && prefix.length() > 0) { // prefix provided; see if it is okay in current context, otherwise we'll // have to rewrite it String resolvedNS = nsCtx.getNamespaceURI(prefix); if (resolvedNS != null) { if (!resolvedNS.equals(nsURI)) { // prefix is already bound to a different namespace; we have to // find or generate and alternative prefix String newPrefix = nsCtx.getPrefix(nsURI); if (newPrefix == null) { // no existing prefix; need to generate a new prefix newPrefix = generatePrefix(nsURI, nsCtx, namespaces); } // return the newly prefixed name return new QName(nsURI, name.getLocalPart(), newPrefix); } else { // prefix bound to proper namespace; name is already ok } } else if (nsURI != null && nsURI.length() > 0) { // prefix isn't bound yet; bind it and the name is good to go nsCtx.setPrefix(prefix, nsURI); namespaces.add(factory.createNamespace(prefix, nsURI)); } return name; } else if (nsURI != null && nsURI.length() > 0) { // name is namespaced, but has no prefix associated with it. Look for an // existing prefix, or generate one. String newPrefix = nsCtx.getPrefix(nsURI); if (newPrefix == null) { // no existing prefix; need to generate a new prefix newPrefix = generatePrefix(nsURI, nsCtx, namespaces); } // return the newly prefixed name return new QName(nsURI, name.getLocalPart(), newPrefix); } else { // name belongs to no namespace and has no prefix. return name; } } /** * Generates a new namespace prefix for the specified namespace URI that * doesn't collide with any existing prefix. * * @param nsURI The URI for which to generate a prefix. * @param nsCtx The namespace context in which to set the prefix. * @param namespaces A {@link List} of {@link Namespace} events to which the * new prefix will be added. * @return The new prefix. */ private String generatePrefix(String nsURI, SimpleNamespaceContext nsCtx, List namespaces) { String newPrefix; int nsCount = 0; do { newPrefix = "ns" + nsCount; nsCount++; } while (nsCtx.getNamespaceURI(newPrefix) != null); nsCtx.setPrefix(newPrefix, nsURI); namespaces.add(factory.createNamespace(newPrefix, nsURI)); return newPrefix; } public synchronized void close() throws XMLStreamException { if (closed) { return; } try { flush(); } finally { closed = true; } } public synchronized void add(XMLEvent event) throws XMLStreamException { if (closed) { throw new XMLStreamException("Writer has been closed"); } // If the event is an Attribute or Namespace, cache it; otherwise, we // should send any previously cached items switch (event.getEventType()) { case XMLEvent.NAMESPACE : cacheNamespace((Namespace) event); return; case XMLEvent.ATTRIBUTE : cacheAttribute((Attribute) event); return; default : // send any cached events sendCachedEvents(); } if (event.isStartElement()) { // cache the start element in case any following Attribute or // Namespace events occur lastStart = event.asStartElement(); return; } else if (event.isEndElement()) { if (nsStack.isEmpty()) { throw new XMLStreamException("Mismatched end element event: " + event); } SimpleNamespaceContext nsCtx = this.peekNamespaceStack(); EndElement endTag = event.asEndElement(); QName endElemName = endTag.getName(); String prefix = endElemName.getPrefix(); String nsURI = endElemName.getNamespaceURI(); if (nsURI != null && nsURI.length() > 0) { // check that the prefix used in the name is bound to the same // namespace String boundURI = nsCtx.getNamespaceURI(prefix); if (!nsURI.equals(boundURI)) { // not equal! now we must see what prefix it's actually // bound to String newPrefix = nsCtx.getPrefix(nsURI); if (newPrefix != null) { QName newName = new QName(nsURI, endElemName.getLocalPart(), newPrefix); event = factory.createEndElement(newName, endTag.getNamespaces()); } else { // no prefix is bound! report an error throw new XMLStreamException("EndElement namespace (" + nsURI + ") isn't bound [" + endTag + "]"); } } } else { // default namespace String defaultURI = nsCtx.getNamespaceURI(""); if (defaultURI != null && defaultURI.length() > 0) { throw new XMLStreamException("Unable to write " + event + " because default namespace is occluded by " + defaultURI); } // else, namespace matches and can be written directly } // pop the stack popNamespaceStack(); } sendEvent(event); } public void add(XMLEventReader reader) throws XMLStreamException { while (reader.hasNext()) { add(reader.nextEvent()); } } public synchronized String getPrefix(String nsURI) throws XMLStreamException { return getNamespaceContext().getPrefix(nsURI); } public synchronized void setPrefix(String prefix, String nsURI) throws XMLStreamException { peekNamespaceStack().setPrefix(prefix, nsURI); } public synchronized void setDefaultNamespace(String nsURI) throws XMLStreamException { peekNamespaceStack().setDefaultNamespace(nsURI); } public synchronized void setNamespaceContext(NamespaceContext root) throws XMLStreamException { SimpleNamespaceContext parent = (SimpleNamespaceContext) nsStack.get(0); parent.setParent(root); } public synchronized NamespaceContext getNamespaceContext() { return peekNamespaceStack(); } /** * Removes the active {@link SimpleNamespaceContext} from the top of the * stack. * * @return The {@link SimpleNamespaceContext} removed from the namespace * stack. */ protected SimpleNamespaceContext popNamespaceStack() { return (SimpleNamespaceContext) nsStack.remove(nsStack.size() - 1); } /** * Returns the active {@link SimpleNamespaceContext} from the top of the * stack. * * @return The active {@link SimpleNamespaceContext} from the top of the * stack. */ protected SimpleNamespaceContext peekNamespaceStack() { return (SimpleNamespaceContext) nsStack.get(nsStack.size() - 1); } /** * Creates a new {@link SimpleNamespaceContext} and adds it to the top of * the stack. * * @return The new {@link SimpleNamespaceContext}. */ protected SimpleNamespaceContext pushNamespaceStack() { SimpleNamespaceContext nsCtx; SimpleNamespaceContext parent = peekNamespaceStack(); if (parent != null) { nsCtx = new SimpleNamespaceContext(parent); } else { nsCtx = new SimpleNamespaceContext(); } nsStack.add(nsCtx); return nsCtx; } /** * Adds the specified {@link Attribute} to the attribute cache. * * @param attr The attribute to cache. */ protected void cacheAttribute(Attribute attr) { attrBuff.put(attr.getName(), attr); } /** * Adds the provided {@link Namespace} event to the namespace cache. The * current namespace context will not be affected. * * @param ns The namespace to add to the cache. */ protected void cacheNamespace(Namespace ns) { nsBuff.put(ns.getPrefix(), ns); } /** * Called by the methods of this class to write the event to the stream. * * @param event The event to write. * @throws XMLStreamException If an error occurs processing the event. */ protected abstract void sendEvent(XMLEvent event) throws XMLStreamException; }src/javanet/staxutils/ContentHandlerToXMLStreamWriter.java0000644000175000017500000002121210327475450023116 0ustar tonytony/* $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 Ryan.Shoemaker@Sun.COM * @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); } } } src/javanet/staxutils/OutputFactory.java0000644000175000017500000000433210075370466017606 0ustar tonytony/* * $Id: OutputFactory.java,v 1.2 2004-07-15 02:51:33 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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 java.io.Writer; import javanet.staxutils.io.StAXStreamWriter; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; /** * XMLOutputFactory implementation based on stax-utils code base. * * @author Christian Niles * @version $Revision: 1.2 $ */ public class OutputFactory extends BaseXMLOutputFactory { public XMLStreamWriter createXMLStreamWriter(Writer stream) throws XMLStreamException { return new StAXStreamWriter(stream); } }src/javanet/staxutils/StAXSource.java0000644000175000017500000002612010555245152016751 0ustar tonytony/* $Id: StAXSource.java,v 1.5 2007-01-22 23:36:09 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 javanet.staxutils.helpers.XMLFilterImplEx; import org.xml.sax.*; import org.xml.sax.ext.LexicalHandler; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.transform.sax.SAXSource; /** * A JAXP {@link javax.xml.transform.Source} implementation that wraps * the specified {@link javax.xml.stream.XMLStreamReader} or * {@link javax.xml.stream.XMLEventReader} for use by applications that * expext a {@link javax.xml.transform.Source}. * *

* The fact that StAXSource derives from SAXSource is an implementation * detail. Thus in general applications are strongly discouraged from * accessing methods defined on SAXSource. In particular: * *

* *

* Example: * *

 * // create a StAXSource
 * XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new FileReader(args[0]));
 * Source staxSource = new StAXSource(reader);
 *
 * // createa StreamResult
 * Result streamResult = new StreamResult(System.out);
 *
 * // run the transform
 * TransformerFactory.newInstance().newTransformer().transform(staxSource, streamResult);
 * 
* * @author Ryan.Shoemaker@Sun.COM * @version 1.0 */ public class StAXSource extends SAXSource { // StAX to SAX converter that will read from StAX and produce SAX // this object will be wrapped by the XMLReader exposed to the client private final StAXReaderToContentHandler reader; // SAX allows ContentHandler to be changed during the parsing, // but JAXB doesn't. So this repeater will sit between those // two components. private XMLFilterImplEx repeater = new XMLFilterImplEx(); // this object will pretend as an XMLReader. // no matter what parameter is specified to the parse method, // it will just read from the StAX reader. private final XMLReader pseudoParser = new XMLReader() { public boolean getFeature(String name) throws SAXNotRecognizedException { if ("http://xml.org/sax/features/namespaces".equals(name)) { return true; } else if ("http://xml.org/sax/features/namespace-prefixes".equals(name)) { return repeater.getNamespacePrefixes(); } else if ("http://xml.org/sax/features/external-general-entities".equals(name)) { return true; } else if ("http://xml.org/sax/features/external-parameter-entities".equals(name)) { return true; } throw new SAXNotRecognizedException(name); } public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException { if ("http://xml.org/sax/features/namespaces".equals(name)) { // Presently we only support namespaces==true. [Issue 9] if (!value) { throw new SAXNotSupportedException(name); } } else if ("http://xml.org/sax/features/namespace-prefixes".equals(name)) { repeater.setNamespacePrefixes(value); } else if ("http://xml.org/sax/features/external-general-entities".equals(name)) { // Pass over, XOM likes to get this feature } else if ("http://xml.org/sax/features/external-parameter-entities".equals(name)) { // Pass over, XOM likes to get this feature } else { throw new SAXNotRecognizedException(name); } } public Object getProperty(String name) throws SAXNotRecognizedException { if( "http://xml.org/sax/properties/lexical-handler".equals(name) ) { return repeater.getLexicalHandler(); } throw new SAXNotRecognizedException(name); } public void setProperty(String name, Object value) throws SAXNotRecognizedException { if( "http://xml.org/sax/properties/lexical-handler".equals(name) ) { repeater.setLexicalHandler((LexicalHandler)value); } else { throw new SAXNotRecognizedException(name); } } // we will store this value but never use it by ourselves. private EntityResolver entityResolver; public void setEntityResolver(EntityResolver resolver) { this.entityResolver = resolver; } public EntityResolver getEntityResolver() { return entityResolver; } private DTDHandler dtdHandler; public void setDTDHandler(DTDHandler handler) { this.dtdHandler = handler; } public DTDHandler getDTDHandler() { return dtdHandler; } public void setContentHandler(ContentHandler handler) { repeater.setContentHandler(handler); } public ContentHandler getContentHandler() { return repeater.getContentHandler(); } private ErrorHandler errorHandler; public void setErrorHandler(ErrorHandler handler) { this.errorHandler = handler; } public ErrorHandler getErrorHandler() { return errorHandler; } public void parse(InputSource input) throws SAXException { parse(); } public void parse(String systemId) throws SAXException { parse(); } public void parse() throws SAXException { // parses from a StAX reader and generates SAX events which // go through the repeater and are forwarded to the appropriate // component try { reader.bridge(); } catch( XMLStreamException e ) { // wrap it in a SAXException SAXParseException se = new SAXParseException( e.getMessage(), null, null, e.getLocation().getLineNumber(), e.getLocation().getColumnNumber(), e); // if the consumer sets an error handler, it is our responsibility // to notify it. if(errorHandler!=null) errorHandler.fatalError(se); // this is a fatal error. Even if the error handler // returns, we will abort anyway. throw se; } } }; /** * Creates a new {@link javax.xml.transform.Source} for the given * {@link XMLStreamReader}. * * The XMLStreamReader must be pointing at either a * {@link javax.xml.stream.XMLStreamConstants#START_DOCUMENT} or * {@link javax.xml.stream.XMLStreamConstants#START_ELEMENT} event. * * @param reader XMLStreamReader that will be exposed as a Source * @throws IllegalArgumentException iff the reader is null * @throws IllegalStateException iff the reader is not pointing at either a * START_DOCUMENT or START_ELEMENT event */ public StAXSource(XMLStreamReader reader) { if( reader == null ) throw new IllegalArgumentException(); int eventType = reader.getEventType(); if (!(eventType == XMLStreamConstants.START_DOCUMENT) && !(eventType == XMLStreamConstants.START_ELEMENT)) { throw new IllegalStateException(); } this.reader = new XMLStreamReaderToContentHandler( reader, repeater); super.setXMLReader(pseudoParser); // pass a dummy InputSource. We don't care super.setInputSource(new InputSource()); } /** * Creates a new {@link javax.xml.transform.Source} for the given * {@link XMLEventReader}. * * The XMLEventReader must be pointing at either a * {@link javax.xml.stream.XMLStreamConstants#START_DOCUMENT} or * {@link javax.xml.stream.XMLStreamConstants#START_ELEMENT} event. * * @param reader XMLEventReader that will be exposed as a Source * @throws IllegalArgumentException iff the reader is null * @throws IllegalStateException iff the reader is not pointing at either a * START_DOCUEMENT or START_ELEMENT event */ public StAXSource(XMLEventReader reader) { if( reader == null ) throw new IllegalArgumentException(); // TODO: detect IllegalStateException for START_ELEMENT|DOCUMENT // bugid 5046340 - peek not implemented // XMLEvent event = staxEventReader.peek(); this.reader = new XMLEventReaderToContentHandler( reader, repeater); super.setXMLReader(pseudoParser); // pass a dummy InputSource. We don't care super.setInputSource(new InputSource()); } } src/javanet/staxutils/XMLStreamUtils.java0000644000175000017500000006012710073553112017604 0ustar tonytony/* * $Id: XMLStreamUtils.java,v 1.8 2004-07-09 17:30:50 cniles Exp $ * * Copyright (c) 2004, Christian Niles, Unit12 * 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 Christian Niles, Unit12, 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 java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.util.XMLEventConsumer; import javax.xml.transform.Result; import javax.xml.transform.Source; /** * Static utility methods useful when handling XML Streams. * * @author Christian Niles * @version $Revision: 1.8 $ */ public class XMLStreamUtils { private static XMLInputFactory inputFactory = XMLInputFactory.newInstance(); private static XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); private static final String[] EVENT_NAMES = new String[16]; static { EVENT_NAMES[0] = ""; // no event has 0 index EVENT_NAMES[XMLStreamConstants.ATTRIBUTE] = "ATTRIBUTE"; EVENT_NAMES[XMLStreamConstants.CDATA] = "CDATA"; EVENT_NAMES[XMLStreamConstants.CHARACTERS] = "CHARACTERS"; EVENT_NAMES[XMLStreamConstants.COMMENT] = "COMMENT"; EVENT_NAMES[XMLStreamConstants.DTD] = "DTD"; EVENT_NAMES[XMLStreamConstants.END_DOCUMENT] = "END_DOCUMENT"; EVENT_NAMES[XMLStreamConstants.END_ELEMENT] = "END_ELEMENT"; EVENT_NAMES[XMLStreamConstants.ENTITY_DECLARATION] = "ENTITY_DECLARATION"; EVENT_NAMES[XMLStreamConstants.ENTITY_REFERENCE] = "ENTITY_REFERENCE"; EVENT_NAMES[XMLStreamConstants.NAMESPACE] = "NAMESPACE"; EVENT_NAMES[XMLStreamConstants.NOTATION_DECLARATION] = "NOTATION_DECLARATION"; EVENT_NAMES[XMLStreamConstants.PROCESSING_INSTRUCTION] = "PROCESSING_INSTRUCTION"; EVENT_NAMES[XMLStreamConstants.SPACE] = "SPACE"; EVENT_NAMES[XMLStreamConstants.START_DOCUMENT] = "START_DOCUMENT"; EVENT_NAMES[XMLStreamConstants.START_ELEMENT] = "START_ELEMENT"; } /** * Returns the name of the specified stream event constant. * * @param eventType The event constant, such as * {@link XMLStreamConstants#START_DOCUMENT}. * @return The name of the specified event, or "UNKNOWN" if the * constant isn't valid. */ public static final String getEventTypeName(int eventType) { if (eventType > 0 || eventType < EVENT_NAMES.length) { return EVENT_NAMES[eventType]; } else { return "UNKNOWN"; } } /** * Returns the value of the attribute with the given non-qualified name. * * @param reader The xml stream reader * @param name The name of the attribute. * @return The value of the unqualified attribute, or null * if the attribute wasn't present. */ public static final String attributeValue(XMLStreamReader reader, String name) { return reader.getAttributeValue("", name); } /** * Returns the value of the attribute with the given name. * * @param reader The xml stream reader * @param name The name of the attribute. * @return The value of the attribute, or null if the * attribute wasn't present. */ public static final String attributeValue(XMLStreamReader reader, QName name) { return reader.getAttributeValue(name.getNamespaceURI(), name.getLocalPart()); } /** * Skips all events within a single element, including its start and end * tags. The provided reader must be positioned directly in front of a * StartElement event or it will have no effect. After this * method completes, the reader will be positioned before the event * following the end tag (the end tag will have been read). * * @param reader The event stream to read. * @throws XMLStreamException If an error occurs reading events. */ public static final void skipElement(XMLEventReader reader) throws XMLStreamException { copyElement(reader, null); } /** * Copies an element and all its content from the provided event reader, to * the provided event consumer. The event reader must be positioned before a * start element event, or this method has no effect. * * @param reader The reader from which to read the events. * @param consumer The destination for read events, or null to * ignore all events. * @throws XMLStreamException If an error occurs reading or writing the * events. */ public static final void copyElement(XMLEventReader reader, XMLEventConsumer consumer) throws XMLStreamException { if (!reader.hasNext()) return; XMLEvent event = reader.peek(); if (!event.isStartElement()) return; int depth = 0; do { XMLEvent currEvt = reader.nextEvent(); if (currEvt.isStartElement()) { depth++; } else if (currEvt.isEndElement()) { depth--; } if (consumer != null) { consumer.add(currEvt); } } while (depth > 0 && reader.hasNext()); } /** * Skips all events within a StartElement until the matching * EndElement is reached. This method assumes that the reader * is positioned after the StartElement event, and when the * method completes, the stream will be positioned before the * EndElement event, but it will not consume the end tag. * * @param reader The event stream to read, positioned after the * StartElement * @throws XMLStreamException If an error occurs reading events. */ public static final void skipElementContent(XMLEventReader reader) throws XMLStreamException { copyElementContent(reader, null); } /** * Copies all events within a StartElement until the matching * EndElement is reached. This method assumes that the reader * is positioned after the StartElement event, and when the * method completes, the stream will be positioned before the * EndElement event, but it will not consume the end tag. * * @param reader The event stream to read, positioned after the * StartElement * @param consumer The destination for events read from teh stream, or * null to ignore the events completely. * @throws XMLStreamException If an error occurs reading events. */ public static final void copyElementContent(XMLEventReader reader, XMLEventConsumer consumer) throws XMLStreamException { if (!reader.hasNext()) return; for (int depth = 1; true;) { // peek and see if we're at the end element XMLEvent currEvt = reader.peek(); if (currEvt.isEndElement()) { depth--; if (depth == 0) { break; } } else if (currEvt.isStartElement()) { depth++; } // consume the event currEvt = reader.nextEvent(); if (consumer != null) { consumer.add(currEvt); } } } /** * Skips the complete content of the element at the specified reader's * cursor. The reader's current event type must be START_ELEMENT, otherwise * this method will have no effect. Upon completion, the reader's cursor * will be at the END_ELEMENT event for the skipped element. * * @param reader An XML stream reader currently in the START_ELEMENT event. */ public static final void skipElement(XMLStreamReader reader) throws XMLStreamException { if (reader.isStartElement()) { skipElementContent(reader); } } /** * Skips an element's complete content. This method assumes that the * START_ELEMENT has already be passed, and when it terminates, * the stream will be positioned at the END_ELEMENT. * * @param reader The stream reader to read. * @throws XMLStreamException If an error occurs reading the stream. */ public static final void skipElementContent(XMLStreamReader reader) throws XMLStreamException { int depth = 0; while (depth >= 0) { reader.next(); if (reader.isStartElement()) { depth++; } else if (reader.isEndElement()) { depth--; } } } /** * Static utility method that throws an exception if the supplied reader's * cursor doesn't point to a START_ELEMENT with the given name. * * @param reader The reader to test. * @param name The name of the element to require. * @throws XMLStreamException If the reader state is an element with the * specified name. */ public static final void requireElement(XMLStreamReader reader, QName name) throws XMLStreamException { reader.require(XMLStreamReader.START_ELEMENT, name.getNamespaceURI(), name.getLocalPart()); } /** * Copies the content read from the specified source stream to the provided * result stream. This method is exactly the same as calling * {@link XMLEventWriter#add(XMLEventReader)}, and is provided only for * completeness. * * @param reader The source stream. * @param consumer The destination stream. * @throws XMLStreamException If an error occurs copying the stream * contents. */ public static final void copy(XMLEventReader reader, XMLEventConsumer consumer) throws XMLStreamException { if (consumer instanceof XMLEventWriter) { copy(reader, (XMLEventWriter) consumer); } else { while (reader.hasNext()) { consumer.add(reader.nextEvent()); } } } /** * Copies the content read from the specified source stream to the provided * result stream. This method is exactly the same as calling * {@link XMLEventWriter#add(XMLEventReader)}, and is provided only for * completeness. * * @param reader The source stream. * @param writer The destination stream. * @throws XMLStreamException If an error occurs copying the stream * contents. */ public static final void copy(XMLEventReader reader, XMLEventWriter writer) throws XMLStreamException { writer.add(reader); } /** * Copies the content read from the specified source stream to the provided * result stream. * * @param reader The source stream. * @param writer The destination stream. * @throws XMLStreamException If an error occurs copying the stream * contents. */ public static final void copy(XMLStreamReader reader, XMLStreamWriter writer) throws XMLStreamException { XMLEventReader r = inputFactory.createXMLEventReader(reader); XMLEventWriter w = new XMLStreamEventWriter(writer); try { w.add(r); } finally { // force any cached events to the underlying writer w.flush(); } } /** * Copies the content read from the specified source stream to the provided * result stream. * * @param reader The source stream. * @param writer The destination stream. * @param factory An optional input factory used to create any intermediate * streams. * @throws XMLStreamException If an error occurs copying the stream * contents. */ public static final void copy(XMLStreamReader reader, XMLStreamWriter writer, XMLInputFactory factory) throws XMLStreamException { if (factory == null) { factory = inputFactory; } XMLEventReader r = factory.createXMLEventReader(reader); XMLEventWriter w = new XMLStreamEventWriter(writer); try { w.add(r); } finally { // force any cached events to the underlying writer w.flush(); } } /** * Copies the content read from a TrAX {@link Source} to a StAX * {@link XMLStreamWriter}. * * @param source The content source. * @param writer The destination stream. * @throws XMLStreamException If an error occurs copying the content to the * stream. */ public static final void copy(Source source, XMLStreamWriter writer) throws XMLStreamException { XMLStreamReader reader = inputFactory.createXMLStreamReader(source); copy(reader, writer); } /** * Copies the content read from a TrAX {@link Source} to a StAX * {@link XMLEventWriter}. * * @param source The content source. * @param writer The destination event stream. * @throws XMLStreamException If an error occurs copying the content to the * event stream. */ public static final void copy(Source source, XMLEventWriter writer) throws XMLStreamException { XMLEventReader reader = inputFactory.createXMLEventReader(source); copy(reader, writer); } /** * Copies the content read from a StAX {@link XMLEventReader} to a TrAX * {@link Result}. * * @param reader The source event stream. * @param result The destination {@link Result}. * @throws XMLStreamException If an error occurs copying the content to the * result. */ public static final void copy(XMLEventReader reader, Result result) throws XMLStreamException { XMLEventWriter writer = outputFactory.createXMLEventWriter(result); copy(reader, writer); // force any cached events to the result writer.flush(); } /** * Copies the content read from a StAX {@link XMLStreamReader} to a TrAX * {@link Result}. * * @param reader The source stream. * @param result The destination {@link Result}. * @throws XMLStreamException If an error occurs copying the content to the * result. */ public static final void copy(XMLStreamReader reader, Result result) throws XMLStreamException { XMLStreamWriter writer = outputFactory.createXMLStreamWriter(result); copy(reader, writer); // force any cached content to the result writer.flush(); } /** * Utility method that throws an exception if the provided reader is not * positioned before a StartElement event with the specified tag name. * * @param reader The reader to test. * @param qname The required name of the start-tag. If null, * any start tag is accepted. * @throws XMLStreamException If an error occurs reading from the stream. */ public static final void requireStartElement(XMLEventReader reader, QName qname) throws XMLStreamException { if (reader.hasNext()) { XMLEvent nextEvent = reader.peek(); if (nextEvent.isStartElement()) { if (qname != null) { StartElement start = nextEvent.asStartElement(); QName name = start.getName(); if (!name.equals(qname)) { throw new XMLStreamException( "Encountered unexpected element; expected " + qname + ", but found " + name); } } } else { throw new XMLStreamException( "Encountered unexpected event; expected " + qname + " start-tag, but found event " + nextEvent); } } else { throw new XMLStreamException( "Encountered unexpected end of stream; expected element " + qname); } } /** * Constructs a new StartElement that merges the attributes and namespaces * found in the specified StartElement, with the provided attributes. The * returned StartElement will contain all the attributes and namespaces of * the original, plus those defined in the map. * * @param tag The original StartElement * @param attrs An iterator of Atributes to add to the element. * @return A new StartElement that contains all the original attributes and * namespaces, plus the provided attributes. */ public static StartElement mergeAttributes(StartElement tag, Iterator attrs, XMLEventFactory factory) { // create Attribute map Map attributes = new HashMap(); // iterate through start tag's attributes for (Iterator i = tag.getAttributes(); i.hasNext();) { Attribute attr = (Attribute) i.next(); attributes.put(attr.getName(), attr); } // iterate through new attributes while (attrs.hasNext()) { Attribute attr = (Attribute) attrs.next(); attributes.put(attr.getName(), attr); } factory.setLocation(tag.getLocation()); QName tagName = tag.getName(); return factory.createStartElement(tagName.getPrefix(), tagName.getNamespaceURI(), tagName.getLocalPart(), attributes.values().iterator(), tag.getNamespaces(), tag.getNamespaceContext()); } /** * Reads the text content of an element. The reader should be positioned in * front of a StartElement event, and will be read up to and including the * end element tag. * * @param reader The event stream from which to read the element text. * @param elemName The optional name of the element being read. If this * paramter is non- null then an exception will * be thrown if the element read doesn't have the same name. * @return The text read from the element. * @throws XMLStreamException If an error occurs reading the stream, or if * the read element doesn't match the provided QName. */ public static final String readTextElement(XMLEventReader reader, QName elemName) throws XMLStreamException { if (elemName != null) { requireStartElement(reader, elemName); } // read text String text = reader.getElementText(); // consume the end tag reader.nextEvent(); return text; } /** * Advances the event stream until it encounters a start or end tag, but * does not actaully read the event. * * @param reader The reader to peek. * @return The next StartElement or EndElement event, retrieved using * peek(), or null if the end of the * stream was encountered before any tag event. * @throws XMLStreamException If an error occurs reading the stream. */ public static final XMLEvent nextTag(XMLEventReader reader) throws XMLStreamException { while (reader.hasNext()) { XMLEvent nextEvent = reader.peek(); if (nextEvent.isStartElement() || nextEvent.isEndElement()) { return nextEvent; } else { // eat the event. reader.nextEvent(); } } return null; } /** * Reads the events from the provided event stream until either a start or * end tag is encountered. In the former case, the start tag will be * returned, but if an end tag is encountered, null will be * returned. After returning, the stream will be positioned just before the * returned start element. The start element will not be consumed by this * method. * * @param reader The event stream from which to read. * @return The StartElement read from the stream, or null if * an end tag was found first, or the stream ended before a start * element was found. * @throws XMLStreamException If an error occurs reading the stream. */ public static final StartElement nextElement(XMLEventReader reader) throws XMLStreamException { return nextElement(reader, null); } /** * Reads the events from the provided event stream until either a start or * end tag is encountered. In the former case, the start tag will be * returned if it matches the specified QName, but if it doesn't match, an * end tag is encountered, or the stream ends, null will be * returned. After returning, the stream will be positioned just before the * start element. The start element will not be consumed by this method. * * @param reader The event stream from which to read. * @param name The name of the element to read, or null to * read any start tag. * @return The StartElement read from the stream, or null if * the encountered start tag didn't match the specified QName, an * end tag was found first, or the stream ended before a start * element was found. * @throws XMLStreamException If an error occurs reading the stream. */ public static final StartElement nextElement(XMLEventReader reader, QName name) throws XMLStreamException { while (reader.hasNext()) { XMLEvent nextEvent = reader.peek(); if (nextEvent.isStartElement()) { StartElement start = nextEvent.asStartElement(); if (name == null || start.getName().equals(name)) { return start; } else { break; } } else if (nextEvent.isEndElement()) { break; } else { // consume the event. reader.nextEvent(); } } return null; } }src/javanet/staxutils/ContentHandlerToXMLEventWriter.java0000644000175000017500000002522210327475450022751 0ustar tonytony/* $Id: ContentHandlerToXMLEventWriter.java,v 1.4 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.Location; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Characters; import java.util.HashMap; import java.util.Stack; /** * This is a simple utility class that adapts SAX events into StAX * {@link javax.xml.stream.XMLEventWriter} events, bridging between * the two parser technologies. * * This ContentHandler does not own the XMLEventWriter. Therefore, it will * not close or flush the writer at any point. * * @author Ryan.Shoemaker@Sun.COM * @version 1.0 */ public class ContentHandlerToXMLEventWriter extends DefaultHandler { // SAX events will be sent to this XMLEventWriter private final XMLEventWriter staxWriter; // factory for StAX events private final XMLEventFactory staxEventFactory; // SAX locator private Locator locator = null; // StAX location private Location location = null; // storage for prefix bindings private final Stack prefixBindings; // name to entity decl map // map private final HashMap entityMap; public ContentHandlerToXMLEventWriter(XMLEventWriter staxCore) { this.staxWriter = staxCore; staxEventFactory = XMLEventFactory.newInstance(); prefixBindings = new Stack(); // default of 10 seems reasonable entityMap = new HashMap(); } /* * (non-Javadoc) * * @see org.xml.sax.ContentHandler#endDocument() */ public void endDocument() throws SAXException { try { staxWriter.add(staxEventFactory.createEndDocument()); staxWriter.flush(); } catch (XMLStreamException e) { throw new SAXException(e); } } /* * (non-Javadoc) * * @see org.xml.sax.ContentHandler#startDocument() */ public void startDocument() throws SAXException { try { staxWriter.add(staxEventFactory.createStartDocument()); } 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 { // TODO: is there a way to reuse an event? Characters event = staxEventFactory.createCharacters( new String(ch,start,length)); staxWriter.add(event); } 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. } public void unparsedEntityDecl(String name, String publicId, String systemId, String notationName) throws SAXException { // store unparsed entity decls so we can report them properly in skippedEntity entityMap.put(name, new EntityDeclarationImpl(location, name, publicId, systemId, notationName, null)); } /* * (non-Javadoc) * * @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String) */ public void skippedEntity(String name) throws SAXException { try { // if the entity isn't knows, then pass null through // for the EntityDeclaration staxWriter.add(staxEventFactory.createEntityReference(name, (EntityDeclarationImpl)entityMap.get(name))); } catch (XMLStreamException e) { throw new SAXException(e); } } /* * (non-Javadoc) * * @see org.xml.sax.ContentHandler#setDocumentLocator(org.xml.sax.Locator) */ public void setDocumentLocator(final Locator locator) { this.locator = locator; staxEventFactory.setLocation( new Location() { public int getLineNumber() { return locator.getLineNumber(); } public int getColumnNumber() { return locator.getColumnNumber(); } public int getCharacterOffset() { return -1; } public String getPublicId() { return locator.getPublicId(); } public String getSystemId() { return locator.getSystemId(); } }); } /* * (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.add( staxEventFactory.createProcessingInstruction(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 .add( staxEventFactory.createEndElement( getPrefix(qName), namespaceURI, localName)); } 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.add( staxEventFactory.createStartElement( getPrefix(qName), namespaceURI, localName)); 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 if( prefix == null || "".equals(prefix) || "xmlns".equals(prefix) ) { staxWriter.add(staxEventFactory.createNamespace(uri)); } else { staxWriter.add(staxEventFactory.createNamespace(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.add( staxEventFactory.createAttribute( 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); } } } src/javanet/staxutils/events/0000755000175000017500000000000011542302312015376 5ustar tonytonysrc/javanet/staxutils/events/DTDEvent.java0000644000175000017500000000674010075363666017710 0ustar tonytony/* * $Id: DTDEvent.java,v 1.2 2004-07-15 02:11:02 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.events; import java.util.Collections; import java.util.List; import javax.xml.stream.Location; import javax.xml.stream.events.DTD; /** * DTD event implementation. * * @author Christian Niles * @version $Revision: 1.2 $ */ public class DTDEvent extends AbstractXMLEvent implements DTD { /** * The full DTD declaration. */ protected String declaration; /** * The list of {@link javax.xml.stream.events.EntityDeclaration}s. */ protected List entities; /** * The list of {@link javax.xml.stream.events.NotationDeclaration}s. */ protected List notations; public DTDEvent(String declaration, Location location) { super(location); this.declaration = declaration; // TODO Parse declaration? } public DTDEvent(String declaration, List entities, List notations, Location location) { super(location); this.declaration = declaration; this.entities = (entities == null ? Collections.EMPTY_LIST : entities); this.notations = (notations == null ? Collections.EMPTY_LIST : notations); } /** Copy constructor. */ public DTDEvent(DTD that) { super(that); this.declaration = that.getDocumentTypeDeclaration(); this.entities = that.getEntities(); this.notations = that.getNotations(); } /** * Returns {@link #DTD}. */ public int getEventType() { return DTD; } public String getDocumentTypeDeclaration() { return declaration; } public List getEntities() { return entities; } public List getNotations() { return notations; } public Object getProcessedDTD() { return null; } }src/javanet/staxutils/events/AbstractCharactersEvent.java0000644000175000017500000000633510075363666023040 0ustar tonytony/* * $Id: AbstractCharactersEvent.java,v 1.3 2004-07-15 02:11:02 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.events; import javax.xml.namespace.QName; import javax.xml.stream.Location; import javax.xml.stream.events.Characters; /** * Abstract base class for various {@link Characters} implementations. * * @author Christian Niles * @version $Revision: 1.3 $ */ public abstract class AbstractCharactersEvent extends AbstractXMLEvent implements Characters { /** Character content. */ protected String data; public AbstractCharactersEvent(String data) { this.data = data; } public AbstractCharactersEvent(String data, Location location) { super(location); this.data = data; } public AbstractCharactersEvent(String data, Location location, QName schemaType) { super(location, schemaType); this.data = data; } public AbstractCharactersEvent(Characters that) { super(that); this.data = that.getData(); } public String getData() { return data; } public boolean isCharacters() { return true; } public boolean isWhiteSpace() { String data = getData(); for (int i = 0, s = data.length(); i < s; i++) { switch (data.charAt(i)) { case ' ': case '\n': case '\t': case '\r': continue; default: return false; } } return true; } }src/javanet/staxutils/events/ProcessingInstructionEvent.java0000644000175000017500000000566510075363666023660 0ustar tonytony/* * $Id: ProcessingInstructionEvent.java,v 1.2 2004-07-15 02:11:02 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.events; import javax.xml.stream.Location; import javax.xml.stream.events.ProcessingInstruction; /** * {@link ProcessingInstruction} event implementation. * * @author Christian Niles * @version $Revision: 1.2 $ */ public class ProcessingInstructionEvent extends AbstractXMLEvent implements ProcessingInstruction { /** The PI target. */ protected String target; /** The instruction data. */ protected String data; public ProcessingInstructionEvent(String target, String data) { this.target = target; this.data = data; } public ProcessingInstructionEvent(String target, String data, Location location) { super(location); this.target = target; this.data = data; } public ProcessingInstructionEvent(ProcessingInstruction that) { super(that); this.target = that.getTarget(); this.data = that.getData(); } /** * Returns {@link #PROCESSING_INSTRUCTION}. */ public int getEventType() { return PROCESSING_INSTRUCTION; } public String getTarget() { return this.target; } public String getData() { return this.data; } }src/javanet/staxutils/events/BaseXMLEventAllocator.java0000644000175000017500000001231410072357654022360 0ustar tonytony/* * $Id: BaseXMLEventAllocator.java,v 1.1 2004-07-05 23:09:31 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.events; import javax.xml.namespace.NamespaceContext; import javax.xml.stream.Location; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.events.*; import javax.xml.stream.util.XMLEventAllocator; import javax.xml.stream.util.XMLEventConsumer; /** * Abstract base class for {@link XMLEventAllocator} implementations. * * @author Christian Niles * @version $Revision: 1.1 $ */ public abstract class BaseXMLEventAllocator implements XMLEventAllocator { public void allocate(XMLStreamReader reader, XMLEventConsumer consumer) throws XMLStreamException { consumer.add(allocate(reader)); } /** * Delegates allocation to the appropriate allocateXXX method. */ public XMLEvent allocate(XMLStreamReader reader) throws XMLStreamException { int eventType = reader.getEventType(); switch (eventType) { case XMLEvent.START_ELEMENT : return allocateStartElement(reader); case XMLEvent.END_ELEMENT : return allocateEndElement(reader); case XMLEvent.CHARACTERS : return allocateCharacters(reader); case XMLEvent.CDATA : return allocateCData(reader); case XMLEvent.SPACE : return allocateIgnorableSpace(reader); case XMLEvent.COMMENT : return allocateComment(reader); case XMLEvent.DTD : return allocateDTD(reader); case XMLEvent.ENTITY_REFERENCE : return allocateEntityReference(reader); case XMLEvent.PROCESSING_INSTRUCTION : return allocateProcessingInstruction(reader); case XMLEvent.START_DOCUMENT : return allocateStartDocument(reader); case XMLEvent.END_DOCUMENT : return allocateEndDocument(reader); default : throw new XMLStreamException("Unexpected reader state: " + eventType); } } public abstract StartElement allocateStartElement(XMLStreamReader reader) throws XMLStreamException; public abstract EndElement allocateEndElement(XMLStreamReader reader) throws XMLStreamException; public abstract Characters allocateCharacters(XMLStreamReader reader) throws XMLStreamException; public abstract Characters allocateCData(XMLStreamReader reader) throws XMLStreamException; public abstract Characters allocateIgnorableSpace(XMLStreamReader reader) throws XMLStreamException; public abstract EntityReference allocateEntityReference( XMLStreamReader reader) throws XMLStreamException; public abstract Comment allocateComment(XMLStreamReader reader) throws XMLStreamException; public abstract DTD allocateDTD(XMLStreamReader reader) throws XMLStreamException; public abstract StartDocument allocateStartDocument(XMLStreamReader reader) throws XMLStreamException; public abstract EndDocument allocateEndDocument(XMLStreamReader reader) throws XMLStreamException; public abstract ProcessingInstruction allocateProcessingInstruction( XMLStreamReader reader) throws XMLStreamException; public abstract NamespaceContext createStableNamespaceContext( XMLStreamReader reader); public abstract Location createStableLocation(XMLStreamReader reader); }src/javanet/staxutils/events/IgnorableSpaceEvent.java0000644000175000017500000000521410072357712022136 0ustar tonytony/* * $Id: IgnorableSpaceEvent.java,v 1.1 2004-07-05 23:10:00 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.events; import javax.xml.namespace.QName; import javax.xml.stream.Location; import javax.xml.stream.events.Characters; /** * Ignorable Characters event implementation. * * @author Christian Niles * @version $Revision: 1.1 $ */ public class IgnorableSpaceEvent extends AbstractCharactersEvent { public IgnorableSpaceEvent(String data) { super(data); } public IgnorableSpaceEvent(String data, Location location) { super(data, location); } public IgnorableSpaceEvent(String data, Location location, QName schemaType) { super(data, location, schemaType); } public IgnorableSpaceEvent(Characters that) { super(that); } /** Returns {@link #SPACE}. */ public int getEventType() { return SPACE; } public boolean isCData() { return false; } public boolean isIgnorableWhiteSpace() { return true; } }src/javanet/staxutils/events/CDataEvent.java0000644000175000017500000000512210072357712020232 0ustar tonytony/* * $Id: CDataEvent.java,v 1.1 2004-07-05 23:09:56 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.events; import javax.xml.namespace.QName; import javax.xml.stream.Location; import javax.xml.stream.events.Characters; /** * CData Characters event implementation. * * @author Christian Niles * @version $Revision: 1.1 $ */ public class CDataEvent extends AbstractCharactersEvent { public CDataEvent(String data) { super(data); } public CDataEvent(String data, Location location) { super(data, location); } public CDataEvent(String data, Location location, QName schemaType) { super(data, location, schemaType); } public CDataEvent(Characters that) { super(that); } public boolean isCData() { return true; } /** Returns {@link #CDATA}. */ public int getEventType() { return CDATA; } public boolean isIgnorableWhiteSpace() { return false; } }src/javanet/staxutils/events/NamespaceEvent.java0000644000175000017500000000604410075363666021166 0ustar tonytony/* * $Id: NamespaceEvent.java,v 1.3 2004-07-15 02:11:02 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.events; import javax.xml.XMLConstants; import javax.xml.namespace.QName; import javax.xml.stream.Location; import javax.xml.stream.events.Namespace; /** * {@link Namespace} event implementation. * * @author Christian Niles * @version $Revision: 1.3 $ */ public class NamespaceEvent extends AttributeEvent implements Namespace { public static final QName DEFAULT_NS_DECL = new QName( XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE); public NamespaceEvent(String prefix, String nsURI) { this(prefix, nsURI, null); } public NamespaceEvent(String prefix, String nsURI, Location location) { super(prefix != null ? new QName(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, prefix, XMLConstants.XMLNS_ATTRIBUTE) : DEFAULT_NS_DECL, nsURI, location); } /** Returns {@link #NAMESPACE}. */ public int getEventType() { return NAMESPACE; } public String getNamespaceURI() { return getValue(); } public String getPrefix() { String prefix = getName().getLocalPart(); if (!"xmlns".equals(prefix)) { return prefix; } else { return ""; } } public boolean isDefaultNamespaceDeclaration() { return "".equals(getPrefix()); } }src/javanet/staxutils/events/StartElementEvent.java0000644000175000017500000003041310075363666021676 0ustar tonytony/* * $Id: StartElementEvent.java,v 1.5 2004-07-15 02:11:01 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.events; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.xml.namespace.NamespaceContext; import javax.xml.namespace.QName; import javax.xml.stream.Location; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.Namespace; import javax.xml.stream.events.StartElement; import javanet.staxutils.NamespaceContextAdapter; import javanet.staxutils.StaticNamespaceContext; /** * {@link StartElement} event implementation. This event will coalesce its namespaces * into an internal {@link NamespaceContext}, available via * {@link #getNamespaceContext()}. It will also create any implicit namespaces * necessary to satisfy the element's name and those of its attributes. * * @author Christian Niles * @version $Revision: 1.5 $ */ public class StartElementEvent extends AbstractXMLEvent implements StartElement { /** The qualified element name. */ protected QName name; /** The element attributes. */ protected Map attributes; /** The element namespaces. */ protected Map namespaces; /** The namespace context. */ protected NamespaceContext namespaceCtx; public StartElementEvent(QName name, NamespaceContext namespaceCtx, Location location) { super(location); this.name = name; this.namespaceCtx = new StartElementContext(namespaceCtx); } public StartElementEvent(QName name, Iterator attributes, Iterator namespaces, NamespaceContext namespaceCtx, Location location, QName schemaType) { super(location, schemaType); this.namespaceCtx = new StartElementContext(namespaceCtx); mergeNamespaces(namespaces); mergeAttributes(attributes); QName newName = processQName(name); this.name = (newName == null ? name : newName); } public StartElementEvent(StartElement that) { this(that.getName(), that.getAttributes(), that.getNamespaces(), that.getNamespaceContext(), that.getLocation(), that.getSchemaType()); } /** Returns {@link #START_ELEMENT}. */ public int getEventType() { return START_ELEMENT; } public QName getName() { return name; } public Attribute getAttributeByName(QName name) { if (attributes != null) { return (Attribute) attributes.get(name); } else { return null; } } public Iterator getAttributes() { if (attributes != null) { return attributes.values().iterator(); } else { return Collections.EMPTY_LIST.iterator(); } } public NamespaceContext getNamespaceContext() { return namespaceCtx; } public Iterator getNamespaces() { if (namespaces != null) { return namespaces.values().iterator(); } else { return Collections.EMPTY_LIST.iterator(); } } public String getNamespaceURI(String prefix) { return getNamespaceContext().getNamespaceURI(prefix); } /** * Performs the task of adding {@link Attribute}s into the internal * {@link #attributes} map. Along the way, it will also create the necessary * {@link Namespace} events to satisfy attribute namespaces. * * @param iter An iterator over a set of {@link Attributes}. */ private void mergeAttributes(Iterator iter) { if (iter == null) { return; } while (iter.hasNext()) { Attribute attr = (Attribute) iter.next(); if (attributes == null) { attributes = new HashMap(); } // check if the attribute QName has the proper mapping QName attrName = attr.getName(); QName newName = processQName(attrName); if (newName != null) { // need to generate a new attribute with the new qualified name Attribute newAttr = new AttributeEvent(newName, null, attr); attributes.put(newName, newAttr); } else { // the attribute is fine attributes.put(attrName, attr); } } } /** * Performs the task of adding {@link Namespace}s into the internal * {@link #namespaces} map. * * @param iter An iterator over a set of {@link Namespaces}. */ private void mergeNamespaces(Iterator iter) { if (iter == null) { return; } // for each namespace, add it to the context, and place it in the list while (iter.hasNext()) { Namespace ns = (Namespace) iter.next(); String prefix = ns.getPrefix(); if (namespaces == null) { namespaces = new HashMap(); } if (!namespaces.containsKey(prefix)) { namespaces.put(prefix, ns); } } } /** * Processes a {@link QName}, possibly rewriting it to match the current * namespace context. If necessary, a new {@link Namespace} will be added to * support the name's prefix. * * @param name The {@link QName} to process. * @return The new name, or null if no changes were necessary. */ private QName processQName(QName name) { String nsURI = name.getNamespaceURI(); String prefix = name.getPrefix(); if (nsURI == null || nsURI.length() == 0) { // name belongs to no namespace. This can only be okay if the name is // an attribute name, or the default namespace hasn't been overridden. // either way, no prefix should be allowed on the name, so the best we // can do is rewrite the name to make sure no prefix is present // clear any prefix from the name if (prefix != null && prefix.length() > 0) { return new QName(name.getLocalPart()); } else { return name; } } // namespace uri is non-null after this point String resolvedNS = namespaceCtx.getNamespaceURI(prefix); if (resolvedNS == null) { // if the prefix is not empty, then we should default the prefix if (prefix != null && prefix.length() > 0) { if (namespaces == null) { namespaces = new HashMap(); } namespaces.put(prefix, new NamespaceEvent(prefix, nsURI)); } return null; } else if (!resolvedNS.equals(nsURI)) { // The prefix is bound to a different namespace, so we'll have to // search for existing prefixes bound to the namespace uri, or // generate a new namespace binding. String newPrefix = namespaceCtx.getPrefix(nsURI); if (newPrefix == null) { // no existing prefix; need to generate a new prefix newPrefix = generatePrefix(nsURI); } // return the newly prefixed name return new QName(nsURI, name.getLocalPart(), newPrefix); } else { // prefix has already been bound to the namespace; nothing to do return null; } } /** * Generates a new namespace prefix for the specified namespace URI that * doesn't collide with any existing prefix. * * @param nsURI The URI for which to generate a prefix. * @return The new prefix. */ private String generatePrefix(String nsURI) { String newPrefix; int nsCount = 0; do { newPrefix = "ns" + nsCount; nsCount++; } while (namespaceCtx.getNamespaceURI(newPrefix) != null); if (namespaces == null) { namespaces = new HashMap(); } namespaces.put(newPrefix, new NamespaceEvent(newPrefix, nsURI)); return newPrefix; } /** * Adapts another {@link NamespaceContext} to expose this tag's declared * namespaces. * * @author Christian Niles * @version $Revision: 1.5 $ */ private final class StartElementContext extends NamespaceContextAdapter implements StaticNamespaceContext { public StartElementContext(NamespaceContext namespaceCtx) { super(namespaceCtx); } public String getNamespaceURI(String prefix) { if (namespaces != null && namespaces.containsKey(prefix)) { Namespace namespace = (Namespace) namespaces.get(prefix); return namespace.getNamespaceURI(); } else { return super.getNamespaceURI(prefix); } } public String getPrefix(String nsURI) { for (Iterator i = getNamespaces(); i.hasNext();) { Namespace ns = (Namespace) i.next(); if (ns.getNamespaceURI().equals(nsURI)) { return ns.getPrefix(); } } return super.getPrefix(nsURI); } public Iterator getPrefixes(String nsURI) { // lazily-loaded set to store found prefixes List prefixes = null; // add our prefixes first if (namespaces != null) { for (Iterator i = namespaces.values().iterator(); i.hasNext();) { Namespace ns = (Namespace) i.next(); if (ns.getNamespaceURI().equals(nsURI)) { if (prefixes == null) { prefixes = new ArrayList(); } String prefix = ns.getPrefix(); prefixes.add(prefix); } } } // copy parent prefixes that aren't redefined by this context Iterator parentPrefixes = super.getPrefixes(nsURI); while (parentPrefixes.hasNext()) { String prefix = (String) parentPrefixes.next(); // only add the prefix if we haven't redefined it if (namespaces != null && !namespaces.containsKey(prefix)) { if (prefixes == null) { prefixes = new ArrayList(); } prefixes.add(prefix); } } return prefixes == null ? Collections.EMPTY_LIST.iterator() : prefixes.iterator(); } } }src/javanet/staxutils/events/EventAllocator.java0000644000175000017500000002240210072357712021176 0ustar tonytony/* * $Id: EventAllocator.java,v 1.1 2004-07-05 23:10:00 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.events; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.xml.namespace.NamespaceContext; import javax.xml.namespace.QName; import javax.xml.stream.Location; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.Characters; import javax.xml.stream.events.Comment; import javax.xml.stream.events.DTD; import javax.xml.stream.events.EndDocument; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.EntityDeclaration; import javax.xml.stream.events.EntityReference; import javax.xml.stream.events.Namespace; import javax.xml.stream.events.ProcessingInstruction; import javax.xml.stream.events.StartDocument; import javax.xml.stream.events.StartElement; import javax.xml.stream.util.XMLEventAllocator; /** * Allocates events within this package. * * @author Christian Niles * @version $Revision: 1.1 $ */ public class EventAllocator extends BaseXMLEventAllocator { public XMLEventAllocator newInstance() { return new EventAllocator(); } public StartElement allocateStartElement(XMLStreamReader reader) throws XMLStreamException { Location location = createStableLocation(reader); QName name = reader.getName(); List attributes = allocateAttributes(location, reader); List namespaces = allocateNamespaces(location, reader); NamespaceContext nsCtx = createStableNamespaceContext(reader); QName schemaType = determineSchemaType(reader); return new StartElementEvent(name, attributes.iterator(), namespaces.iterator(), nsCtx, location, schemaType); } public EndElement allocateEndElement(XMLStreamReader reader) throws XMLStreamException { Location location = createStableLocation(reader); QName name = reader.getName(); List namespaces = allocateNamespaces(location, reader); QName schemaType = determineSchemaType(reader); return new EndElementEvent(name, namespaces.iterator(), location, schemaType); } public List allocateAttributes(Location location, XMLStreamReader reader) throws XMLStreamException { List attributes = null; for (int i = 0, s = reader.getAttributeCount(); i < s; i++) { QName name = reader.getAttributeName(i); String value = reader.getAttributeValue(i); String dtdType = reader.getAttributeType(i); boolean specified = reader.isAttributeSpecified(i); QName schemaType = determineAttributeSchemaType(reader, i); Attribute attr = new AttributeEvent(name, value, specified, dtdType, location, schemaType); if (attributes == null) { attributes = new ArrayList(); } attributes.add(attr); } return (attributes != null) ? attributes : Collections.EMPTY_LIST; } public List allocateNamespaces(Location location, XMLStreamReader reader) throws XMLStreamException { List namespaces = null; for (int i = 0, s = reader.getNamespaceCount(); i < s; i++) { String prefix = reader.getNamespacePrefix(i); String nsURI = reader.getNamespaceURI(i); Namespace ns = new NamespaceEvent(prefix, nsURI, location); if (namespaces == null) { namespaces = new ArrayList(); } namespaces.add(ns); } return (namespaces != null) ? namespaces : Collections.EMPTY_LIST; } public Characters allocateCData(XMLStreamReader reader) throws XMLStreamException { Location location = createStableLocation(reader); String text = reader.getText(); QName schemaType = determineSchemaType(reader); return new CDataEvent(text, location, schemaType); } public Characters allocateCharacters(XMLStreamReader reader) throws XMLStreamException { Location location = createStableLocation(reader); String text = reader.getText(); QName schemaType = determineSchemaType(reader); return new CharactersEvent(text, location, schemaType); } public Characters allocateIgnorableSpace(XMLStreamReader reader) throws XMLStreamException { Location location = createStableLocation(reader); String text = reader.getText(); QName schemaType = determineSchemaType(reader); return new IgnorableSpaceEvent(text, location, schemaType); } public Comment allocateComment(XMLStreamReader reader) throws XMLStreamException { Location location = createStableLocation(reader); String text = reader.getText(); return new CommentEvent(text, location); } public DTD allocateDTD(XMLStreamReader reader) throws XMLStreamException { Location location = createStableLocation(reader); List entities = (List) reader.getProperty("javax.xml.stream.entities"); List notations = (List) reader.getProperty("javax.xml.stream.notations"); String text = reader.getText(); return new DTDEvent(text, entities, notations, location); } public StartDocument allocateStartDocument(XMLStreamReader reader) throws XMLStreamException { Location location = createStableLocation(reader); String encoding = reader.getCharacterEncodingScheme(); String version = reader.getVersion(); Boolean standalone = reader.standaloneSet() ? Boolean.valueOf(reader.isStandalone()) : null; QName schemaType = determineSchemaType(reader); return new StartDocumentEvent(encoding, standalone, version, location, schemaType); } public EndDocument allocateEndDocument(XMLStreamReader reader) throws XMLStreamException { Location location = createStableLocation(reader); QName schemaType = determineSchemaType(reader); return new EndDocumentEvent(location, schemaType); } public EntityReference allocateEntityReference(XMLStreamReader reader) throws XMLStreamException { Location location = createStableLocation(reader); String name = reader.getLocalName(); EntityDeclaration decl = determineEntityDeclaration(name, reader); return new EntityReferenceEvent(name, decl, location); } public ProcessingInstruction allocateProcessingInstruction( XMLStreamReader reader) throws XMLStreamException { Location location = createStableLocation(reader); String target = reader.getPITarget(); String data = reader.getPIData(); return new ProcessingInstructionEvent(target, data, location); } public QName determineSchemaType(XMLStreamReader reader) { // TODO look for xsi:type? return null; } public QName determineAttributeSchemaType(XMLStreamReader reader, int index) { return null; } public EntityDeclaration determineEntityDeclaration(String name, XMLStreamReader reader) { return new EntityDeclarationEvent(name, reader.getText(), null); } public Location createStableLocation(XMLStreamReader reader) { // FIXME assume location is already stable? return reader.getLocation(); } public NamespaceContext createStableNamespaceContext(XMLStreamReader reader) { // FIXME assume context is already stable return reader.getNamespaceContext(); } }src/javanet/staxutils/events/CharactersEvent.java0000644000175000017500000000520210072357712021334 0ustar tonytony/* * $Id: CharactersEvent.java,v 1.1 2004-07-05 23:09:56 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.events; import javax.xml.namespace.QName; import javax.xml.stream.Location; import javax.xml.stream.events.Characters; /** * Non-ignorable Characters event implementation. * * @author Christian Niles * @version $Revision: 1.1 $ */ public class CharactersEvent extends AbstractCharactersEvent { public CharactersEvent(String data) { super(data); } public CharactersEvent(String data, Location location) { super(data, location); } public CharactersEvent(String data, Location location, QName schemaType) { super(data, location, schemaType); } public CharactersEvent(Characters that) { super(that); } public boolean isCData() { return false; } public boolean isIgnorableWhiteSpace() { return false; } /** Returns {@link #CHARACTERS}. */ public int getEventType() { return CHARACTERS; } }src/javanet/staxutils/events/AttributeEvent.java0000644000175000017500000001447210075363666021241 0ustar tonytony/* * $Id: AttributeEvent.java,v 1.3 2004-07-15 02:11:01 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.events; import javax.xml.namespace.QName; import javax.xml.stream.Location; import javax.xml.stream.events.Attribute; /** * {@link Attribute} event implementation. * * @author Christian Niles * @version $Revision: 1.3 $ */ public class AttributeEvent extends AbstractXMLEvent implements Attribute { /** * Whether the attribute was specified in the document. Defaults to * true. */ private boolean specified = true; /** The qualified attribute name. */ private QName name; /** The normalized attribute value. */ private String value; /** Type of attribute as specified in the DTD. Defaults to CDATA. */ private String dtdType = "CDATA"; /** * Constructs an AttributeEvent with the specified name and value. * * @param name The qualified attribute name. * @param value The attribute value. */ public AttributeEvent(QName name, String value) { this.name = name; this.value = value; } /** * Constructs a new AttributeEvent. * * @param name The qualified attribute name. * @param value The attribute value. * @param specified Whether the attribute was specified in the document * (truefalse). */ public AttributeEvent(QName name, String value, boolean specified) { this.name = name; this.value = value; this.specified = specified; } /** * Constructs a new AttributeEvent. * * @param name The qualified attribute name. * @param value The attribute value. * @param location The {@link Location} of the attribute. */ public AttributeEvent(QName name, String value, Location location) { super(location); this.name = name; this.value = value; } /** * Constructs a new AttributeEvent. * * @param name The qualified attribute name. * @param value The attribute value. * @param location The {@link Location} of the attribute. * @param schemaType The attribute type as specified in the schema. */ public AttributeEvent(QName name, String value, Location location, QName schemaType) { super(location, schemaType); this.name = name; this.value = value; } /** * Constructs a new AttributeEvent. * * @param name The qualified attribute name. * @param value The attribute value. * @param specified Whether the attribute was specified in the document * (truefalse). * @param location The {@link Location} of the attribute. * @param dtdType The attribute type as specified in the DTD. * @param schemaType The attribute type as specified in the schema. */ public AttributeEvent(QName name, String value, boolean specified, String dtdType, Location location, QName schemaType) { super(location, schemaType); this.name = name; this.value = value; this.specified = specified; this.dtdType = dtdType; } /** * Copy constructor that optionally allows the name and/or value to be changed. * * @param name The new attribute name, or null to use the name from * the provided attribute. * @param value The new attribute value, or null to use the value * from the provided attribute. * @param that The {@link Attribute} event to copy. */ public AttributeEvent(QName name, String value, Attribute that) { super(that); this.specified = that.isSpecified(); this.name = (name == null ? that.getName() : name); this.value = (value == null ? that.getValue() : value); this.dtdType = that.getDTDType(); } /** * Copy constructor. * * @param that The {@link Attribute} event to copy. */ public AttributeEvent(Attribute that) { super(that); this.specified = that.isSpecified(); this.name = that.getName(); this.value = that.getValue(); this.dtdType = that.getDTDType(); } /** Returns {@link #ATTRIBUTE}. */ public int getEventType() { return ATTRIBUTE; } public QName getName() { return name; } public String getValue() { return value; } public boolean isSpecified() { return specified; } public String getDTDType() { return dtdType; } }src/javanet/staxutils/events/AbstractXMLEvent.java0000644000175000017500000001314510075363666021416 0ustar tonytony/* * $Id: AbstractXMLEvent.java,v 1.3 2004-07-15 02:11:02 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.events; import java.io.IOException; import java.io.Serializable; import java.io.StringWriter; import java.io.Writer; import javax.xml.namespace.QName; import javax.xml.stream.Location; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import javax.xml.stream.events.Characters; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import javanet.staxutils.helpers.EventMatcher; import javanet.staxutils.helpers.UnknownLocation; import javanet.staxutils.io.XMLWriterUtils; /** * Abstract base class for {@link XMLEvent} implementations. * * @author Christian Niles * @version $Revision: 1.3 $ */ public abstract class AbstractXMLEvent implements ExtendedXMLEvent, Serializable, Cloneable { /** The event location. */ protected Location location; /** The schema type. */ protected QName schemaType; public AbstractXMLEvent() { } public AbstractXMLEvent(Location location) { this.location = location; } public AbstractXMLEvent(Location location, QName schemaType) { this.location = location; this.schemaType = schemaType; } public AbstractXMLEvent(XMLEvent that) { this.location = that.getLocation(); this.schemaType = that.getSchemaType(); } public Location getLocation() { return (location == null ? UnknownLocation.INSTANCE : location); } public QName getSchemaType() { return schemaType; } public Characters asCharacters() { return (Characters) this; } public EndElement asEndElement() { return (EndElement) this; } public StartElement asStartElement() { return (StartElement) this; } public boolean isAttribute() { return getEventType() == ATTRIBUTE; } public boolean isCharacters() { switch (getEventType()) { case CHARACTERS : case SPACE : case CDATA : return true; default : return false; } } public boolean isEndDocument() { return getEventType() == END_DOCUMENT; } public boolean isEndElement() { return getEventType() == END_ELEMENT; } public boolean isEntityReference() { return getEventType() == ENTITY_REFERENCE; } public boolean isNamespace() { return getEventType() == NAMESPACE; } public boolean isProcessingInstruction() { return getEventType() == PROCESSING_INSTRUCTION; } public boolean isStartDocument() { return getEventType() == START_DOCUMENT; } public boolean isStartElement() { return getEventType() == START_ELEMENT; } public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { // should never happen since we implement Cloneable throw new RuntimeException("Unexpected exception cloning XMLEvent", e); } } public boolean matches(XMLEvent event) { return EventMatcher.eventsMatch(this, event); } public void writeEvent(XMLStreamWriter writer) throws XMLStreamException { XMLWriterUtils.writeEvent(this, writer); } public void writeAsEncodedUnicode(Writer writer) throws XMLStreamException { try { XMLWriterUtils.writeEvent(this, writer); } catch (IOException e) { throw new XMLStreamException(e); } } public String toString() { StringWriter writer = new StringWriter(); try { this.writeAsEncodedUnicode(writer); } catch (XMLStreamException e) { // shouldn't happen? } return writer.toString(); } }src/javanet/staxutils/events/EntityDeclarationEvent.java0000644000175000017500000001063710075363666022717 0ustar tonytony/* * $Id: EntityDeclarationEvent.java,v 1.2 2004-07-15 02:11:01 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.events; import javax.xml.stream.Location; import javax.xml.stream.events.EntityDeclaration; /** * {@link EntityDeclaration} event implementation. * * @author Christian Niles * @version $Revision: 1.2 $ */ public class EntityDeclarationEvent extends AbstractXMLEvent implements EntityDeclaration { /** The entity name. */ protected String name; /** * The replacement text, or null if this isn't an internal entity. */ protected String replacementText; /** The entity base URI, or null if this isn't an external entity */ protected String baseURI; /** The public id, or null if this isn't an external entity */ protected String publicId; /** The system id, or null if this isn't an external entity. */ protected String systemId; /** * The optional notation name. */ protected String notationName; public EntityDeclarationEvent(String name, String replacementText, Location location) { super(location); this.name = name; this.replacementText = replacementText; } public EntityDeclarationEvent(String name, String replacementText, String notationName, Location location) { super(location); this.name = name; this.replacementText = replacementText; this.notationName = notationName; } public EntityDeclarationEvent(String name, String publicId, String systemId, String baseURI, String notationName, Location location) { super(location); this.name = name; this.publicId = publicId; this.systemId = systemId; this.baseURI = baseURI; this.notationName = notationName; } public EntityDeclarationEvent(EntityDeclaration that) { super(that); this.name = that.getName(); this.replacementText = that.getReplacementText(); this.publicId = that.getPublicId(); this.systemId = that.getSystemId(); this.baseURI = that.getBaseURI(); this.notationName = that.getNotationName(); } /** * Returns {@link #ENTITY_DECLARATION}. */ public int getEventType() { return ENTITY_DECLARATION; } public String getBaseURI() { return this.baseURI; } public String getName() { return this.name; } public String getNotationName() { return this.notationName; } public String getPublicId() { return this.publicId; } public String getReplacementText() { return this.replacementText; } public String getSystemId() { return this.systemId; } }src/javanet/staxutils/events/EndDocumentEvent.java0000644000175000017500000000467410075363666021506 0ustar tonytony/* * $Id: EndDocumentEvent.java,v 1.2 2004-07-15 02:11:02 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.events; import javax.xml.namespace.QName; import javax.xml.stream.Location; import javax.xml.stream.events.EndDocument; /** * {@link EndDocument} event implementation. * * @author Christian Niles * @version $Revision: 1.2 $ */ public class EndDocumentEvent extends AbstractXMLEvent implements EndDocument { public EndDocumentEvent() { } public EndDocumentEvent(Location location) { super(location); } public EndDocumentEvent(Location location, QName schemaType) { super(location, schemaType); } public EndDocumentEvent(EndDocument that) { super(that); } /** Returns {@link #END_DOCUMENT}. */ public int getEventType() { return END_DOCUMENT; } }src/javanet/staxutils/events/EventFactory.java0000644000175000017500000001206010072357712020664 0ustar tonytony/* * $Id: EventFactory.java,v 1.1 2004-07-05 23:09:59 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.events; import java.util.Iterator; import javax.xml.namespace.NamespaceContext; import javax.xml.namespace.QName; import javax.xml.stream.Location; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.Characters; import javax.xml.stream.events.Comment; import javax.xml.stream.events.DTD; import javax.xml.stream.events.EndDocument; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.EntityDeclaration; import javax.xml.stream.events.EntityReference; import javax.xml.stream.events.Namespace; import javax.xml.stream.events.ProcessingInstruction; import javax.xml.stream.events.StartDocument; import javax.xml.stream.events.StartElement; /** * Factory for events within this package. * * @author Christian Niles * @version $Revision: 1.1 $ */ public class EventFactory extends BaseXMLEventFactory { public Attribute createAttribute(QName name, String value, Location location, QName schemaType) { return new AttributeEvent(name, value, location, schemaType); } public Characters createCData(String content, Location location, QName schemaType) { return new CDataEvent(content, location, schemaType); } public Characters createCharacters(String content, Location location, QName schemaType) { return new CharactersEvent(content, location, schemaType); } public Comment createComment(String text, Location location) { return new CommentEvent(text, location); } public DTD createDTD(String dtd, Location location) { return new DTDEvent(dtd, location); } public EndDocument createEndDocument(Location location) { return new EndDocumentEvent(location); } public EndElement createEndElement(QName name, Iterator namespaces, Location location, QName schemaType) { return new EndElementEvent(name, namespaces, location, schemaType); } public EntityReference createEntityReference(String name, EntityDeclaration declaration, Location location) { return new EntityReferenceEvent(name, declaration, location); } public Characters createIgnorableSpace(String content, Location location) { return new IgnorableSpaceEvent(content, location); } public Namespace createNamespace(String prefix, String namespaceUri, Location location) { return new NamespaceEvent(prefix, namespaceUri, location); } public ProcessingInstruction createProcessingInstruction(String target, String data, Location location) { return new ProcessingInstructionEvent(target, data, location); } public Characters createSpace(String content, Location location) { return new IgnorableSpaceEvent(content, location); } public StartDocument createStartDocument(String encoding, String version, Boolean standalone, Location location, QName schemaType) { return new StartDocumentEvent(encoding, standalone, version, location, schemaType); } public StartElement createStartElement(QName name, Iterator attributes, Iterator namespaces, NamespaceContext namespaceCtx, Location location, QName schemaType) { return new StartElementEvent(name, attributes, namespaces, namespaceCtx, location, schemaType); } }src/javanet/staxutils/events/EntityReferenceEvent.java0000644000175000017500000000601510075363666022363 0ustar tonytony/* * $Id: EntityReferenceEvent.java,v 1.2 2004-07-15 02:11:02 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.events; import javax.xml.stream.Location; import javax.xml.stream.events.EntityDeclaration; import javax.xml.stream.events.EntityReference; /** * {@link EntityReference} event implementation. * * @author Christian Niles * @version $Revision: 1.2 $ */ public class EntityReferenceEvent extends AbstractXMLEvent implements EntityReference { /** The referenced entity name. */ protected String name; /** The referenced entity declaration. */ protected EntityDeclaration declaration; public EntityReferenceEvent(String name, EntityDeclaration declaration) { this.name = name; this.declaration = declaration; } public EntityReferenceEvent(String name, EntityDeclaration declaration, Location location) { super(location); this.name = name; this.declaration = declaration; } public EntityReferenceEvent(EntityReference that) { super(that); this.name = that.getName(); this.declaration = that.getDeclaration(); } public EntityDeclaration getDeclaration() { return declaration; } public String getName() { return name; } /** Returns {@link #ENTITY_REFERENCE}. */ public int getEventType() { return ENTITY_REFERENCE; } }src/javanet/staxutils/events/BaseXMLEventFactory.java0000644000175000017500000002154610072357654022056 0ustar tonytony/* * $Id: BaseXMLEventFactory.java,v 1.1 2004-07-05 23:09:32 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.events; import java.util.Iterator; import javax.xml.namespace.NamespaceContext; import javax.xml.namespace.QName; import javax.xml.stream.Location; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.Characters; import javax.xml.stream.events.Comment; import javax.xml.stream.events.DTD; import javax.xml.stream.events.EndDocument; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.EntityDeclaration; import javax.xml.stream.events.EntityReference; import javax.xml.stream.events.Namespace; import javax.xml.stream.events.ProcessingInstruction; import javax.xml.stream.events.StartDocument; import javax.xml.stream.events.StartElement; /** * Abstract base class for {@link XMLEventFactory} implementations. This class * makes it easier to implement by coalesing the various forms of each method into * a single creation method, such as * {@link #createAttribute(QName, String, Location, QName)}. * * @author Christian Niles * @version $Revision: 1.1 $ */ public abstract class BaseXMLEventFactory extends XMLEventFactory { /** The current location registered with the factory. */ protected Location location; public void setLocation(Location location) { this.location = location; } public Attribute createAttribute(QName name, String value) { return createAttribute(name, value, location, null); } public Attribute createAttribute(String prefix, String namespaceURI, String localName, String value) { return createAttribute(new QName(namespaceURI, localName, prefix), value, location, null); } public Attribute createAttribute(String localName, String value) { return createAttribute(new QName(localName), value, location, null); } public abstract Attribute createAttribute(QName name, String value, Location location, QName schemaType); public Characters createCData(String content) { return createCData(content, location, null); } public abstract Characters createCData(String content, Location location, QName schemaType); public Characters createCharacters(String content) { return createCharacters(content, location, null); } public abstract Characters createCharacters(String content, Location location, QName schemaType); public Comment createComment(String text) { return createComment(text, location); } public abstract Comment createComment(String text, Location location); public DTD createDTD(String dtd) { return createDTD(dtd, location); } public abstract DTD createDTD(String dtd, Location location); public EndDocument createEndDocument() { return createEndDocument(location); } public abstract EndDocument createEndDocument(Location location); public EndElement createEndElement(QName name, Iterator namespaces) { return createEndElement(name, namespaces, location, null); } public EndElement createEndElement(String prefix, String namespaceUri, String localName, Iterator namespaces) { return createEndElement(new QName(namespaceUri, localName, prefix), namespaces, location, null); } public EndElement createEndElement(String prefix, String namespaceUri, String localName) { return createEndElement(new QName(namespaceUri, localName, prefix), null, location, null); } public abstract EndElement createEndElement(QName name, Iterator namespaces, Location location, QName schemaType); public EntityReference createEntityReference(String name, EntityDeclaration declaration) { return createEntityReference(name, declaration, location); } public abstract EntityReference createEntityReference(String name, EntityDeclaration declaration, Location location); public Characters createIgnorableSpace(String content) { return createIgnorableSpace(content, location); } public abstract Characters createIgnorableSpace(String content, Location location); public Namespace createNamespace(String prefix, String namespaceUri) { return createNamespace(prefix, namespaceUri, location); } public Namespace createNamespace(String namespaceUri) { return createNamespace("", namespaceUri, location); } public abstract Namespace createNamespace(String prefix, String namespaceUri, Location location); public ProcessingInstruction createProcessingInstruction(String target, String data) { return createProcessingInstruction(target, data, location); } public abstract ProcessingInstruction createProcessingInstruction( String target, String data, Location location); public Characters createSpace(String content) { return createSpace(content, location); } public abstract Characters createSpace(String content, Location location); public StartDocument createStartDocument() { return createStartDocument(null, null, null, location, null); } public StartDocument createStartDocument(String encoding, String version, boolean standalone) { return createStartDocument(encoding, version, Boolean.valueOf(standalone), location, null); } public StartDocument createStartDocument(String encoding, String version) { return createStartDocument(encoding, version, null, location, null); } public StartDocument createStartDocument(String encoding) { return createStartDocument(encoding, null, null, location, null); } public abstract StartDocument createStartDocument(String encoding, String version, Boolean standalone, Location location, QName schemaType); public StartElement createStartElement(QName name, Iterator attributes, Iterator namespaces) { return createStartElement(name, attributes, namespaces, null, location, null); } public StartElement createStartElement(String prefix, String namespaceUri, String localName, Iterator attributes, Iterator namespaces, NamespaceContext context) { return createStartElement(new QName(namespaceUri, localName, prefix), attributes, namespaces, context, location, null); } public StartElement createStartElement(String prefix, String namespaceUri, String localName, Iterator attributes, Iterator namespaces) { return createStartElement(new QName(namespaceUri, localName, prefix), attributes, namespaces, null, location, null); } public StartElement createStartElement(String prefix, String namespaceUri, String localName) { return createStartElement(new QName(namespaceUri, localName, prefix), null, null, null, location, null); } public abstract StartElement createStartElement(QName name, Iterator attributes, Iterator namespaces, NamespaceContext namespaceCtx, Location location, QName schemaType); }src/javanet/staxutils/events/StartDocumentEvent.java0000644000175000017500000001207010075363666022062 0ustar tonytony/* * $Id: StartDocumentEvent.java,v 1.2 2004-07-15 02:11:01 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.events; import javax.xml.namespace.QName; import javax.xml.stream.Location; import javax.xml.stream.events.StartDocument; /** * {@link StartDocument} implementation. * * @author Christian Niles * @version $Revision: 1.2 $ */ public class StartDocumentEvent extends AbstractXMLEvent implements StartDocument { /** Default XML version returned by {@link #getVersion()}. */ public static final String DEFAULT_VERSION = "1.0"; /** Default system id returned by {@link #getSystemId()}. */ public static final String DEFAULT_SYSTEM_ID = ""; /** Default encoding returned by {@link #getCharacterEncodingScheme()}. */ public static final String DEFAULT_ENCODING = "UTF-8"; /** The document encoding, or null if none was specified. */ protected String encoding; /** The document standalone value, or null if none was specified. */ protected Boolean standalone; /** The XML version, or null if none was specified. */ protected String version; public StartDocumentEvent() { } public StartDocumentEvent(Location location) { super(location); } public StartDocumentEvent(String encoding, Location location) { super(location); this.encoding = encoding; } public StartDocumentEvent(String encoding, Boolean standalone, String version, Location location) { super(location); this.encoding = encoding; this.standalone = standalone; this.version = version; } public StartDocumentEvent(String encoding, Boolean standalone, String version, Location location, QName schemaType) { super(location, schemaType); this.encoding = encoding; this.standalone = standalone; this.version = version; } /** * Copy constructor. * * @param that The {@link StartDocument} event to copy. */ public StartDocumentEvent(StartDocument that) { super(that); // copy encoding if (that.encodingSet()) { this.encoding = that.getCharacterEncodingScheme(); } // copy standalone if (standaloneSet()) { this.standalone = that.isStandalone() ? Boolean.TRUE : Boolean.FALSE; } this.version = DEFAULT_VERSION.equals(that.getVersion()) ? null : that.getVersion(); } /** Returns {@link #START_DOCUMENT}. */ public int getEventType() { return START_DOCUMENT; } public boolean encodingSet() { return encoding != null; } public String getCharacterEncodingScheme() { return (encoding == null ? DEFAULT_ENCODING : encoding); } public String getSystemId() { Location location = getLocation(); if (location != null) { String systemId = location.getSystemId(); if (systemId != null) { return systemId; } } return DEFAULT_SYSTEM_ID; } public String getVersion() { return (version == null ? DEFAULT_VERSION : version); } public boolean isStandalone() { return (standalone == null ? false : standalone.booleanValue()); } public boolean standaloneSet() { return standalone != null; } }src/javanet/staxutils/events/package.html0000644000175000017500000000063510074545702017676 0ustar tonytony stax-utils Events Package Provides common XMLEvent implementations and related classes. src/javanet/staxutils/events/ExtendedXMLEvent.java0000644000175000017500000000523410072357532021403 0ustar tonytony/* * $Id: ExtendedXMLEvent.java,v 1.1 2004-07-05 23:08:10 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.events; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import javax.xml.stream.events.XMLEvent; /** * Extended {@link XMLEvent} interface that provides additional functionality. * * @author Christian Niles * @version $Revision: 1.1 $ */ public interface ExtendedXMLEvent extends XMLEvent { /** * Determines if this event matches another event, irrespective of document * location. * * @param event The event to match against. * @return true if the two events match, false * otherwise. */ public boolean matches(XMLEvent event); /** * Writes the event to the provided {@link XMLStreamWriter}. * * @param writer The destination stream. * @throws XMLStreamException If an error occurs writing to the destination * stream. */ public void writeEvent(XMLStreamWriter writer) throws XMLStreamException; }src/javanet/staxutils/events/EndElementEvent.java0000644000175000017500000000753310075363666021316 0ustar tonytony/* * $Id: EndElementEvent.java,v 1.3 2004-07-15 02:11:02 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.events; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import javax.xml.namespace.QName; import javax.xml.stream.Location; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.Namespace; /** * {@link EndElement} event implementation. * * @author Christian Niles * @version $Revision: 1.3 $ */ public class EndElementEvent extends AbstractXMLEvent implements EndElement { /** The element name. */ protected QName name; /** A collection of {@link Namespace}s going out of scope. */ protected Collection namespaces; public EndElementEvent(QName name, Iterator namespaces) { this(name, namespaces, null, null); } public EndElementEvent(QName name, Iterator namespaces, Location location) { this(name, namespaces, location, null); } public EndElementEvent(QName name, Iterator namespaces, Location location, QName schemaType) { super(location, schemaType); this.name = name; if (namespaces != null && namespaces.hasNext()) { List nsList = new ArrayList(); do { Namespace ns = (Namespace) namespaces.next(); nsList.add(ns); } while (namespaces.hasNext()); } } public EndElementEvent(EndElement that) { super(that); this.name = that.getName(); Iterator namespaces = that.getNamespaces(); if (namespaces != null && namespaces.hasNext()) { List nsList = new ArrayList(); do { Namespace ns = (Namespace) namespaces.next(); nsList.add(ns); } while (namespaces.hasNext()); } } /** * Returns {@link #END_ELEMENT}. */ public int getEventType() { return END_ELEMENT; } public QName getName() { return name; } public Iterator getNamespaces() { if (namespaces != null) { return namespaces.iterator(); } else { return Collections.EMPTY_LIST.iterator(); } } }src/javanet/staxutils/events/CommentEvent.java0000644000175000017500000000507310075363666020675 0ustar tonytony/* * $Id: CommentEvent.java,v 1.2 2004-07-15 02:11:01 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.events; import javax.xml.stream.Location; import javax.xml.stream.events.Comment; /** * Comment event implementation. * * @author Christian Niles * @version $Revision: 1.2 $ */ public class CommentEvent extends AbstractXMLEvent implements Comment { /** Comment text. */ protected String text; public CommentEvent(String text) { this.text = text; } public CommentEvent(String text, Location location) { super(location); this.text = text; } /** * Copy constructor. * * @param that The comment to copy. */ public CommentEvent(Comment that) { super(that); this.text = that.getText(); } public String getText() { return text; } /** Returns {@link #COMMENT}. */ public int getEventType() { return COMMENT; } }src/javanet/staxutils/events/NotationDeclarationEvent.java0000644000175000017500000000634410075363666023236 0ustar tonytony/* * $Id: NotationDeclarationEvent.java,v 1.2 2004-07-15 02:11:02 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.events; import javax.xml.stream.Location; import javax.xml.stream.events.NotationDeclaration; /** * {@link NotationDeclaration} implementation. * * @author Christian Niles * @version $Revision: 1.2 $ */ public class NotationDeclarationEvent extends AbstractXMLEvent implements NotationDeclaration { /** The notation name. */ protected String name; /** The public id of the notation */ protected String publicId; /** The system id of the notation */ protected String systemId; public NotationDeclarationEvent(String name, String publicId, Location location) { super(location); this.name = name; this.publicId = publicId; } public NotationDeclarationEvent(String name, String publicId, String systemId, Location location) { super(location); this.name = name; this.publicId = publicId; this.systemId = systemId; } public NotationDeclarationEvent(NotationDeclaration that) { super(that); this.name = that.getName(); this.publicId = that.getPublicId(); this.systemId = that.getSystemId(); } /** * Returns {@link #NOTATION_DECLARATION}. */ public int getEventType() { return NOTATION_DECLARATION; } public String getName() { return this.name; } public String getPublicId() { return this.publicId; } public String getSystemId() { return this.systemId; } }src/javanet/staxutils/SimpleLocation.java0000644000175000017500000001215310073255126017671 0ustar tonytony/* * $Id: SimpleLocation.java,v 1.2 2004-07-08 14:29:41 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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 javax.xml.stream.Location; /** * Basic implementation of {@link ExtendedLocation}. * * @author Christian Niles * @version $Revision: 1.2 $ */ public class SimpleLocation implements ExtendedLocation, StaticLocation { /** The nested location. */ private Location nestedLocation; /** The line number; defaults to -1. */ private int lineNumber = -1; /** The character offset; defaults to -1. */ private int characterOffset = -1; /** The column number; defaults to -1. */ private int columnNumber = -1; /** The system ID; defaults to null. */ private String publicId; /** The public ID; defaults to null. */ private String systemId; public SimpleLocation(String publicId, String systemId, int lineNumber, Location nestedLocation) { this.publicId = publicId; this.systemId = systemId; this.lineNumber = lineNumber; this.nestedLocation = nestedLocation; } public SimpleLocation(String publicId, String systemId, int lineNumber, int columnNumber, Location nestedLocation) { this.publicId = publicId; this.systemId = systemId; this.lineNumber = lineNumber; this.columnNumber = columnNumber; this.nestedLocation = nestedLocation; } public SimpleLocation(String publicId, String systemId, int lineNumber, int columnNumber, int characterOffset, Location nestedLocation) { this.publicId = publicId; this.systemId = systemId; this.lineNumber = lineNumber; this.columnNumber = columnNumber; this.characterOffset = characterOffset; this.nestedLocation = nestedLocation; } public SimpleLocation(Location loc) { this.publicId = loc.getPublicId(); this.systemId = loc.getSystemId(); this.lineNumber = loc.getLineNumber(); this.columnNumber = loc.getColumnNumber(); this.characterOffset = loc.getCharacterOffset(); if (loc instanceof ExtendedLocation) { this.nestedLocation = ((ExtendedLocation) loc).getNestedLocation(); } } public int getCharacterOffset() { return this.characterOffset; } public int getColumnNumber() { return this.columnNumber; } public int getLineNumber() { return this.lineNumber; } public String getPublicId() { return this.publicId; } public String getSystemId() { return this.systemId; } public Location getNestedLocation() { return nestedLocation; } public String toString() { StringBuffer buffer = new StringBuffer(); String publicId = getPublicId(); String systemId = getSystemId(); if (publicId != null) { buffer.append(publicId); if (systemId != null) { buffer.append("#").append(systemId); } } else if (systemId != null) { buffer.append(publicId); } buffer.append('['); buffer.append("line=").append(getLineNumber()); buffer.append("column=").append(getColumnNumber()); buffer.append(']'); Location nested = getNestedLocation(); if (nested != null) { buffer.append("->"); buffer.append(nested); } return buffer.toString(); } }src/javanet/staxutils/error/0000755000175000017500000000000011542302310015221 5ustar tonytonysrc/javanet/staxutils/error/IllegalStreamStateException.java0000644000175000017500000000567411535774174023534 0ustar tonytony/* * $Id: IllegalStreamStateException.java,v 1.1 2004-07-12 17:27:21 cniles Exp $ * * Copyright (c) 2004, Christian Niles, Unit12 * 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 Christian Niles, Unit12, 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.error; import javax.xml.stream.Location; /** * {@link IllegalStateException} that includes a StAX {@link Location} identifying * the point where the error occured. * * @author Christian Niles * @version $Revision: 1.1 $ */ public class IllegalStreamStateException extends IllegalStateException { /** The location in the stream where the error occured. */ private Location location; public IllegalStreamStateException() { } public IllegalStreamStateException(Location location) { this.location = location; } public IllegalStreamStateException(String s) { super(s); } public IllegalStreamStateException(String s, Location location) { super(s); this.location = location; } /** * Returns the {@link Location} where the error occured. * * @return The {@link Location} where the error occured. */ public Location getLocation() { return this.location; } /** * Sets the {@link Location} where the error occured. * * @param location The {@link Location} where the error occured. */ public void setLocation(Location location) { this.location = location; } } src/javanet/staxutils/error/package.html0000644000175000017500000000071310074545702017520 0ustar tonytony stax-utils Error Package

Provides useful Exception classes and utilties for error handling and reporting.

src/javanet/staxutils/XMLEventReaderToContentHandler.java0000644000175000017500000003374110365222532022675 0ustar tonytony/* $Id: XMLEventReaderToContentHandler.java,v 1.10 2006-01-23 18:50:02 sandoz 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 java.util.Iterator; import javanet.staxutils.helpers.XMLFilterImplEx; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.Location; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.Characters; import javax.xml.stream.events.Comment; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.Namespace; import javax.xml.stream.events.ProcessingInstruction; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * This is a simple utility class that adapts StAX events from an * {@link javax.xml.stream.XMLEventReader} to SAX events on a * {@link org.xml.sax.ContentHandler}, bridging between the two * parser technologies. * * @author Ryan.Shoemaker@Sun.COM * @version 1.0 */ public class XMLEventReaderToContentHandler implements StAXReaderToContentHandler { // StAX event source private final XMLEventReader staxEventReader; // SAX event sinks private XMLFilterImplEx filter; /** * Construct a new StAX to SAX adapter that will convert a StAX event * stream into a SAX event stream. * * @param staxCore * StAX event source * @param filter * SAX event sink */ public XMLEventReaderToContentHandler(XMLEventReader staxCore, XMLFilterImplEx filter) { staxEventReader = staxCore; this.filter = filter; } /* * @see StAXReaderToContentHandler#bridge() */ public void bridge() throws XMLStreamException { try { // remembers the nest level of elements to know when we are done. int depth=0; XMLEvent event = staxEventReader.peek(); boolean readWhole = false; if(event.isStartDocument()) { readWhole = true; } else if(!event.isStartElement()) throw new IllegalStateException(); // if the parser is on START_DOCUMENT, skip ahead to the first element do { event = staxEventReader.nextEvent(); } while( !event.isStartElement() ); handleStartDocument(event); OUTER: while(true) { // These are all of the events listed in the javadoc for // XMLEvent. // The spec only really describes 11 of them. switch (event.getEventType()) { case XMLStreamConstants.START_ELEMENT : depth++; handleStartElement(event.asStartElement()); break; case XMLStreamConstants.END_ELEMENT : handleEndElement(event.asEndElement()); depth--; if(depth==0) break OUTER; break; case XMLStreamConstants.CHARACTERS : handleCharacters(event.asCharacters()); break; case XMLStreamConstants.ENTITY_REFERENCE : handleEntityReference(); break; case XMLStreamConstants.PROCESSING_INSTRUCTION : handlePI((ProcessingInstruction)event); break; case XMLStreamConstants.COMMENT : handleComment((Comment)event); break; case XMLStreamConstants.DTD : handleDTD(); break; case XMLStreamConstants.ATTRIBUTE : handleAttribute(); break; case XMLStreamConstants.NAMESPACE : handleNamespace(); break; case XMLStreamConstants.CDATA : handleCDATA(); break; case XMLStreamConstants.ENTITY_DECLARATION : handleEntityDecl(); break; case XMLStreamConstants.NOTATION_DECLARATION : handleNotationDecl(); break; case XMLStreamConstants.SPACE : handleSpace(); break; default : throw new InternalError("processing event: " + event); } event=staxEventReader.nextEvent(); } handleEndDocument(); if(readWhole) { // if we started from START_DOCUMENT, read the whole document while(staxEventReader.hasNext()) staxEventReader.nextEvent(); } } catch (SAXException e) { throw new XMLStreamException(e); } } private void handleEndDocument() throws SAXException { filter.endDocument(); } private void handleStartDocument(final XMLEvent event) throws SAXException { final Location location = event.getLocation(); if (location != null) { filter.setDocumentLocator(new Locator() { public int getColumnNumber() { return location.getColumnNumber(); } public int getLineNumber() { return location.getLineNumber(); } public String getPublicId() { return location.getPublicId(); } public String getSystemId() { return location.getSystemId(); } }); } else { filter.setDocumentLocator(new DummyLocator()); } filter.startDocument(); } private void handlePI(ProcessingInstruction event) throws XMLStreamException { try { filter.processingInstruction( event.getTarget(), event.getData()); } catch (SAXException e) { throw new XMLStreamException(e); } } private void handleCharacters(Characters event) throws XMLStreamException { try { filter.characters( event.getData().toCharArray(), 0, event.getData().length()); } catch (SAXException e) { throw new XMLStreamException(e); } } private void handleEndElement(EndElement event) throws XMLStreamException { QName qName = event.getName(); try { // fire endElement String prefix = qName.getPrefix(); String rawname; if(prefix==null || prefix.length()==0) rawname = qName.getLocalPart(); else rawname = prefix + ':' + qName.getLocalPart(); filter.endElement( qName.getNamespaceURI(), qName.getLocalPart(), rawname); // end namespace bindings for( Iterator i = event.getNamespaces(); i.hasNext();) { String nsprefix = ((Namespace)i.next()).getPrefix(); if( nsprefix == null ) { // true for default namespace nsprefix = ""; } filter.endPrefixMapping(nsprefix); } } catch (SAXException e) { throw new XMLStreamException(e); } } private void handleStartElement(StartElement event) throws XMLStreamException { try { // start namespace bindings for (Iterator i = event.getNamespaces(); i.hasNext();) { String prefix = ((Namespace)i.next()).getPrefix(); if (prefix == null) { // true for default namespace prefix = ""; } filter.startPrefixMapping( prefix, event.getNamespaceURI(prefix)); } // fire startElement QName qName = event.getName(); String prefix = qName.getPrefix(); String rawname; if (prefix == null || prefix.length() == 0) rawname = qName.getLocalPart(); else rawname = prefix + ':' + qName.getLocalPart(); Attributes saxAttrs = getAttributes(event); filter.startElement( qName.getNamespaceURI(), qName.getLocalPart(), rawname, saxAttrs); } catch (SAXException e) { throw new XMLStreamException(e); } } /** * Get the attributes associated with the given START_ELEMENT StAXevent. * * @return the StAX attributes converted to an org.xml.sax.Attributes */ private Attributes getAttributes(StartElement event) { AttributesImpl attrs = new AttributesImpl(); if ( !event.isStartElement() ) { throw new InternalError( "getAttributes() attempting to process: " + event); } // Add namspace declarations if required if (filter.getNamespacePrefixes()) { for (Iterator i = event.getNamespaces(); i.hasNext();) { Namespace staxNamespace = (javax.xml.stream.events.Namespace)i.next(); String uri = staxNamespace.getNamespaceURI(); if (uri==null) uri=""; String prefix = staxNamespace.getPrefix(); if (prefix==null) prefix=""; String qName = "xmlns"; if (prefix.length() == 0) { prefix = qName; } else { qName = qName + ':' + prefix; } attrs.addAttribute("http://www.w3.org/2000/xmlns/", prefix, qName, "CDATA", uri); } } // gather non-namespace attrs for (Iterator i = event.getAttributes(); i.hasNext();) { Attribute staxAttr = (javax.xml.stream.events.Attribute)i.next(); String uri = staxAttr.getName().getNamespaceURI(); if (uri == null) uri = ""; String localName = staxAttr.getName().getLocalPart(); String prefix = staxAttr.getName().getPrefix(); String qName; if (prefix == null || prefix.length() == 0) qName = localName; else qName = prefix + ':' + localName; String type = staxAttr.getDTDType(); String value = staxAttr.getValue(); attrs.addAttribute(uri, localName, qName, type, value); } return attrs; } private void handleNamespace() { // no-op ??? // namespace events don't normally occur outside of a startElement // or endElement } private void handleAttribute() { // no-op ??? // attribute events don't normally occur outside of a startElement // or endElement } private void handleDTD() { // no-op ??? // it seems like we need to pass this info along, but how? } private void handleComment(Comment comment) throws XMLStreamException { try { String text = comment.getText(); filter.comment( text.toCharArray(), 0, text.length()); } catch (SAXException e) { throw new XMLStreamException(e); } } private void handleEntityReference() { // no-op ??? } private void handleSpace() { // no-op ??? // this event is listed in the javadoc, but not in the spec. } private void handleNotationDecl() { // no-op ??? // this event is listed in the javadoc, but not in the spec. } private void handleEntityDecl() { // no-op ??? // this event is listed in the javadoc, but not in the spec. } private void handleCDATA() { // no-op ??? // this event is listed in the javadoc, but not in the spec. } } src/javanet/staxutils/SimpleNamespaceContext.java0000644000175000017500000002762510075231752021375 0ustar tonytony/* * $Id: SimpleNamespaceContext.java,v 1.7 2004-07-14 13:23:54 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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 java.util.Collections; import java.util.LinkedHashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.xml.XMLConstants; import javax.xml.namespace.NamespaceContext; /** * Simple NamespaceContext implementation backed by a HashMap. * * @author Christian Niles * @version $Revision: 1.7 $ */ public class SimpleNamespaceContext implements ExtendedNamespaceContext, StaticNamespaceContext { /** * The parent context, which may be null */ protected NamespaceContext parent; /** * map containing bound namespaces, keyed by their prefix. A LinkedHashMap * is used to ensure that {@link #getPrefix(String)} always returns the same * prefix, unless that prefix is removed. */ protected Map namespaces = new LinkedHashMap(); /** * Constructs a SimpleNamespaceContext with no parent context or namespace * declarations. */ public SimpleNamespaceContext() { } /** * Constructs a SimpleNamespaceContext with no parent context that contains * the specified prefixes. * * @param namespaces A Map of namespace URIs, keyed by their prefixes. */ public SimpleNamespaceContext(Map namespaces) { if (namespaces != null) { this.namespaces.putAll(namespaces); } } /** * Constructs an empty SimpleNamespaceContext with the given parent. The * parent context will be forwarded any requests for namespaces not declared * in this context. * * @param parent The parent context. */ public SimpleNamespaceContext(NamespaceContext parent) { this.parent = parent; } /** * Constructs an empty SimpleNamespaceContext with the given parent. The * parent context will be forwarded any requests for namespaces not declared * in this context. * * @param parent The parent context. * @param namespaces A Map of namespace URIs, keyed by their prefixes. */ public SimpleNamespaceContext(NamespaceContext parent, Map namespaces) { this.parent = parent; if (namespaces != null) { this.namespaces.putAll(namespaces); } } /** * Returns a reference to the parent of this context. * * @return The parent context, or null if this is a root * context. */ public NamespaceContext getParent() { return parent; } /** * Sets the parent context used to inherit namespace bindings. * * @param parent The new parent context. */ public void setParent(NamespaceContext parent) { this.parent = parent; } /** * Determines if this is a root context. * * @return true if this is a root context, false * otherwise. */ public boolean isRootContext() { return parent == null; } public String getNamespaceURI(String prefix) { if (prefix == null) { throw new IllegalArgumentException("prefix argument was null"); } else if (prefix.equals(XMLConstants.XML_NS_PREFIX)) { return XMLConstants.XML_NS_URI; } else if (prefix.equals(XMLConstants.XMLNS_ATTRIBUTE)) { return XMLConstants.XMLNS_ATTRIBUTE_NS_URI; } else if (namespaces.containsKey(prefix)) { // The StAX spec says to return null for any undefined prefix. To support // undefining a prefix as specified in the Namespaces spec, we store // undefined prefixes as the empty string. String uri = (String) namespaces.get(prefix); if (uri.length() == 0) { return null; } else { return uri; } } else if (parent != null) { return parent.getNamespaceURI(prefix); } else { return null; } } public String getPrefix(String nsURI) { if (nsURI == null) { throw new IllegalArgumentException("nsURI was null"); } else if (nsURI.length() == 0) { throw new IllegalArgumentException("nsURI was empty"); } else if (nsURI.equals(XMLConstants.XML_NS_URI)) { return XMLConstants.XML_NS_PREFIX; } else if (nsURI.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) { return XMLConstants.XMLNS_ATTRIBUTE; } Iterator iter = namespaces.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); String uri = (String) entry.getValue(); if (uri.equals(nsURI)) { return (String) entry.getKey(); } } if (parent != null) { return parent.getPrefix(nsURI); } else if (nsURI.length() == 0) { return ""; } else { return null; } } /** * Determines if the specified prefix is declared within this context, * irrespective of any ancestor contexts. * * @param prefix The prefix to check. * @return true if the prefix is declared in this context, * false otherwise. */ public boolean isPrefixDeclared(String prefix) { return namespaces.containsKey(prefix); } public Iterator getDeclaredPrefixes() { return Collections.unmodifiableCollection(this.namespaces.keySet()) .iterator(); } /** * Returns the number of namespace prefixes declared in this context. * * @return The number of namespace prefixes declared in this context. */ public int getDeclaredPrefixCount() { return namespaces.size(); } public Iterator getPrefixes() { if (parent == null || !(parent instanceof ExtendedNamespaceContext)) { return getDeclaredPrefixes(); } else { Set prefixes = new HashSet(this.namespaces.keySet()); ExtendedNamespaceContext superCtx = (ExtendedNamespaceContext) parent; for (Iterator i = superCtx.getPrefixes(); i.hasNext();) { String prefix = (String) i.next(); prefixes.add(prefix); } return prefixes.iterator(); } } public Iterator getPrefixes(String nsURI) { if (nsURI == null) { throw new IllegalArgumentException("nsURI was null"); } else if (nsURI.equals(XMLConstants.XML_NS_URI)) { return Collections.singleton(XMLConstants.XML_NS_PREFIX).iterator(); } else if (nsURI.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) { return Collections.singleton(XMLConstants.XMLNS_ATTRIBUTE) .iterator(); } Set prefixes = null; Iterator iter = namespaces.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); String uri = (String) entry.getValue(); if (uri.equals(nsURI)) { if (prefixes == null) { prefixes = new HashSet(); } prefixes.add(entry.getKey()); } } if (parent != null) { for (Iterator i = parent.getPrefixes(nsURI); i.hasNext();) { String prefix = (String) i.next(); if (prefixes == null) { prefixes = new HashSet(); } prefixes.add(prefix); } } if (prefixes != null) { return Collections.unmodifiableSet(prefixes).iterator(); } else if (nsURI.length() == 0) { return Collections.singleton("").iterator(); } else { return Collections.EMPTY_LIST.iterator(); } } /** * Sets the default namespace in this context. * * @param nsURI The default namespace URI. * @return The previously declared namespace uri, or null if * the default prefix wasn't previously declared in this context. */ public String setDefaultNamespace(String nsURI) { if (nsURI != null) { if (nsURI.equals(XMLConstants.XML_NS_URI)) { throw new IllegalArgumentException("Attempt to map 'xml' uri"); } else if (nsURI.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) { throw new IllegalArgumentException("Attempt to map 'xmlns' uri"); } return (String) namespaces.put(XMLConstants.DEFAULT_NS_PREFIX, nsURI); } else { // put the empty string to record an undefined prefix return (String) namespaces.put(XMLConstants.DEFAULT_NS_PREFIX, ""); } } /** * Declares a namespace binding in this context. * * @param prefix The namespace prefix. * @param nsURI The namespace URI. * @return The previously declared namespace uri, or null if * the prefix wasn't previously declared in this context. */ public String setPrefix(String prefix, String nsURI) { if (prefix == null) { throw new NullPointerException("Namespace Prefix was null"); } else if (prefix.equals(XMLConstants.DEFAULT_NS_PREFIX)) { return setDefaultNamespace(nsURI); } else if (prefix.equals(XMLConstants.XML_NS_PREFIX)) { throw new IllegalArgumentException("Attempt to map 'xml' prefix"); } else if (prefix.equals(XMLConstants.XMLNS_ATTRIBUTE)) { throw new IllegalArgumentException("Attempt to map 'xmlns' prefix"); } else if (nsURI != null) { if (nsURI.equals(XMLConstants.XML_NS_URI)) { throw new IllegalArgumentException("Attempt to map 'xml' uri"); } else if (nsURI.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) { throw new IllegalArgumentException("Attempt to map 'xmlns' uri"); } else { return (String) namespaces.put(prefix, nsURI); } } else { // put the empty string to record an undefined prefix return (String) namespaces.put(prefix, ""); } } }src/javanet/staxutils/IndentingXMLStreamWriter.java0000644000175000017500000002634610424446144021633 0ustar tonytony/* * Copyright (c) 2006, John Kristian * 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 StAX-Utils 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 javanet.staxutils.helpers.StreamWriterDelegate; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; /** * A filter that indents an XML stream. To apply it, construct a filter that * contains another {@link XMLStreamWriter}, which you pass to the constructor. * Then call methods of the filter instead of the contained stream. For example: * *
 * {@link XMLStreamWriter} stream = ...
 * stream = new {@link IndentingXMLStreamWriter}(stream);
 * stream.writeStartDocument();
 * ...
 * 
* *

* The filter inserts characters to format the document as an outline, with * nested elements indented. Basically, it inserts a line break and whitespace * before: *

* This works well with 'data-oriented' XML, wherein each element contains * either data or nested elements but not both. It can work badly with other * styles of XML. For example, the data in a 'mixed content' document are apt to * be polluted with indentation characters. *

* Indentation can be adjusted by setting the newLine and indent properties. But * set them to whitespace only, for best results. Non-whitespace is apt to cause * problems, for example when this class attempts to insert newLine before the * root element. * * @author John Kristian */ public class IndentingXMLStreamWriter extends StreamWriterDelegate implements Indentation { public IndentingXMLStreamWriter(XMLStreamWriter out) { super(out); } /** How deeply nested the current scope is. The root element is depth 1. */ private int depth = 0; // document scope /** stack[depth] indicates what's been written into the current scope. */ private int[] stack = new int[] { 0, 0, 0, 0 }; // nothing written yet private static final int WROTE_MARKUP = 1; private static final int WROTE_DATA = 2; private String indent = DEFAULT_INDENT; private String newLine = NORMAL_END_OF_LINE; /** newLine followed by copies of indent. */ private char[] linePrefix = null; public void setIndent(String indent) { if (!indent.equals(this.indent)) { this.indent = indent; linePrefix = null; } } public String getIndent() { return indent; } public void setNewLine(String newLine) { if (!newLine.equals(this.newLine)) { this.newLine = newLine; linePrefix = null; } } /** * @return System.getProperty("line.separator"); or * {@link #NORMAL_END_OF_LINE} if that fails. */ public static String getLineSeparator() { try { return System.getProperty("line.separator"); } catch (SecurityException ignored) { } return NORMAL_END_OF_LINE; } public String getNewLine() { return newLine; } public void writeStartDocument() throws XMLStreamException { beforeMarkup(); out.writeStartDocument(); afterMarkup(); } public void writeStartDocument(String version) throws XMLStreamException { beforeMarkup(); out.writeStartDocument(version); afterMarkup(); } public void writeStartDocument(String encoding, String version) throws XMLStreamException { beforeMarkup(); out.writeStartDocument(encoding, version); afterMarkup(); } public void writeDTD(String dtd) throws XMLStreamException { beforeMarkup(); out.writeDTD(dtd); afterMarkup(); } public void writeProcessingInstruction(String target) throws XMLStreamException { beforeMarkup(); out.writeProcessingInstruction(target); afterMarkup(); } public void writeProcessingInstruction(String target, String data) throws XMLStreamException { beforeMarkup(); out.writeProcessingInstruction(target, data); afterMarkup(); } public void writeComment(String data) throws XMLStreamException { beforeMarkup(); out.writeComment(data); afterMarkup(); } public void writeEmptyElement(String localName) throws XMLStreamException { beforeMarkup(); out.writeEmptyElement(localName); afterMarkup(); } public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { beforeMarkup(); out.writeEmptyElement(namespaceURI, localName); afterMarkup(); } public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { beforeMarkup(); out.writeEmptyElement(prefix, localName, namespaceURI); afterMarkup(); } public void writeStartElement(String localName) throws XMLStreamException { beforeStartElement(); out.writeStartElement(localName); afterStartElement(); } public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { beforeStartElement(); out.writeStartElement(namespaceURI, localName); afterStartElement(); } public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { beforeStartElement(); out.writeStartElement(prefix, localName, namespaceURI); afterStartElement(); } public void writeCharacters(String text) throws XMLStreamException { out.writeCharacters(text); afterData(); } public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { out.writeCharacters(text, start, len); afterData(); } public void writeCData(String data) throws XMLStreamException { out.writeCData(data); afterData(); } public void writeEntityRef(String name) throws XMLStreamException { out.writeEntityRef(name); afterData(); } public void writeEndElement() throws XMLStreamException { beforeEndElement(); out.writeEndElement(); afterEndElement(); } public void writeEndDocument() throws XMLStreamException { try { while (depth > 0) { writeEndElement(); // indented } } catch (Exception ignored) { } out.writeEndDocument(); afterEndDocument(); } /** Prepare to write markup, by writing a new line and indentation. */ protected void beforeMarkup() { int soFar = stack[depth]; if ((soFar & WROTE_DATA) == 0 // no data in this scope && (depth > 0 || soFar != 0)) // not the first line { try { writeNewLine(depth); if (depth > 0 && getIndent().length() > 0) { afterMarkup(); // indentation was written } } catch (Exception e) { } } } /** Note that markup or indentation was written. */ protected void afterMarkup() { stack[depth] |= WROTE_MARKUP; } /** Note that data were written. */ protected void afterData() { stack[depth] |= WROTE_DATA; } /** Prepare to start an element, by allocating stack space. */ protected void beforeStartElement() { beforeMarkup(); if (stack.length <= depth + 1) { // Allocate more space for the stack: int[] newStack = new int[stack.length * 2]; System.arraycopy(stack, 0, newStack, 0, stack.length); stack = newStack; } stack[depth + 1] = 0; // nothing written yet } /** Note that an element was started. */ protected void afterStartElement() { afterMarkup(); ++depth; } /** Prepare to end an element, by writing a new line and indentation. */ protected void beforeEndElement() { if (depth > 0 && stack[depth] == WROTE_MARKUP) { // but not data try { writeNewLine(depth - 1); } catch (Exception ignored) { } } } /** Note that an element was ended. */ protected void afterEndElement() { if (depth > 0) { --depth; } } /** Note that a document was ended. */ protected void afterEndDocument() { if (stack[depth = 0] == WROTE_MARKUP) { // but not data try { writeNewLine(0); } catch (Exception ignored) { } } stack[depth] = 0; // start fresh } /** Write a line separator followed by indentation. */ protected void writeNewLine(int indentation) throws XMLStreamException { final int newLineLength = getNewLine().length(); final int prefixLength = newLineLength + (getIndent().length() * indentation); if (prefixLength > 0) { if (linePrefix == null) { linePrefix = (getNewLine() + getIndent()).toCharArray(); } while (prefixLength > linePrefix.length) { // make linePrefix longer: char[] newPrefix = new char[newLineLength + ((linePrefix.length - newLineLength) * 2)]; System.arraycopy(linePrefix, 0, newPrefix, 0, linePrefix.length); System.arraycopy(linePrefix, newLineLength, newPrefix, linePrefix.length, linePrefix.length - newLineLength); linePrefix = newPrefix; } out.writeCharacters(linePrefix, 0, prefixLength); } } } src/javanet/staxutils/DummyLocator.java0000644000175000017500000001164711535774174017412 0ustar tonytony/* * 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.Locator; /** * A dummy locator that returns -1 and null from all methods to * indicate that location info is not available. * * @author Ryan.Shoemaker@Sun.COM */ public class DummyLocator implements Locator { /** * Return the column number where the current document event ends. *

*

Warning: The return value from the method * is intended only as an approximation for the sake of error * reporting; it is not intended to provide sufficient information * to edit the character content of the original XML document.

*

*

The return value is an approximation of the column number * in the document entity or external parsed entity where the * markup triggering the event appears.

*

*

If possible, the SAX driver should provide the line position * of the first character after the text associated with the document * event.

*

*

If possible, the SAX driver should provide the line position * of the first character after the text associated with the document * event. The first column in each line is column 1.

* * @return The column number, or -1 if none is available. * @see #getLineNumber */ public int getColumnNumber() { return -1; } /** * Return the line number where the current document event ends. *

*

Warning: The return value from the method * is intended only as an approximation for the sake of error * reporting; it is not intended to provide sufficient information * to edit the character content of the original XML document.

*

*

The return value is an approximation of the line number * in the document entity or external parsed entity where the * markup triggering the event appears.

*

*

If possible, the SAX driver should provide the line position * of the first character after the text associated with the document * event. The first line in the document is line 1.

* * @return The line number, or -1 if none is available. * @see #getColumnNumber */ public int getLineNumber() { return -1; } /** * Return the public identifier for the current document event. *

*

The return value is the public identifier of the document * entity or of the external parsed entity in which the markup * triggering the event appears.

* * @return A string containing the public identifier, or * null if none is available. * @see #getSystemId */ public String getPublicId() { return null; } /** * Return the system identifier for the current document event. *

*

The return value is the system identifier of the document * entity or of the external parsed entity in which the markup * triggering the event appears.

*

*

If the system identifier is a URL, the parser must resolve it * fully before passing it to the application.

* * @return A string containing the system identifier, or null * if none is available. * @see #getPublicId */ public String getSystemId() { return null; } } src/javanet/staxutils/BaseXMLEventReader.java0000644000175000017500000001156210072360234020326 0ustar tonytony/* * $Id: BaseXMLEventReader.java,v 1.1 2004-07-05 23:13:31 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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 java.util.NoSuchElementException; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Comment; import javax.xml.stream.events.XMLEvent; /** * Abstract base class for {@link XMLEventReader} implementations. * * @author Christian Niles * @version $Revision: 1.1 $ */ public abstract class BaseXMLEventReader implements XMLEventReader { /** Whether we've been closed or not. */ protected boolean closed; public synchronized String getElementText() throws XMLStreamException { if (closed) { throw new XMLStreamException("Stream has been closed"); } // TODO At the moment, this simply coalesces all Characters events up to a // terminal EndElement event. StringBuffer buffer = new StringBuffer(); while (true) { XMLEvent event = nextEvent(); if (event.isCharacters()) { // don't return ignorable whitespace if (event.getEventType() != XMLEvent.SPACE) { buffer.append(event.asCharacters().getData()); } } else if (event.isEndElement()) { break; } else { throw new XMLStreamException( "Non-text event encountered in getElementText(): " + event); } } return buffer.toString(); } public XMLEvent nextTag() throws XMLStreamException { if (closed) { throw new XMLStreamException("Stream has been closed"); } XMLEvent event; do { if (hasNext()) { event = nextEvent(); if (event.isStartElement() || event.isEndElement()) { return event; } else if (event.isCharacters()) { if (!event.asCharacters().isWhiteSpace()) { throw new XMLStreamException( "Non-ignorable space encountered"); } } else if (!(event instanceof Comment)) { throw new XMLStreamException( "Non-ignorable event encountered: " + event); } } else { throw new XMLStreamException("Ran out of events in nextTag()"); } } while (!event.isStartElement() && !event.isEndElement()); return event; } public Object getProperty(String name) throws IllegalArgumentException { throw new IllegalArgumentException("Property not supported: " + name); } public synchronized void close() throws XMLStreamException { if (!closed) { closed = true; } } public Object next() { try { return nextEvent(); } catch (XMLStreamException e) { NoSuchElementException ex = new NoSuchElementException( "Error getting next event"); ex.initCause(e); throw ex; } } public void remove() { throw new UnsupportedOperationException(); } }src/javanet/staxutils/EntityDeclarationImpl.java0000644000175000017500000000734210065630042021212 0ustar tonytony/* $Id: EntityDeclarationImpl.java,v 1.1 2004-06-21 18:59:45 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 javax.xml.stream.Location; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.EntityDeclaration; import java.io.IOException; import java.io.Writer; /** * Implementation of {@link javax.xml.stream.events.EntityDeclaration}. * * The only reason this class exists is because {@link javax.xml.stream.XMLEventFactory} * doesn't have a factory for this event type and the {@link ContentHandlerToXMLEventWriter} * needs to create one of these event types to handle skippedEntity events. * * @author Ryan.Shoemaker@Sun.COM * @version 1.0 */ class EntityDeclarationImpl extends EventHelper implements EntityDeclaration { private final String entityName; private final String publicId; private final String systemId; private final String notationName; private final String replacementText; public EntityDeclarationImpl(Location location, String entityName, String publicId, String systemId, String notationName, String replacementText) { super(location); this.entityName = entityName; this.publicId = publicId; this.systemId = systemId; this.notationName = notationName; this.replacementText = replacementText; } public String getBaseURI() { // TODO: ?? return null; } public String getName() { return entityName; } public String getNotationName() { return notationName; } public String getPublicId() { return publicId; } public String getReplacementText() { return replacementText; } public String getSystemId() { return systemId; } public int getEventType() { return ENTITY_DECLARATION; } public boolean isEntityReference() { return true; } public void writeAsEncodedUnicode(Writer w) throws XMLStreamException { try { w.write('&'); w.write(entityName); w.write(';'); } catch (IOException ie) { throw new XMLStreamException(ie); } } } src/javanet/staxutils/StaticLocation.java0000644000175000017500000000410211535774174017677 0ustar tonytony/* * $Id: StaticLocation.java,v 1.1 2004-07-08 14:29:42 cniles Exp $ * * Copyright (c) 2004, Christian Niles, Unit12 * 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 Christian Niles, Unit12, 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 javax.xml.stream.Location; /** * Marker interface used to denote {@link Location} implementations whose state is * not transient or dependent on external objects/events and will remain stable * unless explicitly updated. * * @author Christian Niles * @version $Revision: 1.1 $ */ public interface StaticLocation extends Location { } src/javanet/staxutils/NamespaceContextAdapter.java0000644000175000017500000000602110072360150021477 0ustar tonytony/* * $Id: NamespaceContextAdapter.java,v 1.1 2004-07-05 23:12:40 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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 java.util.Collections; import java.util.Iterator; import javax.xml.namespace.NamespaceContext; /** * {@link NamespaceContext} that wraps another context. This class is useful for * hiding the underlying implementation, or adding additional functionality on top of * another context. * * @author Christian Niles * @version $Revision: 1.1 $ */ public class NamespaceContextAdapter implements NamespaceContext { /** The wrapped context. */ protected NamespaceContext namespaceCtx; public NamespaceContextAdapter() { } public NamespaceContextAdapter(NamespaceContext namespaceCtx) { this.namespaceCtx = namespaceCtx; } public String getNamespaceURI(String prefix) { if (namespaceCtx != null) { return this.namespaceCtx.getNamespaceURI(prefix); } else { return null; } } public String getPrefix(String nsURI) { if (this.namespaceCtx != null) { return this.namespaceCtx.getPrefix(nsURI); } else { return null; } } public Iterator getPrefixes(String nsURI) { if (this.namespaceCtx != null) { return this.namespaceCtx.getPrefixes(nsURI); } else { return Collections.EMPTY_LIST.iterator(); } } }src/javanet/staxutils/Indentation.java0000644000175000017500000000526011535774174017241 0ustar tonytony/* * Copyright (c) 2006, John Kristian * 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 StAX-Utils 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; /** * Characters that represent line breaks and indentation. These are represented * as String-valued JavaBean properties. */ public interface Indentation { /** Two spaces; the default indentation. */ public static final String DEFAULT_INDENT = " "; /** * Set the characters used for one level of indentation. The default is * {@link #DEFAULT_INDENT}. "\t" is a popular alternative. */ void setIndent(String indent); /** The characters used for one level of indentation. */ String getIndent(); /** * "\n"; the normalized representation of end-of-line in XML. */ public static final String NORMAL_END_OF_LINE = "\n"; /** * Set the characters that introduce a new line. The default is * {@link #NORMAL_END_OF_LINE}. * {@link IndentingXMLStreamWriter#getLineSeparator}() is a popular * alternative. */ public void setNewLine(String newLine); /** The characters that introduce a new line. */ String getNewLine(); } src/javanet/staxutils/BaseXMLInputFactory.java0000644000175000017500000002110410075370466020555 0ustar tonytony/* * $Id: BaseXMLInputFactory.java,v 1.2 2004-07-15 02:51:32 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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 java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import javanet.staxutils.XMLStreamEventReader; import javax.xml.stream.EventFilter; import javax.xml.stream.StreamFilter; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLReporter; import javax.xml.stream.XMLResolver; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.util.XMLEventAllocator; import javax.xml.transform.Source; /** * * @author Christian Niles * @version $Revision: 1.2 $ */ public abstract class BaseXMLInputFactory extends XMLInputFactory { protected XMLEventAllocator eventAllocator; protected XMLReporter xmlReporter; protected XMLResolver xmlResolver; public Object getProperty(String name) throws IllegalArgumentException { // TODO provide base support for well-known properties? throw new IllegalArgumentException(name + " property not supported"); } public boolean isPropertySupported(String name) { return false; } public void setProperty(String name, Object value) throws IllegalArgumentException { throw new IllegalArgumentException(name + " property not supported"); } public XMLEventAllocator getEventAllocator() { return this.eventAllocator; } public void setEventAllocator(XMLEventAllocator eventAllocator) { this.eventAllocator = eventAllocator; } public XMLReporter getXMLReporter() { return this.xmlReporter; } public void setXMLReporter(XMLReporter xmlReporter) { this.xmlReporter = xmlReporter; } public XMLResolver getXMLResolver() { return this.xmlResolver; } public void setXMLResolver(XMLResolver xmlResolver) { this.xmlResolver = xmlResolver; } public XMLEventReader createXMLEventReader(InputStream stream, String encoding) throws XMLStreamException { try { if (encoding != null) { return createXMLEventReader(new InputStreamReader(stream, encoding), encoding); } else { return createXMLEventReader(new InputStreamReader(stream)); } } catch (UnsupportedEncodingException e) { throw new XMLStreamException(e); } } public XMLEventReader createXMLEventReader(InputStream stream) throws XMLStreamException { return createXMLEventReader(new InputStreamReader(stream)); } public XMLEventReader createXMLEventReader(String systemId, InputStream stream) throws XMLStreamException { return createXMLEventReader(systemId, new InputStreamReader(stream)); } public XMLEventReader createXMLEventReader(XMLStreamReader reader) throws XMLStreamException { return new XMLStreamEventReader(reader); } public XMLStreamReader createXMLStreamReader(InputStream stream, String encoding) throws XMLStreamException { try { if (encoding != null) { return createXMLStreamReader(new InputStreamReader(stream, encoding), encoding); } else { return createXMLStreamReader(new InputStreamReader(stream)); } } catch (UnsupportedEncodingException e) { throw new XMLStreamException(e); } } public XMLStreamReader createXMLStreamReader(InputStream stream) throws XMLStreamException { return createXMLStreamReader(new InputStreamReader(stream)); } public XMLStreamReader createXMLStreamReader(String systemId, InputStream stream) throws XMLStreamException { return createXMLStreamReader(systemId, new InputStreamReader(stream)); } public XMLEventReader createXMLEventReader(Reader reader) throws XMLStreamException { return createXMLEventReader(createXMLStreamReader(reader)); } public XMLEventReader createXMLEventReader(Reader reader, String encoding) throws XMLStreamException { return createXMLEventReader(createXMLStreamReader(reader, encoding)); } public XMLEventReader createXMLEventReader(Source source) throws XMLStreamException { return createXMLEventReader(createXMLStreamReader(source)); } public XMLEventReader createXMLEventReader(String systemId, Reader reader) throws XMLStreamException { return createXMLEventReader(createXMLStreamReader(systemId, reader)); } public XMLEventReader createXMLEventReader(String systemId, Reader reader, String encoding) throws XMLStreamException { return createXMLEventReader(createXMLStreamReader(systemId, reader, encoding)); } public XMLStreamReader createXMLStreamReader(Source source) throws XMLStreamException { // TODO implement TrAX support throw new UnsupportedOperationException(); } public XMLStreamReader createXMLStreamReader(Reader reader) throws XMLStreamException { return createXMLStreamReader(null, reader, null); } public XMLStreamReader createXMLStreamReader(Reader reader, String encoding) throws XMLStreamException { return createXMLStreamReader(null, reader, encoding); } public XMLStreamReader createXMLStreamReader(String systemId, Reader reader) throws XMLStreamException { String encoding = null; if (reader instanceof InputStreamReader) { encoding = ((InputStreamReader) reader).getEncoding(); } return createXMLStreamReader(systemId, reader, encoding); } public XMLEventReader createFilteredReader(XMLEventReader reader, EventFilter filter) throws XMLStreamException { // TODO implement filter support throw new UnsupportedOperationException(); } public XMLStreamReader createFilteredReader(XMLStreamReader reader, StreamFilter filter) throws XMLStreamException { // TODO implement filter support throw new UnsupportedOperationException(); } /** * Called by all other methods to construct an {@link XMLStreamReader}. * * @param systemId The system ID of the provided reader, or null * @param reader The character stream from which to construct the StAX stream. * @param encoding The underlying encoding of the reader, or null. * @return The newly constructed {@link XMLStreamReader}. * @throws XMLStreamException If an error occurs constructing the reader. */ public abstract XMLStreamReader createXMLStreamReader(String systemId, Reader reader, String encoding) throws XMLStreamException; }src/javanet/staxutils/io/0000755000175000017500000000000011542302312014501 5ustar tonytonysrc/javanet/staxutils/io/StreamEventWriter.java0000644000175000017500000001202610075363570021014 0ustar tonytony/* * $Id: StreamEventWriter.java,v 1.4 2004-07-15 02:09:59 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.io; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import javanet.staxutils.BaseXMLEventWriter; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; /** * {@link javax.xml.stream.XMLEventWriter} that writes events to a character stream * using {@link XMLEvent#writeAsEncodedUnicode(Writer)}. * * @author Christian Niles * @version $Revision: 1.4 $ */ public class StreamEventWriter extends BaseXMLEventWriter { /** The underlying {@link Writer}. */ private Writer writer; /** * Constructs a new StreamEventWriter that writes to a file. * * @param file The file to write. * @throws IOException If the file couldn't be opened. */ public StreamEventWriter(File file) throws IOException { this(new FileWriter(file)); } /** * Constructs a new StreamEventWriter that writes to a binary * stream. * * @param os The stream to write. */ public StreamEventWriter(OutputStream os) { this(new OutputStreamWriter(os)); } /** * Constructs a new StreamEventWriter that writes to a character * stream. * * @param writer The stream to write. */ public StreamEventWriter(Writer writer) { this.writer = writer; } public synchronized void flush() throws XMLStreamException { super.flush(); try { writer.flush(); } catch (IOException e) { throw new XMLStreamException(e); } } /** * Saved reference to most recent start element. This is used to properly * write empty elements. Each startElement event is saved here until the * next event is received, at which point it will be written as a start or * empty element if it is followed directly by an EndElement. */ private StartElement savedStart; protected void sendEvent(XMLEvent event) throws XMLStreamException { try { // Check if we have a cached start tag. If we do, then we should // check if this event is actually an end tag, so we can properly // write an empty element. if (savedStart != null) { StartElement start = savedStart; savedStart = null; if (event.getEventType() == XMLEvent.END_ELEMENT) { // this end tag directly followed a start tag, so send // the underlying writer an empty start element XMLWriterUtils.writeStartElement(start, true, writer); writer.flush(); return; } else { // element has content, so send a regular start tag XMLWriterUtils.writeStartElement(start, false, writer); } } if (event.isStartElement()) { savedStart = event.asStartElement(); } else { event.writeAsEncodedUnicode(writer); } } catch (IOException e) { throw new XMLStreamException(e); } } }src/javanet/staxutils/io/XMLWriterUtils.java0000644000175000017500000012735210211654522020241 0ustar tonytony/* * $Id: XMLWriterUtils.java,v 1.6 2005-03-03 18:37:05 ryan_shoemaker Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.io; import java.io.IOException; import java.io.Writer; import java.util.Iterator; import java.util.Map; import javanet.staxutils.XMLStreamUtils; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.Characters; import javax.xml.stream.events.Comment; import javax.xml.stream.events.DTD; import javax.xml.stream.events.EndDocument; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.EntityDeclaration; import javax.xml.stream.events.EntityReference; import javax.xml.stream.events.Namespace; import javax.xml.stream.events.NotationDeclaration; import javax.xml.stream.events.ProcessingInstruction; import javax.xml.stream.events.StartDocument; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; /** * Set of utility methods useful when writing XML. * * @author Christian Niles * @version $Revision: 1.6 $ */ public final class XMLWriterUtils { /** * Prevent instantiation. */ private XMLWriterUtils() { } /** * Writes a quoted version of the given value, automatically determining the * appropriate quote character. The value will not be encoded before being * written. This method is useful when writing quoted DTD values, such as system * IDs. * * @param value The value to quote and output. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeQuotedValue(String value, Writer writer) throws IOException { char quoteChar = (value.indexOf('"') < 0 ? '"' : '\''); writer.write(quoteChar); writer.write(value); writer.write(quoteChar); } /** * Encodes the given value and writes it to the provided stream, wrapping it in * the appropriate quote character. This method is useful when writing attribute * values, and entity replacement text. * * @param value The value to encode, quote, and output. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeEncodedQuotedValue(String value, Writer writer) throws IOException { char quoteChar = (value.indexOf('"') < 0 ? '"' : '\''); writer.write(quoteChar); writeEncodedValue(value, quoteChar, writer); writer.write(quoteChar); } /** * Encodes the given value, and writes it to the stream, but does not actually * wrap the value in the quote character. The provided quote character is used to * determine whether a character must be encoded or not. * * @param value The value to encode and output. * @param quoteChar The quote character; used to determine which characters need * to be encoded. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeEncodedValue(String value, char quoteChar, Writer writer) throws IOException { // write value, encoding special characters along the way for (int i = 0, s = value.length(); i < s; i++) { char c = value.charAt(i); if (c == '\'') { writer.write(quoteChar == '\'' ? "'" : "'"); } else if (c == '\"') { writer.write(quoteChar == '\"' ? """ : "\""); } else if (c == '\n') { writer.write(" "); } else { writeEncodedCharacter(c, writer); } } } /** * Encodes the provided text and writes it to the provided stream. This method is * useful when writing character data, such as element text or CData sections, * and will not encode single or double quotes. * * @param text The text to write. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeEncodedText(CharSequence text, Writer writer) throws IOException { for (int i = 0, s = text.length(); i < s; i++) { writeEncodedCharacter(text.charAt(i), writer); } } public static final void writeEncodedText(char[] text, int start, int len, Writer writer) throws IOException { for (int i = start, s = start + len; i < s; i++) { writeEncodedCharacter(text[i], writer); } } /** * Encodes the provided character if needed, and writes it to an output stream. * * @param c The character to encode and output. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeEncodedCharacter(char c, Writer writer) throws IOException { if (c == '&') { writer.write("&"); } else if (c == '<') { writer.write("<"); } else if (c == '>') { writer.write(">"); } else if (c == '\r') { writer.write(" "); } else { writer.write(c); } } /** * Writes a qualified name to the provided stream. * * @param name The name to write. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeQName(QName name, Writer writer) throws IOException { String prefix = name.getPrefix(); if (prefix != null && prefix.length() > 0) { writer.write(prefix); writer.write(':'); } writer.write(name.getLocalPart()); } /** * Writes a qualified name to the provided stream. * * @param prefix The prefix, or null * @param localPart The local part. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeQName(String prefix, String localPart, Writer writer) throws IOException { if (prefix != null && prefix.length() > 0) { writer.write(prefix); writer.write(':'); } writer.write(localPart); } /** * Writes the given event to the provided {@link Writer}. This method * will delegate the actual task of writing to the stream to the appropriate * overloaded method. * * @param event The event to write. * @param writer The destination XML stream. * @throws IOException If an error occurs writing to the stream. * @throws XMLStreamException If the event is a StartElement and an error occurs * writing the Namespace or Attribute events. * @throws IllegalArgumentException If the event is an unknown type. */ public static final void writeEvent(XMLEvent event, Writer writer) throws IOException, XMLStreamException { int eventType = event.getEventType(); switch (eventType) { case XMLEvent.START_ELEMENT : writeStartElement(event.asStartElement(), false, writer); break; case XMLEvent.END_ELEMENT : writeEndElement(event.asEndElement(), writer); break; case XMLEvent.CHARACTERS : case XMLEvent.SPACE : case XMLEvent.CDATA : writeCharacters(event.asCharacters(), writer); break; case XMLEvent.COMMENT : writeComment((Comment) event, writer); break; case XMLEvent.ENTITY_REFERENCE : writeEntityReference((EntityReference) event, writer); break; case XMLEvent.PROCESSING_INSTRUCTION : writeProcessingInstruction((ProcessingInstruction) event, writer); break; case XMLEvent.DTD : writeDTD((DTD) event, writer); break; case XMLEvent.START_DOCUMENT : writeStartDocument((StartDocument) event, writer); break; case XMLEvent.END_DOCUMENT : writeEndDocument((EndDocument) event, writer); break; case XMLEvent.NAMESPACE : writeNamespace((Namespace) event, writer); break; case XMLEvent.ATTRIBUTE : writeAttribute((Attribute) event, writer); break; case XMLEvent.ENTITY_DECLARATION : writeEntityDeclaration((EntityDeclaration) event, writer); break; case XMLEvent.NOTATION_DECLARATION : writeNotationDeclaration((NotationDeclaration) event, writer); break; default : throw new IllegalArgumentException("Unrecognized event (" + XMLStreamUtils.getEventTypeName(eventType) + "): " + event); } } /** * Writes a {@link StartDocument} to the provided stream. * * @param start The {@link StartDocument} to write. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeStartDocument(StartDocument start, Writer writer) throws IOException { String version = start.getVersion(); String encoding = start.getCharacterEncodingScheme(); if (start.standaloneSet()) { writeStartDocument(version, encoding, start.isStandalone(), writer); } else { writeStartDocument(version, encoding, writer); } } /** * Writes a default XML declaration to the provided stream. * * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeStartDocument(Writer writer) throws IOException { writeStartDocument("1.0", null, null, writer); } /** * Writes an XML declaration to the provided stream. * * @param version The xml version definition. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeStartDocument(String version, Writer writer) throws IOException { writeStartDocument(version, null, null, writer); } /** * Writes an XML declaration to the provided stream. * * @param version The xml version definition. * @param encoding The document encoding, or null * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeStartDocument(String version, String encoding, Writer writer) throws IOException { writeStartDocument(version, encoding, null, writer); } /** * Writes an XML declaration to the provided stream. * * @param version The xml version definition. * @param encoding The document encoding, or null * @param standalone The standalone definition * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeStartDocument(String version, String encoding, boolean standalone, Writer writer) throws IOException { writeStartDocument(version, encoding, (standalone ? "yes" : "no"), writer); } /** * Writes an XML declaration to the provided stream. * * @param version The xml version definition. * @param encoding The document encoding, or null * @param standalone The standalone definition, or null * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeStartDocument(String version, String encoding, String standalone, Writer writer) throws IOException { writer.write(""); } /** * Writes an {@link EndDocument} to the provided stream. * * @param end The {@link EndDocument} to write. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeEndDocument(EndDocument end, Writer writer) throws IOException { writeEndDocument(writer); } /** * Writes an document ending to the provided stream. * * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeEndDocument(Writer writer) throws IOException { // nothing to write? } /** * Writes a {@link StartElement} event to the provided stream. * * @param start The {@link StartElement} event to write. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. * @throws XMLStreamException If an error occurs writing any namespaces or * attribute events. */ public static final void writeStartElement(StartElement start, Writer writer) throws IOException, XMLStreamException { writeStartElement(start.getName(), start.getAttributes(), start.getNamespaces(), false, writer); } /** * Writes a {@link StartElement} event to the provided stream. * * @param start The {@link StartElement} event to write. * @param empty Whether the element is empty. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. * @throws XMLStreamException If an error occurs writing any namespaces or * attribute events. */ public static final void writeStartElement(StartElement start, boolean empty, Writer writer) throws IOException, XMLStreamException { writeStartElement(start.getName(), start.getAttributes(), start.getNamespaces(), empty, writer); } /** * Writes a start tag and any associated namespaces and attributes to the * provided stream. * * @param name The tag name. * @param attributes An {@link Attribute} iterator, or null. * @param namespaces A {@link Namespace} iterator, or null. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. * @throws XMLStreamException If an error occurs writing any namespaces or * attribute events. */ public static final void writeStartElement(QName name, Iterator attributes, Iterator namespaces, Writer writer) throws IOException, XMLStreamException { writeStartElement(name, attributes, namespaces, false, writer); } /** * Writes a start tag and any associated namespaces and attributes to the * provided stream. * * @param name The tag name. * @param attributes An {@link Attribute} iterator, or null. * @param namespaces A {@link Namespace} iterator, or null. * @param empty Whether the element is empty. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. * @throws XMLStreamException */ public static final void writeStartElement(QName name, Iterator attributes, Iterator namespaces, boolean empty, Writer writer) throws IOException, XMLStreamException { writer.write('<'); XMLWriterUtils.writeQName(name, writer); // send namespaces if (namespaces != null) { while (namespaces.hasNext()) { Namespace ns = (Namespace) namespaces.next(); writer.write(' '); ns.writeAsEncodedUnicode(writer); } } // write attributes if (attributes != null) { while (attributes.hasNext()) { Attribute attr = (Attribute) attributes.next(); writer.write(' '); attr.writeAsEncodedUnicode(writer); } } if (empty) { writer.write("/>"); } else { writer.write('>'); } } /** * Writes a start tag and any associated namespaces and attributes to the * provided stream. * * @param name The tag name. * @param attributes A {@link Map} of attribute values, keyed by their * {@link QName}s. If no attributes are present, this may be null. * @param namespaces A {@link Map} of namespace values, keyed by their * prefixes. If no namespaces are present, this may be null. * @param empty Whether the element is empty. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeStartElement(QName name, Map attributes, Map namespaces, boolean empty, Writer writer) throws IOException { writer.write('<'); XMLWriterUtils.writeQName(name, writer); // send namespaces if (namespaces != null) { for (Iterator i = namespaces.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); writer.write(' '); writeNamespace((String) entry.getKey(), (String) entry.getValue(), writer); } } // write attributes if (attributes != null) { for (Iterator i = attributes.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); writer.write(' '); writeAttribute((QName) entry.getKey(), (String) entry.getValue(), writer); } } if (empty) { writer.write("/>"); } else { writer.write('>'); } } /** * Writes an {@link Attribute} to the provided stream. * * @param attr The {@link Attribute} to write. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeAttribute(Attribute attr, Writer writer) throws IOException { QName name = attr.getName(); String value = attr.getValue(); writeAttribute(name, value, writer); } /** * Writes an attribute to the provided stream. * * @param name The attribute name. * @param value The attribute value. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeAttribute(QName name, String value, Writer writer) throws IOException { XMLWriterUtils.writeQName(name, writer); writer.write('='); XMLWriterUtils.writeEncodedQuotedValue(value, writer); } /** * Writes a {@link Namespace} to the provided stream. * * @param ns The {@link Namespace} to write. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeNamespace(Namespace ns, Writer writer) throws IOException { String prefix = ns.getPrefix(); String uri = ns.getNamespaceURI(); writeNamespace(prefix, uri, writer); } /** * Writes a {@link Namespace} to the provided stream. * * @param prefix The namespace prefix, which may be null. * @param uri The namespace uri. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeNamespace(String prefix, String uri, Writer writer) throws IOException { writer.write("xmlns"); if (prefix != null && prefix.length() > 0) { writer.write(':'); writer.write(prefix); } writer.write('='); XMLWriterUtils.writeEncodedQuotedValue(uri, writer); } /** * Writes an {@link EndElement} to the provided stream. * * @param end The {@link EndElement} to write. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeEndElement(EndElement end, Writer writer) throws IOException { writeEndElement(end.getName(), writer); } /** * Writes an element end tag to the provided stream. * * @param name The element name. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeEndElement(QName name, Writer writer) throws IOException { writer.write("'); } /** * Writes a {@link Characters} to the provided stream. * * @param chars The {@link Characters} to write. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeCharacters(Characters chars, Writer writer) throws IOException { if (chars.isCData()) { writeCData(chars.getData(), writer); } else { writeCharacters(chars.getData(), writer); } } /** * Writes a chunk of encoded text to the provided stream. * * @param text The text to write. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeCharacters(CharSequence text, Writer writer) throws IOException { XMLWriterUtils.writeEncodedText(text, writer); } /** * Writes a chunk of encoded text to the provided stream. * * @param data A character array containing the characters. * @param start The starting index into the array. * @param length The number of characters to write. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeCharacters(char[] data, int start, int length, Writer writer) throws IOException { XMLWriterUtils.writeEncodedText(data, start, length, writer); } /** * Writes a {@link Characters} to the provided stream. * * @param text The CData text to write. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeCData(String text, Writer writer) throws IOException { writer.write(""); } /** * Writes a {@link Characters} to the provided stream. * * @param data A character array containing the cdata text. * @param start The starting index into the array. * @param length The number of characters to write. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeCData(char[] data, int start, int length, Writer writer) throws IOException { writer.write(""); } /** * Writes a {@link Comment} to the provided stream. * * @param comment The {@link Comment} to write. * @param writer The destination stream. * @throws XMLStreamException If an error occurs writing to the stream. */ public static final void writeComment(Comment comment, Writer writer) throws IOException { writeComment(comment.getText(), writer); } /** * Writes a comment to the provided stream. * * @param comment The comment text. * @param writer The destination stream. * @throws XMLStreamException If an error occurs writing to the stream. */ public static final void writeComment(String comment, Writer writer) throws IOException { writer.write(""); } /** * Writes an {@link EntityReference} to the provided stream. * * @param entityRef The {@link EntityReference} to write. * @param writer The destination stream. * @throws XMLStreamException If an error occurs writing to the stream. */ public static final void writeEntityReference(EntityReference entityRef, Writer writer) throws IOException { writeEntityReference(entityRef.getName(), writer); } /** * Writes an entity reference to the provided stream. * * @param entityRef The name of the entity reference. * @param writer The destination stream. * @throws XMLStreamException If an error occurs writing to the stream. */ public static final void writeEntityReference(String entityRef, Writer writer) throws IOException { writer.write('&'); writer.write(entityRef); writer.write(';'); } /** * Writes an {@link EntityDeclaration} to the stream. * * @param declaration The {@link EntityDeclaration} to write. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeEntityDeclaration(EntityDeclaration declaration, Writer writer) throws IOException { String name = declaration.getName(); String notation = declaration.getNotationName(); String text = declaration.getReplacementText(); if (text != null) { writeEntityDeclaration(name, text, notation, writer); } else { String publicId = declaration.getPublicId(); String systemId = declaration.getSystemId(); writeEntityDeclaration(name, publicId, systemId, notation, writer); } } /** * Writes an external entity declaration to the stream. Either or both of the * publicId and systemId parameters must be * non-null. * * @param name The entity name. * @param publicId The entity public ID, or null. * @param systemId The entity system ID, or null. * @param notation The notation name, or null. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeEntityDeclaration(String name, String publicId, String systemId, String notation, Writer writer) throws IOException { writer.write(""); } /** * Writes an internal entity declaration to the stream. * * @param name The entity name. * @param text The entity replacement text. * @param notation The notation name, or null. * @param writer * @throws IOException */ public static final void writeEntityDeclaration(String name, String text, String notation, Writer writer) throws IOException { writer.write(""); } /** * Writes a {@link NotationDeclaration} to the stream. * * @param declaration The {@link NotationDeclaration} to write. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeNotationDeclaration( NotationDeclaration declaration, Writer writer) throws IOException { String name = declaration.getName(); String publicId = declaration.getPublicId(); String systemId = declaration.getSystemId(); writeNotationDeclaration(name, publicId, systemId, writer); } /** * Writes a notation declaration to the stream. Either or both of the * publicId and systemId parameters must be * non-null. * * @param name The notation name. * @param publicId The entity public ID, or null. * @param systemId The entity system ID, or null. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeNotationDeclaration(String name, String publicId, String systemId, Writer writer) throws IOException { writer.write(""); } /** * Writes a {@link ProcessingInstruction} to the provided stream. * * @param procInst The {@link ProcessingInstruction} to write. * @param writer The destination stream. * @throws XMLStreamException If an error occurs writing to the stream. */ public static final void writeProcessingInstruction( ProcessingInstruction procInst, Writer writer) throws IOException { writeProcessingInstruction(procInst.getTarget(), procInst.getData(), writer); } /** * Writes a {@link ProcessingInstruction} to the provided stream. * * @param target The instruction target. * @param data The instruction data, or null. * @param writer The destination stream. * @throws XMLStreamException If an error occurs writing to the stream. */ public static final void writeProcessingInstruction(String target, String data, Writer writer) throws IOException { writer.write(""); } /** * Writes a {@link DTD} to the provided stream. * * @param dtd The {@link DTD} to write. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeDTD(DTD dtd, Writer writer) throws IOException { writeDTD(dtd, writer); } /** * Writes a dtd to the provided stream. * * @param dtd The dtd to write. * @param writer The destination stream. * @throws IOException If an error occurs writing to the stream. */ public static final void writeDTD(String dtd, Writer writer) throws IOException { writer.write(dtd); } /** * Writes the given event to the provided {@link XMLStreamWriter}. This method * will delegate the actual task of writing to the stream to the appropriate * overloaded method. * * @param event The event to write. * @param writer The destination XML stream. * @throws XMLStreamException If an error occurs writing the event. */ public static final void writeEvent(XMLEvent event, XMLStreamWriter writer) throws XMLStreamException { int eventType = event.getEventType(); switch (eventType) { case XMLEvent.START_ELEMENT : writeStartElement(event.asStartElement(), false, writer); break; case XMLEvent.END_ELEMENT : writeEndElement(event.asEndElement(), writer); break; case XMLEvent.CHARACTERS : case XMLEvent.SPACE : case XMLEvent.CDATA : writeCharacters(event.asCharacters(), writer); break; case XMLEvent.COMMENT : writeComment((Comment) event, writer); break; case XMLEvent.ENTITY_REFERENCE : writeEntityReference((EntityReference) event, writer); break; case XMLEvent.PROCESSING_INSTRUCTION : writeProcessingInstruction((ProcessingInstruction) event, writer); break; case XMLEvent.DTD : writeDTD((DTD) event, writer); break; case XMLEvent.START_DOCUMENT : writeStartDocument((StartDocument) event, writer); break; case XMLEvent.END_DOCUMENT : writeEndDocument((EndDocument) event, writer); break; case XMLEvent.NAMESPACE : writeNamespace((Namespace) event, writer); break; case XMLEvent.ATTRIBUTE : writeAttribute((Attribute) event, writer); break; default : throw new XMLStreamException("Unrecognized event (" + XMLStreamUtils.getEventTypeName(eventType) + "): " + event); } } /** * Writes a {@link StartElement} event to the provided stream. * * @param start The {@link StartElement} event to write. * @param empty Whether the element is empty. * @param writer The destination stream. * @throws XMLStreamException If an error occurs writing to the stream. */ public static final void writeStartElement(StartElement start, boolean empty, XMLStreamWriter writer) throws XMLStreamException { QName name = start.getName(); String nsURI = name.getNamespaceURI(); String localName = name.getLocalPart(); String prefix = name.getPrefix(); if (prefix != null && prefix.length() > 0) { if (empty) { writer.writeEmptyElement(prefix, localName, nsURI); } else { writer.writeStartElement(prefix, localName, nsURI); } } else if (nsURI != null && nsURI.length() > 0) { if (empty) { writer.writeEmptyElement(nsURI, localName); } else { writer.writeStartElement(nsURI, localName); } } else { if (empty) { writer.writeEmptyElement(localName); } else { writer.writeStartElement(localName); } } // send namespaces first Iterator nsIter = start.getNamespaces(); while (nsIter.hasNext()) { Namespace ns = (Namespace) nsIter.next(); writeNamespace(ns, writer); } // write attributes Iterator attrIter = start.getAttributes(); while (attrIter.hasNext()) { Attribute attr = (Attribute) attrIter.next(); writeAttribute(attr, writer); } } /** * Writes an {@link EndElement} to the provided stream. * * @param end The {@link EndElement} to write. * @param writer The destination stream. * @throws XMLStreamException If an error occurs writing to the stream. */ public static final void writeEndElement(EndElement end, XMLStreamWriter writer) throws XMLStreamException { writer.writeEndElement(); } /** * Writes an {@link Attribute} to the provided stream. * * @param attr The {@link Attribute} to write. * @param writer The destination stream. * @throws XMLStreamException If an error occurs writing to the stream. */ public static final void writeAttribute(Attribute attr, XMLStreamWriter writer) throws XMLStreamException { QName name = attr.getName(); String nsURI = name.getNamespaceURI(); String localName = name.getLocalPart(); String prefix = name.getPrefix(); String value = attr.getValue(); if (prefix != null) { writer.writeAttribute(prefix, nsURI, localName, value); } else if (nsURI != null) { writer.writeAttribute(nsURI, localName, value); } else { writer.writeAttribute(localName, value); } } /** * Writes a {@link Namespace} to the provided stream. * * @param ns The {@link Namespace} to write. * @param writer The destination stream. * @throws XMLStreamException If an error occurs writing to the stream. */ public static final void writeNamespace(Namespace ns, XMLStreamWriter writer) throws XMLStreamException { if (ns.isDefaultNamespaceDeclaration()) { writer.writeDefaultNamespace(ns.getNamespaceURI()); } else { writer.writeNamespace(ns.getPrefix(), ns.getNamespaceURI()); } } /** * Writes a {@link StartDocument} to the provided stream. * * @param start The {@link StartDocument} to write. * @param writer The destination stream. * @throws XMLStreamException If an error occurs writing to the stream. */ public static final void writeStartDocument(StartDocument start, XMLStreamWriter writer) throws XMLStreamException { String version = start.getVersion(); if (start.encodingSet()) { String encoding = start.getCharacterEncodingScheme(); writer.writeStartDocument(encoding, version); } else { writer.writeStartDocument(version); } } /** * Writes an {@link EndDocument} to the provided stream. * * @param end The {@link EndDocument} to write. * @param writer The destination stream. * @throws XMLStreamException If an error occurs writing to the stream. */ public static final void writeEndDocument(EndDocument end, XMLStreamWriter writer) throws XMLStreamException { writer.writeEndDocument(); } /** * Writes a {@link Characters} to the provided stream. * * @param chars The {@link Characters} to write. * @param writer The destination stream. * @throws XMLStreamException If an error occurs writing to the stream. */ public static final void writeCharacters(Characters chars, XMLStreamWriter writer) throws XMLStreamException { if (chars.isCData()) { writer.writeCData(chars.getData()); } else { writer.writeCharacters(chars.getData()); } } /** * Writes a {@link Comment} to the provided stream. * * @param comment The {@link Comment} to write. * @param writer The destination stream. * @throws XMLStreamException If an error occurs writing to the stream. */ public static final void writeComment(Comment comment, XMLStreamWriter writer) throws XMLStreamException { writer.writeComment(comment.getText()); } /** * Writes an {@link EntityReference} to the provided stream. * * @param entityRef The {@link EntityReference} to write. * @param writer The destination stream. * @throws XMLStreamException If an error occurs writing to the stream. */ public static final void writeEntityReference(EntityReference entityRef, XMLStreamWriter writer) throws XMLStreamException { writer.writeEntityRef(entityRef.getName()); } /** * Writes a {@link ProcessingInstruction} to the provided stream. * * @param procInst The {@link ProcessingInstruction} to write. * @param writer The destination stream. * @throws XMLStreamException If an error occurs writing to the stream. */ public static final void writeProcessingInstruction( ProcessingInstruction procInst, XMLStreamWriter writer) throws XMLStreamException { String data = procInst.getData(); if (data != null) { writer.writeProcessingInstruction(procInst.getTarget(), data); } else { writer.writeProcessingInstruction(procInst.getTarget()); } } /** * Writes a {@link DTD} to the provided stream. * * @param dtd The {@link DTD} to write. * @param writer The destination stream. * @throws XMLStreamException If an error occurs writing to the stream. */ public static final void writeDTD(DTD dtd, XMLStreamWriter writer) throws XMLStreamException { writer.writeDTD(dtd.getDocumentTypeDeclaration()); } }src/javanet/staxutils/io/StAXStreamWriter.java0000644000175000017500000004440010075364334020552 0ustar tonytony/* * $Id: StAXStreamWriter.java,v 1.1 2004-07-15 02:15:56 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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.io; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import javanet.staxutils.helpers.ElementContext; import javax.xml.namespace.NamespaceContext; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; /** * An {@link XMLStreamWriter} implementation that writes to a character stream. * * @author Christian Niles * @version $Revision: 1.1 $ */ public class StAXStreamWriter implements XMLStreamWriter { /** The destination stream. */ private Writer writer; /** Whether the stream has been closed or not. */ private boolean closed; /** The root namespace context. */ private NamespaceContext rootContext; /** The current {@link ElementContext}. used to keep track of opened elements. */ private ElementContext elementContext; /** * Constructs a StAXStreamWriter that writes to the provided * {@link OutputStream} using the platform default encoding. * * @param stream The destination stream. */ public StAXStreamWriter(OutputStream stream) { this(new OutputStreamWriter(stream)); } /** * Constructs a StAXStreamWriter that writes to the provided * {@link OutputStream} using the specified encoding. * * @param stream The destination stream. * @param encoding The output encoding. * @throws UnsupportedEncodingException If the encoding isn't supported. */ public StAXStreamWriter(OutputStream stream, String encoding) throws UnsupportedEncodingException { this(new OutputStreamWriter(stream, encoding)); } /** * Constructs a StAXStreamWriter that writes to the provided * {@link Writer}. * * @param writer The destination {@link Writer} instance. */ public StAXStreamWriter(Writer writer) { this.writer = writer; } /** * Constructs a StAXStreamWriter that writes to the provided * {@link Writer}. * * @param writer The destination {@link Writer} instance. * @param rootContext The root namespace context. */ public StAXStreamWriter(Writer writer, NamespaceContext rootContext) { this.writer = writer; this.rootContext = rootContext; } public synchronized void close() throws XMLStreamException { if (!closed) { flush(); closed = true; writer = null; } } public synchronized void flush() throws XMLStreamException { // if cached element info exists, send it closeElementContext(); try { writer.flush(); } catch (IOException e) { throw new XMLStreamException(e); } } public String getPrefix(String uri) throws XMLStreamException { return getNamespaceContext().getPrefix(uri); } public Object getProperty(String name) throws IllegalArgumentException { // TODO provide access to properties? throw new IllegalArgumentException(name + " property not supported"); } public void writeStartDocument() throws XMLStreamException { try { XMLWriterUtils.writeStartDocument(writer); } catch (IOException e) { throw new XMLStreamException(e); } } public void writeStartDocument(String version) throws XMLStreamException { try { XMLWriterUtils.writeStartDocument(version, writer); } catch (IOException e) { throw new XMLStreamException(e); } } public synchronized void writeStartDocument(String encoding, String version) throws XMLStreamException { // TODO perform check that StartDocument can be entered try { XMLWriterUtils.writeStartDocument(version, encoding, writer); } catch (IOException e) { throw new XMLStreamException(e); } } public synchronized void writeEndDocument() throws XMLStreamException { // flush any cached start element content closeElementContext(); // close any tags while (elementContext != null) { writeEndElement(); } } public synchronized void writeCData(String data) throws XMLStreamException { if (data == null) { throw new IllegalArgumentException("CDATA argument was null"); } // flush any cached start element content closeElementContext(); // TODO verify data is appropriate for CDATA try { XMLWriterUtils.writeCData(data, writer); } catch (IOException e) { throw new XMLStreamException(e); } } public synchronized void writeCharacters(char[] text, int start, int len) throws XMLStreamException { if (text == null) { throw new IllegalArgumentException( "Character text argument was null"); } // flush any cached start element content closeElementContext(); try { XMLWriterUtils.writeCharacters(text, start, len, writer); } catch (IOException e) { throw new XMLStreamException(e); } } public synchronized void writeCharacters(String text) throws XMLStreamException { if (text == null) { throw new IllegalArgumentException( "Character text argument was null"); } // flush any cached start element content closeElementContext(); try { XMLWriterUtils.writeCharacters(text, writer); } catch (IOException e) { throw new XMLStreamException(e); } } public synchronized void writeComment(String data) throws XMLStreamException { if (data == null) { throw new IllegalArgumentException("Comment data argument was null"); } // flush any cached start element content closeElementContext(); // TODO check comment for non-SGML compatible characters? try { XMLWriterUtils.writeComment(data, writer); } catch (IOException e) { throw new XMLStreamException(e); } } public synchronized void writeDTD(String dtd) throws XMLStreamException { if (dtd == null) { throw new IllegalArgumentException("dtd argument was null"); } try { XMLWriterUtils.writeDTD(dtd, writer); } catch (IOException e) { throw new XMLStreamException(e); } } public synchronized void writeEntityRef(String name) throws XMLStreamException { // flush any cached start element content closeElementContext(); try { XMLWriterUtils.writeEntityReference(name, writer); } catch (IOException e) { throw new XMLStreamException(e); } } public synchronized void writeProcessingInstruction(String target, String data) throws XMLStreamException { // flush any cached start element content closeElementContext(); // TODO test processing instruction validity? try { XMLWriterUtils.writeProcessingInstruction(target, data, writer); } catch (IOException e) { throw new XMLStreamException(e); } } public void writeProcessingInstruction(String target) throws XMLStreamException { writeProcessingInstruction(target, null); } public NamespaceContext getNamespaceContext() { return elementContext; } public void setNamespaceContext(NamespaceContext context) throws XMLStreamException { if (this.rootContext == null && elementContext == null) { this.rootContext = context; } else { throw new IllegalStateException( "NamespaceContext has already been set or document is already in progress"); } } public synchronized void setDefaultNamespace(String uri) throws XMLStreamException { elementContext.putNamespace("", uri); } public synchronized void setPrefix(String prefix, String uri) throws XMLStreamException { elementContext.putNamespace(prefix, uri); } /** * Core start tag output method called by all other writeXXXElement * methods. * * @param prefix The tag prefix. * @param localName The tag local name. * @param namespaceURI The namespace URI of the prefix. * @param isEmpty Whether the tag is empty. * @throws XMLStreamException If an error occurs writing the tag to the stream. */ public synchronized void writeStartElement(String prefix, String localName, String namespaceURI, boolean isEmpty) throws XMLStreamException { if (prefix == null) { throw new IllegalArgumentException("prefix may not be null @ [" + getCurrentPath() + "]"); } else if (localName == null) { throw new IllegalArgumentException("localName may not be null @ [" + getCurrentPath() + "]"); } else if (namespaceURI == null) { throw new IllegalArgumentException( "namespaceURI may not be null @ [" + getCurrentPath() + "]"); } // new context is beginning; close the current context if needed if (elementContext != null) { closeElementContext(); // test if we just closed an empty root context if (elementContext == null) { throw new XMLStreamException( "Writing start tag after close of root element"); } } // create the new context QName name = new QName(namespaceURI, localName, prefix); elementContext = new ElementContext(name, elementContext, isEmpty); } public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { writeStartElement(prefix, localName, namespaceURI, false); } public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { writeStartElement("", localName, namespaceURI, false); } public void writeStartElement(String localName) throws XMLStreamException { writeStartElement("", localName, "", false); } public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { writeStartElement(prefix, localName, namespaceURI, true); } public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { writeStartElement("", localName, namespaceURI, true); } public void writeEmptyElement(String localName) throws XMLStreamException { writeStartElement("", localName, "", true); } public synchronized void writeAttribute(QName name, String value) throws XMLStreamException { if (elementContext == null || elementContext.isReadOnly()) { throw new XMLStreamException( getCurrentPath() + ": attributes must be written directly following a start element."); } elementContext.putAttribute(name, value); } public void writeAttribute(String prefix, String namespaceURI, String localName, String value) throws XMLStreamException { if (prefix == null) { throw new IllegalArgumentException( "attribute prefix may not be null @ [" + getCurrentPath() + "]"); } else if (localName == null) { throw new IllegalArgumentException( "attribute localName may not be null @ [" + getCurrentPath() + "]"); } else if (namespaceURI == null) { throw new IllegalArgumentException( "attribute namespaceURI may not be null @ [" + getCurrentPath() + "]"); } writeAttribute(new QName(namespaceURI, localName, prefix), value); } public void writeAttribute(String namespaceURI, String localName, String value) throws XMLStreamException { writeAttribute("", namespaceURI, localName, value); } public void writeAttribute(String localName, String value) throws XMLStreamException { writeAttribute("", "", localName, value); } public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { writeNamespace("", namespaceURI); } public synchronized void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { if (prefix == null) { throw new IllegalArgumentException( "Namespace prefix may not be null @ [" + getCurrentPath() + "]"); } else if (namespaceURI == null) { throw new IllegalArgumentException( "Namespace URI may not be null @ [" + getCurrentPath() + "]"); } if (elementContext != null && !elementContext.isReadOnly()) { elementContext.putNamespace(prefix, namespaceURI); } else { throw new XMLStreamException( getCurrentPath() + ": Namespaces must be written directly following a start tag"); } } public synchronized void writeEndElement() throws XMLStreamException { // flush any cached start element content closeElementContext(); if (elementContext != null) { QName name = elementContext.getName(); try { XMLWriterUtils.writeEndElement(name, writer); } catch (IOException e) { throw new XMLStreamException(getCurrentPath() + ": Error writing end element to stream", e); } // pop the context elementContext = elementContext.getParentContext(); } else { throw new XMLStreamException("Unmatched END_ELEMENT"); } } /** * Returns the current position of the writer as a path of {@link QName} strings. * * @return The current position of the writer. */ public synchronized String getCurrentPath() { if (elementContext == null) { return "/"; } else { return elementContext.getPath(); } } /** * Closes the current {@link ElementContext}, writing any cached content and * making it read-only. If the current context is empty, it will be popped and * replaced with its parent context. If no context is open, this method has no * effects. * * @throws XMLStreamException If an error occurs flushing any element content. */ protected void closeElementContext() throws XMLStreamException { if (elementContext != null && !elementContext.isReadOnly()) { elementContext.setReadOnly(); // it hasn't been closed yet, so write it try { writer.write('<'); XMLWriterUtils.writeQName(elementContext.getName(), writer); for (int i = 0, s = elementContext.attributeCount(); i < s; i++) { QName name = elementContext.getAttributeName(i); String value = elementContext.getAttribute(i); writer.write(' '); XMLWriterUtils.writeAttribute(name, value, writer); } for (int i = 0, s = elementContext.namespaceCount(); i < s; i++) { String prefix = elementContext.getNamespacePrefix(i); String uri = elementContext.getNamespaceURI(i); writer.write(' '); XMLWriterUtils.writeNamespace(prefix, uri, writer); } if (elementContext.isEmpty()) { writer.write("/>"); elementContext = elementContext.getParentContext(); } else { writer.write('>'); } } catch (IOException e) { throw new XMLStreamException(getCurrentPath() + ": error writing start tag to stream", e); } } } }src/javanet/staxutils/io/package.html0000644000175000017500000000061310074545702016775 0ustar tonytony stax-utils I/O Package Utilities for reading and writing XML from various sources. src/javanet/staxutils/BaseXMLStreamReader.java0000644000175000017500000002147110075370466020513 0ustar tonytony/* * $Id: BaseXMLStreamReader.java,v 1.2 2004-07-15 02:51:32 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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 javanet.staxutils.SimpleLocation; import javanet.staxutils.StaticLocation; import javanet.staxutils.XMLStreamUtils; import javanet.staxutils.error.IllegalStreamStateException; import javax.xml.namespace.QName; import javax.xml.stream.Location; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; /** * Abstract base class for {@link XMLStreamReader} implementations. * * @author Christian Niles * @version $Revision: 1.2 $ */ public abstract class BaseXMLStreamReader implements XMLStreamReader { /** The stream system ID. */ protected String systemId; /** The stream encoding. */ protected String encoding; public BaseXMLStreamReader() { } public BaseXMLStreamReader(String systemId, String encoding) { this.systemId = systemId; this.encoding = encoding; } public String getSystemId() { return systemId; } public String getEncoding() { return encoding; } /** * Returns the name of the current event type. * * @return The name of the current event type. */ public String getEventTypeName() { return XMLStreamUtils.getEventTypeName(getEventType()); } public int nextTag() throws XMLStreamException { for (int eventType = next(); hasNext(); eventType = next()) { switch (eventType) { case START_ELEMENT : case END_ELEMENT : return eventType; case CHARACTERS : case CDATA : if (!isWhiteSpace()) { // throw an error break; } else { // fall through } case SPACE : case PROCESSING_INSTRUCTION : case COMMENT : // skip it continue; default : // stop and throw an error break; } } throw new XMLStreamException("Encountered " + getEventTypeName() + " when expecting START_ELEMENT or END_ELEMENT", getStableLocation()); } public boolean isCharacters() { return getEventType() == XMLStreamConstants.CHARACTERS; } public boolean isEndElement() { return getEventType() == XMLStreamConstants.END_ELEMENT; } public boolean isStartElement() { return getEventType() == XMLStreamConstants.START_ELEMENT; } public boolean isWhiteSpace() { return getEventType() == XMLStreamConstants.SPACE; } public boolean hasName() { switch (getEventType()) { case XMLStreamConstants.START_ELEMENT : case XMLStreamConstants.END_ELEMENT : return true; default : return false; } } public String getPrefix() { switch (getEventType()) { case XMLStreamConstants.START_ELEMENT : case XMLStreamConstants.END_ELEMENT : return getName().getPrefix(); default : throw new IllegalStreamStateException( "Expected START_ELEMENT or END_ELEMENT but was " + getEventTypeName(), getStableLocation()); } } public boolean hasText() { switch (getEventType()) { case XMLStreamConstants.SPACE : case XMLStreamConstants.CHARACTERS : case XMLStreamConstants.COMMENT : case XMLStreamConstants.CDATA : case XMLStreamConstants.ENTITY_REFERENCE : return true; default : return false; } } public String getNamespaceURI(String prefix) { if (prefix == null) { throw new IllegalArgumentException("Namespace prefix was null"); } return getNamespaceContext().getNamespaceURI(prefix); } public String getNamespaceURI() { switch (getEventType()) { case XMLStreamConstants.START_ELEMENT : case XMLStreamConstants.END_ELEMENT : return getName().getNamespaceURI(); default : throw new IllegalStreamStateException( "Expected START_ELEMENT or END_ELEMENT state, but found " + getEventTypeName(), getStableLocation()); } } public String getAttributeLocalName(int index) { return getAttributeName(index).getLocalPart(); } public String getAttributeNamespace(int index) { return getAttributeName(index).getNamespaceURI(); } public String getAttributePrefix(int index) { return getAttributeName(index).getPrefix(); } public void require(int type, String namespaceURI, String localName) throws XMLStreamException { int currType = getEventType(); if (currType != type) { throw new XMLStreamException("Expected " + XMLStreamUtils.getEventTypeName(type) + " but found " + XMLStreamUtils.getEventTypeName(currType), getStableLocation()); } } public String getElementText() throws XMLStreamException { if (getEventType() != XMLStreamConstants.START_ELEMENT) { throw new XMLStreamException("Expected START_ELEMENT but found " + getEventTypeName(), getStableLocation()); } // save the element name and location so we can use it in the error message // as needed. QName elemName = getName(); Location elemLocation = getStableLocation(); // read text events until the end tag is reached StringBuffer content = null; for (int eventType = next(); eventType != END_ELEMENT; eventType = next()) { if (hasText()) { if (content == null) { content = new StringBuffer(); } content.append(getText()); } else { throw new XMLStreamException("Encountered " + getEventTypeName() + " event within text-only element " + elemName, elemLocation); } } // return content return (content == null ? "" : content.toString()); } /** * Constructs a new, stable {@link Location} from the current stream location. * If the stream location implements {@link StaticLocation}, then the stream * location will be returned directly. * * @return Constructs a new, stable {@link Location} from the current stream * location, or the current {@link Location} itself if it is already * stable. */ public Location getStableLocation() { Location location = getLocation(); if (!(location instanceof StaticLocation)) { // create copy location = new SimpleLocation(location); } return location; } }src/javanet/staxutils/StaticNamespaceContext.java0000644000175000017500000000415411535774174021377 0ustar tonytony/* * $Id: StaticNamespaceContext.java,v 1.1 2004-07-08 14:29:42 cniles Exp $ * * Copyright (c) 2004, Christian Niles, Unit12 * 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 Christian Niles, Unit12, 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 javax.xml.namespace.NamespaceContext; /** * Marker interface used to denote {@link NamespaceContext} implementations whose * state is not transient or dependent on external objects/events and will remain * stable unless explicitly updated. * * @author Christian Niles * @version $Revision: 1.1 $ */ public interface StaticNamespaceContext extends NamespaceContext { } src/javanet/staxutils/StAXContentHandler.java0000644000175000017500000001652410043536334020425 0ustar tonytony/* * $Id: StAXContentHandler.java,v 1.3 2004-04-27 20:04:42 cniles Exp $ * * Copyright (c) 2004, Christian Niles, Unit12 * 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 Christian Niles, Unit12, 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 javax.xml.stream.Location; import javax.xml.stream.XMLReporter; import javax.xml.stream.XMLStreamException; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.DefaultHandler; /** * Base class for SAX-to-STAX bridge classes that provides common * functionality. * * @author Christian Niles * @version $Revision: 1.3 $ */ public abstract class StAXContentHandler extends DefaultHandler implements LexicalHandler { /** * Whether the parser is currently within a CDATA section. */ protected boolean isCDATA; /** * Buffer containing text read within the current CDATA section. */ protected StringBuffer CDATABuffer; /** * Stack used to store declared namespaces. */ protected SimpleNamespaceContext namespaces; /** * The SAX {@link Locator}provided to the handler. */ protected Locator docLocator; /** * The STAX {@link XMLReporter}registered to receive notifications. */ protected XMLReporter reporter; public StAXContentHandler() { } public StAXContentHandler(XMLReporter reporter) { this.reporter = reporter; } /** * Sets the {@link XMLReporter}to which warning and error messages will be * sent. * * @param reporter The {@link XMLReporter}to notify of errors. */ public void setXMLReporter(XMLReporter reporter) { this.reporter = reporter; } public void setDocumentLocator(Locator locator) { this.docLocator = locator; } /** * Calculates the STAX {@link Location}from the SAX {@link Locator} * registered with this handler. If no {@link Locator}was provided, then * this method will return null. */ public Location getCurrentLocation() { if (docLocator != null) { return new SAXLocation(docLocator); } else { return null; } } public void error(SAXParseException e) throws SAXException { reportException("ERROR", e); } public void fatalError(SAXParseException e) throws SAXException { reportException("FATAL", e); } public void warning(SAXParseException e) throws SAXException { reportException("WARNING", e); } public void startDocument() throws SAXException { namespaces = new SimpleNamespaceContext(); } public void endDocument() throws SAXException { namespaces = null; } public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { namespaces = null; } public void endElement(String uri, String localName, String qName) throws SAXException { namespaces = null; } public void startPrefixMapping(String prefix, String uri) throws SAXException { if (prefix == null) { prefix = ""; } else if (prefix.equals("xml")) { return; } if (namespaces == null) { namespaces = new SimpleNamespaceContext(); } namespaces.setPrefix(prefix, uri); } public void endPrefixMapping(String prefix) throws SAXException { } public void startCDATA() throws SAXException { isCDATA = true; if (CDATABuffer == null) { CDATABuffer = new StringBuffer(); } else { CDATABuffer.setLength(0); } } public void characters(char[] ch, int start, int length) throws SAXException { if (isCDATA) { CDATABuffer.append(ch, start, length); } } public void endCDATA() throws SAXException { isCDATA = false; CDATABuffer.setLength(0); } public void comment(char[] ch, int start, int length) throws SAXException { } public void endDTD() throws SAXException { } public void endEntity(String name) throws SAXException { } public void startDTD(String name, String publicId, String systemId) throws SAXException { } public void startEntity(String name) throws SAXException { } /** * Used to report a {@link SAXException}to the {@link XMLReporter} * registered with this handler. */ protected void reportException(String type, SAXException e) throws SAXException { if (reporter != null) { try { reporter.report(e.getMessage(), type, e, getCurrentLocation()); } catch (XMLStreamException e1) { throw new SAXException(e1); } } } /** * Parses an XML qualified name, and places the resulting prefix and local * name in the provided String array. * * @param qName The qualified name to parse. * @param results An array where parse results will be placed. The prefix * will be placed at results[0], and the local * part at results[1] */ public static final void parseQName(String qName, String[] results) { String prefix, local; int idx = qName.indexOf(':'); if (idx >= 0) { prefix = qName.substring(0, idx); local = qName.substring(idx + 1); } else { prefix = ""; local = qName; } results[0] = prefix; results[1] = local; } /** * {@Link Location}implementation used to expose details from a SAX * {@link Locator}. * * @author christian * @version $Revision: 1.3 $ */ private static final class SAXLocation implements Location { private int lineNumber; private int columnNumber; private String publicId; private String systemId; private SAXLocation(Locator locator) { lineNumber = locator.getLineNumber(); columnNumber = locator.getColumnNumber(); publicId = locator.getPublicId(); systemId = locator.getSystemId(); } public int getLineNumber() { return lineNumber; } public int getColumnNumber() { return columnNumber; } public int getCharacterOffset() { return -1; } public String getPublicId() { return publicId; } public String getSystemId() { return systemId; } } } src/javanet/staxutils/StAXReaderToContentHandler.java0000644000175000017500000000556610065627662022070 0ustar tonytony/* $Id: StAXReaderToContentHandler.java,v 1.1 2004-06-21 18:57:53 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 javax.xml.stream.XMLStreamException; /** * Common API's for adapting StAX events from {@link javax.xml.stream.XMLStreamReader} * and {@link javax.xml.stream.XMLEventReader} into SAX events on the specified * {@link org.xml.sax.ContentHandler}. * * @author Ryan.Shoemaker@Sun.COM * @version 1.0 */ public interface StAXReaderToContentHandler { /** * Perform the conversion from StAX events to SAX events. * *

* The StAX parser must be pointing at the start element or the start document. * The method reads the parser until it hits the corresponding end element, * and turns the complete sub-tree into the equivalent of the SAX events. * *

* The receiver of the SAX event will see this sub-tree as if it were * a whole document. * *

* When this method returns successfully, the parser is at the next token * of the end element. * * @throws XMLStreamException * if any errors are encountered while parsing XML from the * XMLStreamReader or firing events on the ContentHandler. */ public void bridge() throws XMLStreamException; }src/javanet/staxutils/XMLStreamEventWriter.java0000644000175000017500000001120110072360500020743 0ustar tonytony/* * $Id: XMLStreamEventWriter.java,v 1.1 2004-07-05 23:16:16 cniles Exp $ * * Copyright (c) 2004, Christian Niles, Unit12 * 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 Christian Niles, Unit12, 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 javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import javanet.staxutils.events.ExtendedXMLEvent; import javanet.staxutils.io.XMLWriterUtils; /** * {@link javax.xml.stream.XMLEventWriter} that writes events to a * {@link XMLStreamWriter}. * * @author Christian Niles * @version $Revision: 1.1 $ */ public class XMLStreamEventWriter extends BaseXMLEventWriter { /** The underlying stream. */ private XMLStreamWriter writer; /** * Constructs a XMLEventStreamWriter that writes events to the * given stream. * * @param writer The {@link XMLStreamWriter} to which the events will be * written. */ public XMLStreamEventWriter(XMLStreamWriter writer) { super(null, writer.getNamespaceContext()); this.writer = writer; } public synchronized void flush() throws XMLStreamException { super.flush(); // send any cached start element if (savedStart != null) { XMLWriterUtils.writeStartElement(savedStart, false, writer); } writer.flush(); } public synchronized void close() throws XMLStreamException { super.close(); writer.close(); } /** * Saved reference to most recent start element. This is used to properly * write empty elements. Each startElement event is saved here until the * next event is received, at which point it will be written as a start or * empty element if it is followed directly by an EndElement. */ private StartElement savedStart; protected synchronized void sendEvent(XMLEvent event) throws XMLStreamException { // Check if we have a cached start tag. If we do, then we should // check if this event is actually an end tag, so we can properly // write an empty element. if (savedStart != null) { StartElement start = savedStart; savedStart = null; if (event.getEventType() == XMLEvent.END_ELEMENT) { // this end tag directly followed a start tag, so send // the underlying writer an empty start element XMLWriterUtils.writeStartElement(start, true, writer); return; } else { // element has content, so send a regular start tag XMLWriterUtils.writeStartElement(start, false, writer); } } if (event.isStartElement()) { // cache the event savedStart = event.asStartElement(); } else if (event instanceof ExtendedXMLEvent) { // let the event handle itself ((ExtendedXMLEvent) event).writeEvent(writer); } else { // write the event to the stream XMLWriterUtils.writeEvent(event, writer); } } }src/javanet/staxutils/StAXResult.java0000644000175000017500000001005710066613712016767 0ustar tonytony/* $Id: StAXResult.java,v 1.2 2004-06-24 18:04:57 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 javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLStreamWriter; import javax.xml.transform.sax.SAXResult; /** * A JAXP {@link javax.xml.transform.Result} implementation that produces * a result on the specified {@link javax.xml.stream.XMLStreamWriter} or * {@link javax.xml.stream.XMLEventWriter}. * *

* Please note that you may need to call flush() on the underlying * XMLStreamWriter or XMLEventWriter after the transform is complete. *

* * The fact that JAXBResult derives from SAXResult is an implementation * detail. Thus in general applications are strongly discouraged from * accessing methods defined on SAXResult. * *

* In particular it shall never attempt to call the following methods: * *

* *

* Example: * *

    // create a DOMSource
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(...);
    Source domSource = new DOMSource(doc);

    // create a StAXResult
    XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(System.out);
    Result staxResult = new StAXResult(writer);

    // run the transform
    TransformerFactory.newInstance().newTransformer().transform(domSource, staxResult);
 * 
* * @author Ryan.Shoemaker@Sun.COM * @version 1.0 */ public class StAXResult extends SAXResult { /** * Create a new {@link javax.xml.transform.Result} that produces * a result on the specified {@link javax.xml.stream.XMLStreamWriter} * * @param writer the XMLStreamWriter * @throws IllegalArgumentException iff the writer is null */ public StAXResult(XMLStreamWriter writer) { if( writer == null ) { throw new IllegalArgumentException(); } super.setHandler(new ContentHandlerToXMLStreamWriter( writer )); } /** * Create a new {@link javax.xml.transform.Result} that produces * a result on the specified {@link javax.xml.stream.XMLEventWriter} * * @param writer the XMLEventWriter * @throws IllegalArgumentException iff the writer is null */ public StAXResult(XMLEventWriter writer) { if( writer == null ) { throw new IllegalArgumentException(); } super.setHandler(new ContentHandlerToXMLEventWriter( writer )); } } src/javanet/staxutils/package.html0000644000175000017500000000112610074545702016366 0ustar tonytony stax-utils Root Package Provides a set of utility classes that make it easy for developers to work with JSR-173: Streaming API for XML (StAX) and integrate it into their existing XML processing applications. src/javanet/staxutils/BaseXMLOutputFactory.java0000644000175000017500000001137210075370466020764 0ustar tonytony/* * $Id: BaseXMLOutputFactory.java,v 1.2 2004-07-15 02:51:33 cniles Exp $ * * Copyright (c) 2004, Christian Niles, unit12.net * 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 Christian Niles, Unit12, 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 java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import javanet.staxutils.XMLStreamEventWriter; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import javax.xml.transform.Result; /** * Base {@link XMLOutputFactory} that provides common event functionality. * * @author Christian Niles * @version $Revision: 1.2 $ */ public abstract class BaseXMLOutputFactory extends XMLOutputFactory { public XMLEventWriter createXMLEventWriter(OutputStream stream, String encoding) throws XMLStreamException { try { return createXMLEventWriter(new OutputStreamWriter(stream, encoding)); } catch (UnsupportedEncodingException e) { throw new XMLStreamException(e); } } public XMLEventWriter createXMLEventWriter(OutputStream stream) throws XMLStreamException { return createXMLEventWriter(new OutputStreamWriter(stream)); } public XMLStreamWriter createXMLStreamWriter(OutputStream stream, String encoding) throws XMLStreamException { try { return createXMLStreamWriter(new OutputStreamWriter(stream, encoding)); } catch (UnsupportedEncodingException e) { throw new XMLStreamException(e); } } public XMLStreamWriter createXMLStreamWriter(OutputStream stream) throws XMLStreamException { return createXMLStreamWriter(new OutputStreamWriter(stream)); } public XMLEventWriter createXMLEventWriter(Result result) throws XMLStreamException { return createXMLEventWriter(createXMLStreamWriter(result)); } /** * Creates an {@link XMLEventWriter} that writes to the provided * {@link XMLStreamWriter}. * * @param writer The destination stream. * @return An {@link XMLEventWriter} that writes to the provided * {@link XMLStreamWriter}. */ public XMLEventWriter createXMLEventWriter(XMLStreamWriter writer) { return new XMLStreamEventWriter(writer); } public XMLEventWriter createXMLEventWriter(Writer stream) throws XMLStreamException { return createXMLEventWriter(createXMLStreamWriter(stream)); } public XMLStreamWriter createXMLStreamWriter(Result result) throws XMLStreamException { // FIXME Support TrAX throw new UnsupportedOperationException("TrAX result not supported"); } public Object getProperty(String name) throws IllegalArgumentException { throw new IllegalArgumentException(name + " property isn't supported"); } public boolean isPropertySupported(String name) { return false; } public void setProperty(String name, Object value) throws IllegalArgumentException { throw new IllegalArgumentException(name + " property isn't supported"); } }src/javanet/staxutils/EventHelper.java0000644000175000017500000000702210065630042017162 0ustar tonytony/* $Id: EventHelper.java,v 1.1 2004-06-21 18:59:46 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 javax.xml.namespace.QName; import javax.xml.stream.Location; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Characters; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import java.io.Writer; /** * Partial base class implementation of {@link javax.xml.stream.events.XMLEvent}. * * @author Ryan.Shoemaker@Sun.COM * @version 1.0 */ abstract class EventHelper implements XMLEvent { private final Location location; protected EventHelper(Location location) { this.location = location; } public Location getLocation() { return location; } public boolean isStartElement() { return false; } public boolean isAttribute() { return false; } public boolean isNamespace() { return false; } public boolean isEndElement() { return false; } public boolean isEntityReference() { return false; } public boolean isProcessingInstruction() { return false; } public boolean isCharacters() { return false; } public boolean isStartDocument() { return false; } public boolean isEndDocument() { return false; } public StartElement asStartElement() { throw new UnsupportedOperationException(); } public EndElement asEndElement() { throw new UnsupportedOperationException(); } public Characters asCharacters() { throw new UnsupportedOperationException(); } public QName getSchemaType() { throw new UnsupportedOperationException(); } public abstract void writeAsEncodedUnicode(Writer writer) throws XMLStreamException; public int getEventType() { throw new UnsupportedOperationException(); } } src/javanet/staxutils/XMLStreamReaderToContentHandler.java0000644000175000017500000003653310365222532023051 0ustar tonytony/* $Id: XMLStreamReaderToContentHandler.java,v 1.6 2006-01-23 18:50:02 sandoz 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 javanet.staxutils.helpers.XMLFilterImplEx; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.Location; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.AttributesImpl; /** * This is a simple utility class that adapts StAX events from an * {@link javax.xml.stream.XMLStreamReader} to SAX events on a * {@link org.xml.sax.ContentHandler}, bridging between the two * parser technologies. * * @author Ryan.Shoemaker@Sun.COM * @version 1.0 */ public class XMLStreamReaderToContentHandler implements StAXReaderToContentHandler { // StAX event source private final XMLStreamReader staxStreamReader; // SAX event sinks private XMLFilterImplEx filter; /** * Construct a new StAX to SAX adapter that will convert a StAX event * stream into a SAX event stream. * * @param staxCore * StAX event source * @param filter * SAX event sink */ public XMLStreamReaderToContentHandler(XMLStreamReader staxCore, XMLFilterImplEx filter) { staxStreamReader = staxCore; this.filter = filter; } /* * @see StAXReaderToContentHandler#bridge() */ public void bridge() throws XMLStreamException { try { // remembers the nest level of elements to know when we are done. int depth=0; boolean isDocument = false; handleStartDocument(); // if the parser is at the start document, procees any comments or PIs int event = staxStreamReader.getEventType(); if (event == XMLStreamConstants.START_DOCUMENT) { isDocument = true; event=staxStreamReader.next(); while (event != XMLStreamConstants.START_ELEMENT) { switch(event) { case XMLStreamConstants.COMMENT : handleComment(); break; case XMLStreamConstants.PROCESSING_INSTRUCTION : handlePI(); break; } event = staxStreamReader.next(); }; } if( event!=XMLStreamConstants.START_ELEMENT) throw new IllegalStateException("The current event is not START_ELEMENT\n but" + event); do { // These are all of the events listed in the javadoc for // XMLEvent. // The spec only really describes 11 of them. switch (event) { case XMLStreamConstants.START_ELEMENT : depth++; handleStartElement(); break; case XMLStreamConstants.END_ELEMENT : handleEndElement(); depth--; break; case XMLStreamConstants.CHARACTERS : handleCharacters(); break; case XMLStreamConstants.ENTITY_REFERENCE : handleEntityReference(); break; case XMLStreamConstants.PROCESSING_INSTRUCTION : handlePI(); break; case XMLStreamConstants.COMMENT : handleComment(); break; case XMLStreamConstants.DTD : handleDTD(); break; case XMLStreamConstants.ATTRIBUTE : handleAttribute(); break; case XMLStreamConstants.NAMESPACE : handleNamespace(); break; case XMLStreamConstants.CDATA : handleCDATA(); break; case XMLStreamConstants.ENTITY_DECLARATION : handleEntityDecl(); break; case XMLStreamConstants.NOTATION_DECLARATION : handleNotationDecl(); break; case XMLStreamConstants.SPACE : handleSpace(); break; default : throw new InternalError("processing event: " + event); } event=staxStreamReader.next(); } while (depth!=0); // procees any remaining comments or PIs if (isDocument) { while(event != XMLStreamConstants.END_DOCUMENT) { switch(event) { case XMLStreamConstants.COMMENT : handleComment(); break; case XMLStreamConstants.PROCESSING_INSTRUCTION : handlePI(); break; } event=staxStreamReader.next(); } } handleEndDocument(); } catch (SAXException e) { throw new XMLStreamException(e); } } private void handleEndDocument() throws SAXException { filter.endDocument(); } private void handleStartDocument() throws SAXException { final Location location = staxStreamReader.getLocation(); if (location != null) { filter.setDocumentLocator(new Locator() { public int getColumnNumber() { return location.getColumnNumber(); } public int getLineNumber() { return location.getLineNumber(); } public String getPublicId() { return location.getPublicId(); } public String getSystemId() { return location.getSystemId(); } }); } else { filter.setDocumentLocator(new DummyLocator()); } filter.startDocument(); } private void handlePI() throws XMLStreamException { try { filter.processingInstruction( staxStreamReader.getPITarget(), staxStreamReader.getPIData()); } catch (SAXException e) { throw new XMLStreamException(e); } } private void handleCharacters() throws XMLStreamException { // workaround for bugid 5046319 - switch over to commented section // below when it is fixed. int textLength = staxStreamReader.getTextLength(); int textStart = staxStreamReader.getTextStart(); char[] chars = new char[textLength]; staxStreamReader.getTextCharacters(textStart, chars, 0, textLength); try { filter.characters(chars, 0, chars.length); } catch (SAXException e) { throw new XMLStreamException(e); } // int start = 0; // int len; // do { // len = staxStreamReader.getTextCharacters(start, buf, 0, buf.length); // start += len; // try { // filter.characters(buf, 0, len); // } catch (SAXException e) { // throw new XMLStreamException(e); // } // } while (len == buf.length); } private void handleEndElement() throws XMLStreamException { QName qName = staxStreamReader.getName(); try { // fire endElement String prefix = qName.getPrefix(); String rawname; if(prefix==null || prefix.length()==0) rawname = qName.getLocalPart(); else rawname = prefix + ':' + qName.getLocalPart(); filter.endElement( qName.getNamespaceURI(), qName.getLocalPart(), rawname); // end namespace bindings int nsCount = staxStreamReader.getNamespaceCount(); for (int i = nsCount - 1; i >= 0; i--) { String nsprefix = staxStreamReader.getNamespacePrefix(i); if (nsprefix == null) { // true for default namespace nsprefix = ""; } filter.endPrefixMapping(nsprefix); } } catch (SAXException e) { throw new XMLStreamException(e); } } private void handleStartElement() throws XMLStreamException { try { // start namespace bindings int nsCount = staxStreamReader.getNamespaceCount(); for (int i = 0; i < nsCount; i++) { String uri = staxStreamReader.getNamespaceURI(i); if (uri == null) { uri = ""; } String prefix = staxStreamReader.getNamespacePrefix(i); if (prefix == null) { // true for default namespace prefix = ""; } filter.startPrefixMapping( prefix, uri); } // fire startElement QName qName = staxStreamReader.getName(); String prefix = qName.getPrefix(); String rawname; if(prefix==null || prefix.length()==0) rawname = qName.getLocalPart(); else rawname = prefix + ':' + qName.getLocalPart(); Attributes attrs = getAttributes(); filter.startElement( qName.getNamespaceURI(), qName.getLocalPart(), rawname, attrs); } catch (SAXException e) { throw new XMLStreamException(e); } } /** * Get the attributes associated with the given START_ELEMENT or ATTRIBUTE * StAXevent. * * @return the StAX attributes converted to an org.xml.sax.Attributes */ private Attributes getAttributes() { AttributesImpl attrs = new AttributesImpl(); int eventType = staxStreamReader.getEventType(); if (eventType != XMLStreamConstants.ATTRIBUTE && eventType != XMLStreamConstants.START_ELEMENT) { throw new InternalError( "getAttributes() attempting to process: " + eventType); } // Add namspace declarations if required if (filter.getNamespacePrefixes()) { for (int i = 0; i < staxStreamReader.getNamespaceCount(); i++) { String uri = staxStreamReader.getNamespaceURI(i); if (uri==null) uri=""; String prefix = staxStreamReader.getNamespacePrefix(i); if (prefix==null) prefix=""; String qName = "xmlns"; if (prefix.length() == 0) { prefix = qName; } else { qName = qName + ':' + prefix; } attrs.addAttribute("http://www.w3.org/2000/xmlns/", prefix, qName, "CDATA", uri); } } // gather non-namespace attrs for (int i = 0; i < staxStreamReader.getAttributeCount(); i++) { String uri = staxStreamReader.getAttributeNamespace(i); if(uri==null) uri=""; String localName = staxStreamReader.getAttributeLocalName(i); String prefix = staxStreamReader.getAttributePrefix(i); String qName; if(prefix==null || prefix.length()==0) qName = localName; else qName = prefix + ':' + localName; String type = staxStreamReader.getAttributeType(i); String value = staxStreamReader.getAttributeValue(i); attrs.addAttribute(uri, localName, qName, type, value); } return attrs; } private void handleNamespace() { // no-op ??? // namespace events don't normally occur outside of a startElement // or endElement } private void handleAttribute() { // no-op ??? // attribute events don't normally occur outside of a startElement // or endElement } private void handleDTD() { // no-op ??? // it seems like we need to pass this info along, but how? } private void handleComment() throws XMLStreamException { int textLength = staxStreamReader.getTextLength(); int textStart = staxStreamReader.getTextStart(); char[] chars = new char[textLength]; staxStreamReader.getTextCharacters(textStart, chars, 0, textLength); try { filter.comment(chars, 0, textLength); } catch (SAXException e) { throw new XMLStreamException(e); } } private void handleEntityReference() { // no-op ??? } private void handleSpace() { // no-op ??? // this event is listed in the javadoc, but not in the spec. } private void handleNotationDecl() { // no-op ??? // this event is listed in the javadoc, but not in the spec. } private void handleEntityDecl() { // no-op ??? // this event is listed in the javadoc, but not in the spec. } private void handleCDATA() { // no-op ??? // this event is listed in the javadoc, but not in the spec. } } test/0000755000175000017500000000000011542302320010571 5ustar tonytonytest/javanet/0000755000175000017500000000000011542302302012221 5ustar tonytonytest/javanet/staxutils/0000755000175000017500000000000011542302304014263 5ustar tonytonytest/javanet/staxutils/StAXSourceTest.java0000644000175000017500000001073410555245152020005 0ustar tonytony/* * Copyright (c) 2007, 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.SAXException; import org.xml.sax.XMLReader; import javax.xml.stream.XMLStreamException; import java.io.StringReader; /** * This class tests StAXSource * * @author Ryan.Shoemaker@Sun.COM * @version $Revision: 1.1 $ * @since 1.0 */ public class StAXSourceTest extends StAXTestCase { public void testGetFeature() throws XMLStreamException { boolean pass = true; StAXSource staxSource = new StAXSource(inputFactory.createXMLStreamReader(new StringReader(""))); XMLReader r = staxSource.getXMLReader(); try { assertTrue( r.getFeature("http://xml.org/sax/features/namespaces") && r.getFeature("http://xml.org/sax/features/external-general-entities") && r.getFeature("http://xml.org/sax/features/external-parameter-entities")); } catch (SAXException e) { pass = false; e.printStackTrace(); } finally { if(!pass) { fail(); } } } public void testGetFeatureNegative() throws XMLStreamException { boolean pass = false; StAXSource staxSource = new StAXSource(inputFactory.createXMLStreamReader(new StringReader(""))); XMLReader r = staxSource.getXMLReader(); try { r.getFeature("http://foo.blarg.com"); } catch (SAXException e) { pass = true; } finally { if(!pass) { fail(); } } } public void testSetFeaturePositive() throws XMLStreamException { boolean pass = true; StAXSource staxSource = new StAXSource(inputFactory.createXMLStreamReader(new StringReader(""))); XMLReader r = staxSource.getXMLReader(); try { r.setFeature("http://xml.org/sax/features/namespaces", true); r.setFeature("http://xml.org/sax/features/namespace-prefixes", true); r.setFeature("http://xml.org/sax/features/external-general-entities", true); r.setFeature("http://xml.org/sax/features/external-parameter-entities", true); } catch (SAXException e) { pass = false; e.printStackTrace(); } finally { if(!pass) { fail(); } } } public void testSetFeatureNegative() throws XMLStreamException { boolean pass = false; StAXSource staxSource = new StAXSource(inputFactory.createXMLStreamReader(new StringReader(""))); XMLReader r = staxSource.getXMLReader(); try { r.setFeature("http://xml.org/sax/features/namespaces", false); } catch (SAXException e) { pass = true; } finally { if(!pass) { fail(); } } } } test/javanet/staxutils/XMLStreamEventWriterTest.java0000644000175000017500000002006110075364610022010 0ustar tonytony/* * $Id: XMLStreamEventWriterTest.java,v 1.2 2004-07-15 02:18:48 cniles Exp $ * * Copyright (c) 2004, Christian Niles, Unit12 * 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 Christian Niles, Unit12, 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 java.io.StringWriter; import java.io.Writer; import javanet.staxutils.io.StAXStreamWriter; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; /** * * @author Christian Niles * @version $Revision: 1.2 $ */ public class XMLStreamEventWriterTest extends StAXTestCase { public static final QName ELEMENT_NAME = new QName("element"); public static final QName PREFIXED_ELEMENT_NAME = new QName( "http://www.example.com/namespace", "element", "prefix"); /** * Writes a single, text-only element mapped to a undefined prefix to test * namespace defaulting. */ public void testDefaulting() throws Exception { // create writers StringWriter writer = new StringWriter(); XMLStreamWriter streamWriter = createXMLStreamWriter(writer); XMLStreamEventWriter eventWriter = new XMLStreamEventWriter( streamWriter); // add empty element events eventWriter.add(eventFactory.createStartElement(PREFIXED_ELEMENT_NAME, null, null)); eventWriter.add(eventFactory.createCharacters("text")); eventWriter.add(eventFactory.createEndElement(PREFIXED_ELEMENT_NAME, null)); // flush the writers eventWriter.flush(); streamWriter.flush(); writer.flush(); String xml = writer.getBuffer().toString(); assertEquals( "XML output failed (" + xml + ")", "text", xml); } /** * Writes a single, text-only element to test that caching works with * text nodes. */ public void testTextElement() throws Exception { // create writers StringWriter writer = new StringWriter(); XMLStreamWriter streamWriter = createXMLStreamWriter(writer); XMLStreamEventWriter eventWriter = new XMLStreamEventWriter( streamWriter); // add empty element events eventWriter.add(eventFactory.createStartElement(ELEMENT_NAME, null, null)); eventWriter.add(eventFactory.createCharacters("text")); eventWriter.add(eventFactory.createEndElement(ELEMENT_NAME, null)); // flush the writers eventWriter.flush(); streamWriter.flush(); writer.flush(); String xml = writer.getBuffer().toString(); assertEquals("XML output failed (" + xml + ")", "text", xml); } /** * Writes a single, empty element to test that caching works with a small * dataset. */ public void testSingleElement() throws Exception { // create writers StringWriter writer = new StringWriter(); XMLStreamWriter streamWriter = createXMLStreamWriter(writer); XMLStreamEventWriter eventWriter = new XMLStreamEventWriter( streamWriter); // add empty element events eventWriter.add(eventFactory.createStartElement(ELEMENT_NAME, null, null)); eventWriter.add(eventFactory.createEndElement(ELEMENT_NAME, null)); // flush the writers eventWriter.close(); streamWriter.close(); writer.close(); String xml = writer.toString(); assertEquals("XML output failed (" + xml + ")", "", xml); } /** * Tests to make sure that two adjacent StartElement and EndElement events * are coalesced into an empty element on the underlying XMLStreamWriter. */ public void testEmptyElement() throws Exception { // create writers StringWriter writer = new StringWriter(); XMLStreamWriter streamWriter = createXMLStreamWriter(writer); XMLStreamEventWriter eventWriter = new XMLStreamEventWriter( streamWriter); // add empty element events eventWriter.add(eventFactory.createStartElement(ELEMENT_NAME, null, null)); eventWriter.add(eventFactory.createStartElement(ELEMENT_NAME, null, null)); eventWriter.add(eventFactory.createStartElement(ELEMENT_NAME, null, null)); eventWriter.add(eventFactory.createEndElement(ELEMENT_NAME, null)); eventWriter.add(eventFactory.createEndElement(ELEMENT_NAME, null)); eventWriter.add(eventFactory.createEndElement(ELEMENT_NAME, null)); // flush the writers eventWriter.flush(); streamWriter.flush(); writer.flush(); String xml = writer.getBuffer().toString(); assertEquals("XML output failed (" + xml + ")", "", xml); } /** * Tests the caching of Namespace events, making sure they are * properly added to the next StartElement */ public void testNamespaceCaching() throws Exception { // create writers StringWriter writer = new StringWriter(); XMLStreamWriter streamWriter = createXMLStreamWriter(writer); XMLStreamEventWriter eventWriter = new XMLStreamEventWriter( streamWriter); // add events eventWriter.add(eventFactory.createStartElement(ELEMENT_NAME, null, null)); eventWriter.add(eventFactory.createStartElement(ELEMENT_NAME, null, null)); eventWriter.add(eventFactory.createStartElement(ELEMENT_NAME, null, null)); eventWriter.add(eventFactory.createNamespace("prefix", "http://example.net/namespace")); eventWriter.add(eventFactory.createEndElement(ELEMENT_NAME, null)); eventWriter.add(eventFactory.createEndElement(ELEMENT_NAME, null)); eventWriter.add(eventFactory.createEndElement(ELEMENT_NAME, null)); // flush the writers eventWriter.flush(); streamWriter.flush(); writer.flush(); String xml = writer.getBuffer().toString(); assertEquals( "XML output failed (" + xml + ")", "", xml); } protected XMLStreamWriter createXMLStreamWriter(Writer writer) throws XMLStreamException { return new StAXStreamWriter(writer); } }test/javanet/staxutils/XMLEventConsumerDelegateTest.java0000644000175000017500000000673610111147032022607 0ustar tonytony/* * $Id: XMLEventConsumerDelegateTest.java,v 1.3 2004-08-19 15:58:17 cniles Exp $ * * Copyright (c) 2004, Christian Niles, Unit12 * 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 Christian Niles, Unit12, 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 java.io.StringWriter; import java.io.Writer; import javanet.staxutils.io.StreamEventWriter; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLStreamException; /** * * @author Christian Niles * @version $Revision: 1.3 $ */ public class XMLEventConsumerDelegateTest extends StAXTestCase { public void testWriteElement() throws Exception { // construct writers StringWriter writer = new StringWriter(); XMLEventWriter eventWriter = createEventWriter(writer); // create an empty element XMLEventConsumerDelegate out = createDelegate(eventWriter); out.addStartElement("element", null); out.addEndElement("element"); // flush the writers eventWriter.flush(); writer.flush(); // test the result String xml = writer.getBuffer().toString(); assertEquals("XML output failed (" + xml + ")", "", xml); } public void testWriteTextElement() throws Exception { StringWriter writer = new StringWriter(); XMLEventWriter eventWriter = createEventWriter(writer); XMLEventConsumerDelegate out = createDelegate(eventWriter); out.addTextElement("element", "text", null); eventWriter.flush(); writer.flush(); String xml = writer.getBuffer().toString(); assertEquals("XML output failed (" + xml + ")", "text", xml); } protected XMLEventConsumerDelegate createDelegate(XMLEventWriter eventWriter) { return new XMLEventConsumerDelegate(eventWriter, eventFactory); } protected XMLEventWriter createEventWriter(Writer writer) throws XMLStreamException { return new StreamEventWriter(writer); } }test/javanet/staxutils/XMLStreamUtils.xml0000644000175000017500000000053210042510366017645 0ustar tonytony John Doe
123 fake street
Springfield IL 54321
test/javanet/staxutils/events/0000755000175000017500000000000011542302302015565 5ustar tonytonytest/javanet/staxutils/events/XMLEventsTest.java0000644000175000017500000002444310073401010021116 0ustar tonytony/* * $Id: XMLEventsTest.java,v 1.1 2004-07-09 02:25:12 cniles Exp $ * * Copyright (c) 2004, Christian Niles, Unit12 * 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 Christian Niles, Unit12, 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.events; import javanet.staxutils.events.EventFactory; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.Characters; import javax.xml.stream.events.EndDocument; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.Namespace; import javax.xml.stream.events.ProcessingInstruction; import javax.xml.stream.events.StartDocument; import javax.xml.stream.events.StartElement; import junit.framework.TestCase; /** * * @author Christian Niles * @version $Revision: 1.1 $ */ public class XMLEventsTest extends TestCase { private static final String PREFIX = "prefix"; private static final String URI = "http://w3.org/1999/xhtml"; private static final String NAME = "name"; private static final String VALUE = "value"; private final XMLEventFactory FACTORY = new EventFactory(); private final ProcessingInstruction PI = FACTORY.createProcessingInstruction( NAME, VALUE); private final Namespace NAMESPACE = FACTORY.createNamespace("prefix", "http://w3.org/1999/xhtml"); private final EndElement END_ELEMENT = FACTORY.createEndElement(PREFIX, URI, NAME); private final StartElement START_ELEMENT = FACTORY.createStartElement( PREFIX, URI, NAME); private final EndDocument END_DOCUMENT = FACTORY.createEndDocument(); private final StartDocument START_DOCUMENT = FACTORY.createStartDocument(); private final Characters CHARACTERS = FACTORY.createCharacters(VALUE); private final Attribute ATTRIBUTE = FACTORY.createAttribute(NAME, VALUE); public void testIsAttribute() { assertFalse("Characters.isAttribute() == true", CHARACTERS.isAttribute()); assertFalse("StartDocument.isAttribute() == true", START_DOCUMENT.isAttribute()); assertFalse("EndDocument.isAttribute() == true", END_DOCUMENT.isAttribute()); assertFalse("StartElement.isAttribute() == true", START_ELEMENT.isAttribute()); assertFalse("EndElement.isAttribute() == true", END_ELEMENT.isAttribute()); assertFalse("ProcessingInstruction.isAttribute() == true", PI.isAttribute()); assertFalse("Namespace.isAttribute() == true", NAMESPACE.isAttribute()); assertTrue("Attribute.isAttribute() == false", ATTRIBUTE.isAttribute()); } public void testIsCharacters() { assertFalse("StartDocument.isCharacters() == true", START_DOCUMENT.isCharacters()); assertFalse("EndDocument.isCharacters() == true", END_DOCUMENT.isCharacters()); assertFalse("StartElement.isCharacters() == true", START_ELEMENT.isCharacters()); assertFalse("EndElement.isCharacters() == true", END_ELEMENT.isCharacters()); assertFalse("ProcessingInstruction.isCharacters() == true", PI.isCharacters()); assertFalse("Namespace.isCharacters() == true", NAMESPACE.isCharacters()); assertFalse("Attribute.isCharacters() == true", ATTRIBUTE.isCharacters()); assertTrue("Characters.isCharacters() == false", CHARACTERS.isCharacters()); } public void testIsStartDocument() { assertFalse("Characters.isStartDocument() == true", CHARACTERS.isStartDocument()); assertFalse("EndDocument.isStartDocument() == true", END_DOCUMENT.isStartDocument()); assertFalse("StartElement.isStartDocument() == true", START_ELEMENT.isStartDocument()); assertFalse("EndElement.isStartDocument() == true", END_ELEMENT.isStartDocument()); assertFalse("ProcessingInstruction.isStartDocument() == true", PI.isStartDocument()); assertFalse("Namespace.isStartDocument() == true", NAMESPACE.isStartDocument()); assertFalse("Attribute.isStartDocument() == true", ATTRIBUTE.isStartDocument()); assertTrue("StartDocument.isStartDocument() == false", START_DOCUMENT.isStartDocument()); } public void testIsEndDocument() { assertFalse("Characters.isEndDocument() == true", CHARACTERS.isEndDocument()); assertFalse("StartElement.isEndDocument() == true", START_ELEMENT.isEndDocument()); assertFalse("EndElement.isEndDocument() == true", END_ELEMENT.isEndDocument()); assertFalse("StartDocument.isEndDocument() == true", START_DOCUMENT.isEndDocument()); assertFalse("ProcessingInstruction.isEndDocument() == true", PI.isEndDocument()); assertFalse("Namespace.isEndDocument() == true", NAMESPACE.isEndDocument()); assertFalse("Attribute.isEndDocument() == true", ATTRIBUTE.isEndDocument()); assertTrue("EndDocument.isEndDocument() == false", END_DOCUMENT.isEndDocument()); } public void testIsStartElement() { assertFalse("Characters.isStartElement() == true", CHARACTERS.isStartElement()); assertFalse("EndElement.isStartElement() == true", END_ELEMENT.isStartElement()); assertFalse("ProcessingInstruction.isStartElement() == true", PI.isStartElement()); assertFalse("Namespace.isStartElement() == true", NAMESPACE.isStartElement()); assertFalse("Attribute.isStartElement() == true", ATTRIBUTE.isStartElement()); assertFalse("StartDocument.isStartElement() == true", START_DOCUMENT.isStartElement()); assertFalse("EndDocument.isStartElement() == true", END_DOCUMENT.isStartElement()); assertTrue("StartElement.isStartElement() == false", START_ELEMENT.isStartElement()); } public void testIsEndElement() { assertFalse("Characters.isEndElement() == true", CHARACTERS.isEndElement()); assertFalse("StartElement.isEndElement() == true", START_ELEMENT.isEndElement()); assertFalse("ProcessingInstruction.isEndElement() == true", PI.isEndElement()); assertFalse("Namespace.isEndElement() == true", NAMESPACE.isEndElement()); assertFalse("Attribute.isEndElement() == true", ATTRIBUTE.isEndElement()); assertFalse("StartDocument.isStartElement() == true", START_DOCUMENT.isStartElement()); assertFalse("EndDocument.isEndElement() == true", END_DOCUMENT.isEndElement()); assertTrue("EndElement.isEndElement() == false", END_ELEMENT.isEndElement()); } public void testIsNamespace() { assertFalse("Characters.isNamespace() == true", CHARACTERS.isNamespace()); assertFalse("StartElement.isNamespace() == true", START_ELEMENT.isNamespace()); assertFalse("ProcessingInstruction.isNamespace() == true", PI.isNamespace()); assertFalse("Attribute.isNamespace() == true", ATTRIBUTE.isNamespace()); assertFalse("StartDocument.isNamespace() == true", START_DOCUMENT.isNamespace()); assertFalse("EndDocument.isNamespace() == true", END_DOCUMENT.isNamespace()); assertFalse("EndElement.isNamespace() == true", END_ELEMENT.isNamespace()); assertTrue("Namespace.isNamespace() == false", NAMESPACE.isNamespace()); } public void testIsProcessingInstruction() { assertFalse("Characters.isProcessingInstruction() == true", CHARACTERS.isProcessingInstruction()); assertFalse("StartElement.isProcessingInstruction() == true", START_ELEMENT.isProcessingInstruction()); assertFalse("Namespace.isProcessingInstruction() == true", NAMESPACE.isProcessingInstruction()); assertFalse("Attribute.isProcessingInstruction() == true", ATTRIBUTE.isProcessingInstruction()); assertFalse("StartDocument.isProcessingInstruction() == true", START_DOCUMENT.isProcessingInstruction()); assertFalse("EndDocument.isProcessingInstruction() == true", END_DOCUMENT.isProcessingInstruction()); assertFalse("EndElement.isProcessingInstruction() == true", END_ELEMENT.isProcessingInstruction()); assertTrue("ProcessingInstruction.isProcessingInstruction() == false", PI.isProcessingInstruction()); } }test/javanet/staxutils/StAXTestCase.java0000644000175000017500000000562010075364432017416 0ustar tonytony/* * $Id: StAXTestCase.java,v 1.2 2004-07-15 02:16:57 cniles Exp $ * * Copyright (c) 2004, Christian Niles, Unit12 * 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 Christian Niles, Unit12, 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 javanet.staxutils.events.EventFactory; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import junit.framework.TestCase; /** * Provides common functionality for stax-utils test cases. * * @author Christian Niles * @version $Revision: 1.2 $ */ public class StAXTestCase extends TestCase { /** An input factory used to create input streams. */ protected XMLInputFactory inputFactory; /** An output factory used to create output streams. */ protected XMLOutputFactory outputFactory; /** An event factory used to create StAX events. */ protected XMLEventFactory eventFactory; protected StAXTestCase() { } /** * Initializes the factories. */ protected void setUp() throws Exception { inputFactory = XMLInputFactory.newInstance(); outputFactory = XMLOutputFactory.newInstance(); eventFactory = new EventFactory(); // XMLEventFactory.newInstance(); } /** * Destructs the factories. */ protected void tearDown() throws Exception { inputFactory = null; outputFactory = null; eventFactory = null; } }test/javanet/staxutils/io/0000755000175000017500000000000011542302304014672 5ustar tonytonytest/javanet/staxutils/io/StAXStreamWriterTest.java0000644000175000017500000000677510075364334021617 0ustar tonytony/* * $Id: StAXStreamWriterTest.java,v 1.1 2004-07-15 02:15:55 cniles Exp $ * * Copyright (c) 2004, Christian Niles, Unit12 * 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 Christian Niles, Unit12, 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.io; import java.io.StringWriter; import java.io.Writer; import javanet.staxutils.StAXTestCase; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; /** * Tests the {@link StAXStreamWriter} interface. * * @author Christian Niles * @version $Revision: 1.1 $ */ public class StAXStreamWriterTest extends StAXTestCase { public void testEmptyDocument() throws Exception { // create writers StringWriter writer = new StringWriter(); XMLStreamWriter streamWriter = createStreamWriter(writer); streamWriter.writeStartDocument(); streamWriter.writeEndDocument(); streamWriter.close(); String xml = writer.getBuffer().toString(); assertEquals("XML output failed (" + xml + ")", "", xml); } public void testEmptyRootElement() throws Exception { // create writers StringWriter writer = new StringWriter(); XMLStreamWriter streamWriter = createStreamWriter(writer); streamWriter.writeStartDocument(); streamWriter.writeEmptyElement("prefix", "name", "http://test.namespace.tld/"); streamWriter.writeAttribute("attribute", "value"); streamWriter.writeNamespace("prefix", "http://test.namespace.tld/"); streamWriter.writeEndDocument(); streamWriter.close(); String xml = writer.getBuffer().toString(); assertEquals( "XML output failed (" + xml + ")", "", xml); } protected XMLStreamWriter createStreamWriter(Writer writer) throws XMLStreamException { return new StAXStreamWriter(writer); } }test/javanet/staxutils/XMLStreamUtilsTest.java0000644000175000017500000001660111535774174020653 0ustar tonytony/* * $Id: XMLStreamUtilsTest.java,v 1.2 2004-05-25 15:22:28 cniles Exp $ * * Copyright (c) 2004, Christian Niles, Unit12 * 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 Christian Niles, Unit12, 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 java.io.InputStream; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import junit.framework.TestCase; /** * @author christian * @version $Revision: 1.2 $ */ public class XMLStreamUtilsTest extends TestCase { /** * Constructor for XMLStreamUtilsTest. * @param arg0 */ public XMLStreamUtilsTest(String arg0) { super(arg0); } public void testSkipStreamElement() throws XMLStreamException { XMLStreamReader reader = getSampleXMLStreamReader(); try { while (!reader.isStartElement() && reader.hasNext()) { reader.next(); } assertTrue("Reader didn't get to root", reader.isStartElement()); XMLStreamUtils.skipElement(reader); assertTrue("Didn't end in an end-element state", reader.isEndElement()); assertEquals("Didn't end on end person tag", new QName("person"), reader.getName()); } finally { reader.close(); } } public void testSkipElementEvents() throws XMLStreamException { XMLEventReader reader = getSampleXMLEventReader(); try { StartElement rootElem = XMLStreamUtils.nextElement(reader); reader.nextEvent(); // consume start tag // skip name element StartElement nameElem = XMLStreamUtils.nextElement(reader); XMLStreamUtils.skipElement(reader); StartElement phoneElem = XMLStreamUtils.nextElement(reader); assertNotNull("phone tag was null", phoneElem); assertEquals("Expected phone start tag", new QName("phone"), phoneElem.getName()); reader.nextEvent(); XMLStreamUtils.skipElementContent(reader); assertTrue("expected phone end tag", reader.nextEvent() .isEndElement()); StartElement addrElem = XMLStreamUtils.nextElement(reader); assertNotNull("address tag was null", addrElem); assertEquals("Expected address start tag", new QName("address"), addrElem.getName()); } finally { reader.close(); } } public void testReadTextElement() throws XMLStreamException { XMLEventReader reader = getSampleXMLEventReader(); try { StartElement rootElem = XMLStreamUtils.nextElement(reader); reader.nextEvent(); // consume start tag StartElement nameElem = XMLStreamUtils.nextElement(reader); String name = XMLStreamUtils.readTextElement(reader, null); assertEquals("Name didn't match", "John Doe", name); StartElement phoneElem = XMLStreamUtils.nextElement(reader); assertNotNull("phone tag was null", phoneElem); } finally { reader.close(); } } public void testNextTag() throws XMLStreamException { XMLEventReader reader = getSampleXMLEventReader(); try { XMLEvent rootTag = XMLStreamUtils.nextTag(reader); assertTrue("root tag wasn't StartElement", rootTag.isStartElement()); assertEquals("stream not at StartElement after root", new QName( "person"), reader.nextEvent().asStartElement().getName()); XMLEvent nameTag = XMLStreamUtils.nextTag(reader); assertTrue("expected name start tag", nameTag.isStartElement()); assertEquals("not name start tag", new QName("name"), reader.nextEvent().asStartElement().getName()); XMLEvent nameEnd = XMLStreamUtils.nextTag(reader); assertTrue("expected name end tag", nameEnd.isEndElement()); assertEquals("not name end tag", new QName("name"), reader.nextEvent().asEndElement().getName()); } finally { reader.close(); } } public void testNextElement() throws XMLStreamException { XMLEventReader reader = getSampleXMLEventReader(); try { StartElement rootElem = XMLStreamUtils.nextElement(reader); assertEquals("Root element didn't match person", new QName("person"), rootElem.getName()); StartElement rootElem2 = reader.nextEvent().asStartElement(); assertEquals("Root elements didn't match", rootElem, rootElem2); StartElement nameElem = XMLStreamUtils.nextElement(reader, new QName("name")); assertNotNull("next name elem was null", nameElem); } finally { reader.close(); } } private XMLStreamReader getSampleXMLStreamReader() throws XMLStreamException { // load sample XML ClassLoader loader = Thread.currentThread().getContextClassLoader(); InputStream testSource = loader.getResourceAsStream("javanet/staxutils/XMLStreamUtils.xml"); XMLInputFactory factory = XMLInputFactory.newInstance(); return factory.createXMLStreamReader(testSource); } private XMLEventReader getSampleXMLEventReader() throws XMLStreamException { // load sample XML ClassLoader loader = Thread.currentThread().getContextClassLoader(); InputStream testSource = loader.getResourceAsStream("javanet/staxutils/XMLStreamUtils.xml"); XMLInputFactory factory = XMLInputFactory.newInstance(); return factory.createXMLEventReader(testSource); } } test/javanet/staxutils/IndentingTest.java0000644000175000017500000002665210424215472017727 0ustar tonytony/* * Copyright (c) 2006, John Kristian * 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 StAX-Utils 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 java.io.StringWriter; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Test IndentingXMLEventWriter and IndentingXMLStreamWriter. Those two classes * are expected to output identical XML, in all test cases. * * @author John Kristian */ public class IndentingTest extends TestCase { /** Each test case is represented by an object. */ private static Case[] newCases() { return new Case[] // { new Case("empty document") { protected void test() throws Exception { String expected = ""; String actual = getActual(); assertEquals(expected, actual); } }, new Case("empty element") { protected void test() throws Exception { stream.writeEmptyElement("alpha"); String expected = ""; String actual = getActual(); assertEquals(expected, actual); } }, new Case("element in document") { protected void test() throws Exception { stream.writeStartDocument(); stream.writeStartElement("alpha"); stream.writeEndElement(); stream.writeEndDocument(); String expected = DECLARATION // + NL + "" // + NL; String actual = getActual(); if (!expected.equalsIgnoreCase(actual)) { assertEquals(expected, actual); } } }, new Case("nested elements; data-oriented; omit writeEndElement") { protected void test() throws Exception { stream.writeStartDocument(); stream.writeStartElement("alpha"); stream.writeStartElement("bravo"); stream.writeStartElement("charlie"); stream.writeStartElement("delta"); stream.writeStartElement("echo"); stream.writeEndElement(); // echo stream.writeEndElement(); // delta stream.writeStartElement("delta"); stream.writeCharacters("data"); stream.writeEndDocument(); String expected = DECLARATION // + NL + "" // + NL + " " // + NL + " " // + NL + " " // + NL + " " // + NL + " " // + NL + " data" // + NL + " " // + NL + " " // + NL + "" // + NL; String actual = getActual(); if (!expected.equalsIgnoreCase(actual)) { assertEquals(expected, actual); } } }, new Case("DTD; mixed content; omit writeEndElement") { protected void test() throws Exception { stream.writeStartDocument(); stream.writeDTD("a DTD"); stream.writeStartElement("alpha"); stream.writeCharacters("data"); stream.writeStartElement("bravo"); stream.writeCharacters("data"); stream.writeEndDocument(); String expected = DECLARATION // + NL + "a DTD" // + NL + "datadata" // + NL; String actual = getActual(); if (!expected.equalsIgnoreCase(actual)) { assertEquals(expected, actual); } } }, new Case("bizarre punctuation; processing instruction; comment") { protected void test() throws Exception { indenter.setNewLine(indenter.getNewLine() + "+"); indenter.setIndent("."); stream.writeStartDocument(); stream.writeStartElement("jokes"); stream.writeProcessingInstruction("target", "data"); stream.writeStartElement("riddle"); final String Q = "Why did the chicken cross the road?"; final String A = "To get to the other side."; stream.writeComment(Q); stream.writeStartElement("answer"); stream.writeCharacters(A); stream.writeEndDocument(); String expected = DECLARATION + "" // + NL + "+." // + NL + "+." // + NL + "+.." // + NL + "+.." + A + "" // + NL + "+." // + NL + "+"; String actual = getActual(); if (!expected.equalsIgnoreCase(actual)) { assertEquals(expected, actual); } } }, new Case("erroneous usage") { protected void test() throws Exception { try { stream.writeCharacters("data"); fail(); } catch (XMLStreamException expected) { } catch (IllegalStateException actual) { } try { stream.writeEndElement(); fail(); } catch (XMLStreamException expected) { } stream.writeStartElement("x"); try { stream.writeDTD("DTD"); fail(); } catch (XMLStreamException expected) { } try { stream.writeStartDocument(); fail(); } catch (XMLStreamException expected) { } catch (IllegalStateException actual) { } stream.writeEndDocument(); try { stream.writeStartDocument(); fail(); } catch (XMLStreamException expected) { } catch (IllegalStateException actual) { } try { stream.writeDTD("DTD"); fail(); } catch (XMLStreamException expected) { } catch (IllegalStateException actual) { } try { stream.writeStartElement("y"); fail(); } catch (XMLStreamException expected) { } catch (IllegalStateException actual) { } try { stream.writeCharacters(null); fail(); } catch (XMLStreamException expected) { } catch (NullPointerException actual) { } stream.writeProcessingInstruction("target"); stream.writeComment("comment"); String expected = "" // + NL + " " // before DTD + NL + " " // before StartDocument + NL + "" // + NL + "" // + NL + ""; String actual = getActual(); assertEquals(expected, actual); } } }; } private static abstract class Case extends TestCase { protected Case(String name) { super(name); } protected abstract void test() throws Exception; protected Indentation indenter; protected XMLStreamWriter stream; protected static final String DECLARATION = ""; protected static final String NL = "\n"; protected String getActual() throws Exception { stream.flush(); writer.flush(); return writer.toString(); } private StringWriter writer = new StringWriter(); public void runBare() throws Throwable { test(); } public String getName() { return prefix + super.getName(); } private String prefix; } /** * Construct a TestSuite that applies each test case to an * IndentingXMLStreamWriter and an IndentingXMLEventWriter. */ public static Test suite() throws Exception { TestSuite s = new TestSuite(); XMLOutputFactory outputFactory = new StaxUtilsXMLOutputFactory(); outputFactory.setProperty(StaxUtilsXMLOutputFactory.INDENTING, Boolean.TRUE); Case[] cases = newCases(); for (int c = 0; c < cases.length; ++c) { Case thisCase = cases[c]; XMLStreamWriter subject = outputFactory.createXMLStreamWriter(thisCase.writer); thisCase.indenter = (Indentation) subject; thisCase.stream = subject; thisCase.prefix = "Stream "; s.addTest(thisCase); } cases = newCases(); for (int c = 0; c < cases.length; ++c) { Case thisCase = cases[c]; XMLEventWriter subject = outputFactory.createXMLEventWriter(thisCase.writer); thisCase.indenter = (Indentation) subject; thisCase.stream = new XMLEventStreamWriter(subject); thisCase.prefix = "Event "; s.addTest(thisCase); } assertEquals("factory.indent", Boolean.TRUE, outputFactory .getProperty(StaxUtilsXMLOutputFactory.INDENTING)); return s; } }