LICENSE 0000644 0001750 0001750 00000003142 10423740506 010630 0 ustar tony tony Copyright (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.xml 0000644 0001750 0001750 00000014352 11535776260 011464 0 ustar tony tony
null
.
*/
public Location getNestedLocation();
} src/javanet/staxutils/ExtendedNamespaceContext.java 0000644 0001750 0001750 00000006066 10072357766 021713 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000054543 10111147032 021556 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000013164 10074530136 020711 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000031623 10424446144 021453 0 ustar tony tony /* 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: *
* 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.java 0000644 0001750 0001750 00000015375 10072360400 021573 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000022132 10072364154 017226 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000031026 10072360400 021410 0 ustar tony tony /*
* $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/ 0000755 0001750 0001750 00000000000 11542302312 015534 5 ustar tony tony src/javanet/staxutils/helpers/FilterXMLOutputFactory.java 0000644 0001750 0001750 00000011444 10424446060 022771 0 ustar tony tony /* 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.java 0000644 0001750 0001750 00000004572 11535774174 021564 0 ustar tony tony /*
* 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.java 0000644 0001750 0001750 00000006536 10075335262 022054 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000007752 11535774174 021364 0 ustar tony tony /*
* 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.java 0000644 0001750 0001750 00000006202 10075335262 021451 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000014672 10424446144 022506 0 ustar tony tony /*
* 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.java 0000644 0001750 0001750 00000034042 10075364142 021351 0 ustar tony tony /*
* $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 idx
th attribute defined on
* the context.
*
* @param idx The zero-based index of the attribute value to retrieve.
* @return The value of the idx
th 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 idx
th attribute defined on
* the context.
*
* @param idx The zero-based index of the attribute name to retrieve.
* @return The name of the idx
th 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 idx
th namespace declaration
* defined in this context.
*
* @param idx The index of the namespace URI to return.
* @return The URI of the idx
th 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 idx
th namespace declaration
* defined in this context.
*
* @param idx The index of the namespace prefix to return.
* @return The prefix of the idx
th 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.java 0000644 0001750 0001750 00000043430 10074545702 021003 0 ustar tony tony /*
* $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.html 0000644 0001750 0001750 00000000724 10074545702 020033 0 ustar tony tony
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.java 0000644 0001750 0001750 00000021212 10327475450 023116 0 ustar tony tony /* $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.java 0000644 0001750 0001750 00000004332 10075370466 017606 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000026120 10555245152 016751 0 ustar tony tony /* $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.java 0000644 0001750 0001750 00000060127 10073553112 017604 0 ustar tony tony /* * $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.java 0000644 0001750 0001750 00000025222 10327475450 022751 0 ustar tony tony /* $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
// mapDTD
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.java 0000644 0001750 0001750 00000006335 10075363666 023040 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000005665 10075363666 023660 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000012314 10072357654 022360 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000005214 10072357712 022136 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000005122 10072357712 020232 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000006044 10075363666 021166 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000030413 10075363666 021676 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000022402 10072357712 021176 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000005202 10072357712 021334 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000014472 10075363666 021241 0 ustar tony tony /*
* $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
* (true
false).
*/
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
* (true
false).
* @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.java 0000644 0001750 0001750 00000013145 10075363666 021416 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000010637 10075363666 022717 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000004674 10075363666 021506 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000012060 10072357712 020664 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000006015 10075363666 022363 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000021546 10072357654 022056 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000012070 10075363666 022062 0 ustar tony tony /*
* $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.html 0000644 0001750 0001750 00000000635 10074545702 017676 0 ustar tony tony
XMLEvent
implementations and related classes.
src/javanet/staxutils/events/ExtendedXMLEvent.java 0000644 0001750 0001750 00000005234 10072357532 021403 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000007533 10075363666 021316 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000005073 10075363666 020675 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000006344 10075363666 023236 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000012153 10073255126 017671 0 ustar tony tony /*
* $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/ 0000755 0001750 0001750 00000000000 11542302310 015221 5 ustar tony tony src/javanet/staxutils/error/IllegalStreamStateException.java 0000644 0001750 0001750 00000005674 11535774174 023534 0 ustar tony tony /*
* $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.html 0000644 0001750 0001750 00000000713 10074545702 017520 0 ustar tony tony
Provides useful Exception classes and utilties for error handling and reporting.
src/javanet/staxutils/XMLEventReaderToContentHandler.java 0000644 0001750 0001750 00000033741 10365222532 022675 0 ustar tony tony /* $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.java 0000644 0001750 0001750 00000027625 10075231752 021375 0 ustar tony tony /* * $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 benull
*/
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.java 0000644 0001750 0001750 00000026346 10424446144 021633 0 ustar tony tony /*
* 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: *
* 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.java 0000644 0001750 0001750 00000011647 11535774174 017412 0 ustar tony tony /* * 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.java 0000644 0001750 0001750 00000011562 10072360234 020326 0 ustar tony tony /* * $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.java 0000644 0001750 0001750 00000007342 10065630042 021212 0 ustar tony tony /* $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.java 0000644 0001750 0001750 00000004102 11535774174 017677 0 ustar tony tony /* * $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.java 0000644 0001750 0001750 00000006021 10072360150 021477 0 ustar tony tony /* * $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.java 0000644 0001750 0001750 00000005260 11535774174 017241 0 ustar tony tony /* * 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.java 0000644 0001750 0001750 00000021104 10075370466 020555 0 ustar tony tony /* * $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, ornull
* @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/ 0000755 0001750 0001750 00000000000 11542302312 014501 5 ustar tony tony src/javanet/staxutils/io/StreamEventWriter.java 0000644 0001750 0001750 00000012026 10075363570 021014 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000127352 10211654522 020241 0 ustar tony tony /*
* $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("");
XMLWriterUtils.writeQName(name, writer);
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("");
writer.write(target);
if (data != null) {
writer.write(' ');
writer.write(data);
}
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.java 0000644 0001750 0001750 00000044400 10075364334 020552 0 ustar tony tony /*
* $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.html 0000644 0001750 0001750 00000000613 10074545702 016775 0 ustar tony tony
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.java 0000644 0001750 0001750 00000005566 10065627662 022070 0 ustar tony tony /* $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.java 0000644 0001750 0001750 00000011201 10072360500 020743 0 ustar tony tony /*
* $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.java 0000644 0001750 0001750 00000010057 10066613712 016767 0 ustar tony tony /* $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.html 0000644 0001750 0001750 00000001126 10074545702 016366 0 ustar tony tony