stax-1.2.0.orig/ 0000755 0001750 0001750 00000000000 11224142554 013366 5 ustar twerner twerner stax-1.2.0.orig/src/ 0000755 0001750 0001750 00000000000 10444554664 014171 5 ustar twerner twerner stax-1.2.0.orig/src/test/ 0000755 0001750 0001750 00000000000 10444554662 015146 5 ustar twerner twerner stax-1.2.0.orig/src/test/XmlEscapingTest.java 0000644 0001750 0001750 00000007705 10444554662 021074 0 ustar twerner twerner /*
* Copyright 2002-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 2001, 2002, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* .
*/
package test;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.events.StartDocument;
import javax.xml.stream.events.XMLEvent;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Junit test to test out
* Bug 192
* Escaped characters disappear in certain cases. contributed by
* Thijs Janssen.
*/
public class XmlEscapingTest extends TestCase {
public static void main (String[] args) {
junit.textui.TestRunner.run (new TestSuite(XmlEscapingTest.class));
}
public void testXmlError() throws Exception {
InputStream stream = new ByteArrayInputStream(
"<text>"
.getBytes());
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLEventReader reader = factory.createXMLEventReader(stream);
StartDocument startdoc = (StartDocument) reader.nextEvent();
assertEquals("UTF-8", startdoc.getCharacterEncodingScheme());
assertEquals("1.0", startdoc.getVersion());
assertTrue(reader.hasNext());
XMLEvent event = reader.nextEvent();
assertTrue(event.isStartElement());
event = reader.nextEvent();
assertTrue(event.isCharacters());
String c = event.asCharacters().getData();
event = reader.nextEvent();
assertTrue(event.isCharacters());
c+=event.asCharacters().getData();
assertEquals("",c); //FAILURE expected "" but was "<text> "
.getBytes());
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLEventReader reader = factory.createXMLEventReader(stream);
StartDocument startdoc = (StartDocument) reader.nextEvent();
assertEquals("UTF-8", startdoc.getCharacterEncodingScheme());
assertEquals("1.0", startdoc.getVersion());
assertTrue(reader.hasNext());
XMLEvent event = reader.nextEvent();
assertTrue(event.isStartElement());
event = reader.nextEvent();
assertTrue(event.isCharacters());
String c = event.asCharacters().getData();
event = reader.nextEvent();
assertTrue(event.isCharacters());
c+=event.asCharacters().getData();
event = reader.nextEvent();
assertTrue(event.isEndElement());
assertEquals(" ",c); //SUCCES
}
}
stax-1.2.0.orig/src/test/files/ 0000755 0001750 0001750 00000000000 10444554662 016250 5 ustar twerner twerner stax-1.2.0.orig/src/test/files/test.xml 0000644 0001750 0001750 00000001173 10444554662 017753 0 ustar twerner twerner
]>
foo bar foo
&>< &foo;
&bar;
&foo;&bar;&foo;
]]>
stax-1.2.0.orig/src/samples/ 0000755 0001750 0001750 00000000000 10444554662 015633 5 ustar twerner twerner stax-1.2.0.orig/src/samples/TestSerializer2.java 0000644 0001750 0001750 00000003735 10444554662 021541 0 ustar twerner twerner package samples;
import java.io.StringWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
/**
* Requires StAX RI 1.0 (JSR 173) available at http://stax.codehaus.org/
*/
public class TestSerializer2
{
private final static String SOAP12 = "http://www.w3.org/2003/05/soap-envelope";
private final static String TESTNS = "http://someTestUri";
private final static String CHEESENS = "http://cheese";
public static void doXmlOutput(boolean useRepairing) throws XMLStreamException {
StringWriter buffer = new StringWriter();
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
if (useRepairing) {
outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", Boolean.TRUE);
}
XMLStreamWriter out = outputFactory.createXMLStreamWriter(buffer);
out.writeStartDocument();
if (useRepairing) {
out.setPrefix("env", SOAP12);
out.setPrefix("test", TESTNS);
}
out.writeStartElement("env", "Envelope", SOAP12);
if (!useRepairing) {
out.writeNamespace("env", SOAP12);
out.writeNamespace("test", TESTNS);
}
out.writeStartElement("test", "dummyElement", TESTNS);
if (useRepairing) {
out.setPrefix("", CHEESENS);
}
out.writeStartElement("", "cheddar", CHEESENS);
if (!useRepairing) {
out.writeDefaultNamespace(CHEESENS);
}
out.writeEndElement();
out.writeEndElement();
out.writeEndElement();
out.writeEndDocument();
out.close();
System.out.println("Created "+(useRepairing ? "" : "not")+" using repairing :-");
System.out.println(buffer);
}
public static void main(String[] s) throws Exception {
doXmlOutput(false);
doXmlOutput(true);
}
}
stax-1.2.0.orig/src/samples/TestStreamReader.java 0000644 0001750 0001750 00000020242 10444554662 021714 0 ustar twerner twerner package samples;
import java.io.*;
import java.util.List;
import java.util.zip.*;
import javax.xml.stream.*;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
/**
* Simple helper test class for checking how stream reader handles xml
* documents.
*
* @author Tatu Saloranta
*/
public class TestStreamReader
implements XMLStreamConstants
{
protected TestStreamReader() {
}
protected XMLInputFactory getFactory()
{
// Stax ref. impl. is the default, no need to override?
//System.setProperty("javax.xml.stream.XMLInputFactory", "com.bea.xml.stream.MXParser");
XMLInputFactory f = XMLInputFactory.newInstance();
System.out.println("Factory instance: "+f.getClass());
f.setProperty(XMLInputFactory.IS_COALESCING, Boolean.FALSE);
//f.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
f.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
//f.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);
f.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
f.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.TRUE);
//f.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
//f.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.FALSE);
//f.setProperty(XMLInputFactory.REPORTER, new TestReporter());
//f.setProperty(XMLInputFactory.RESOLVER, new TestResolver1());
return f;
}
protected int test(File file)
throws Exception
{
XMLInputFactory f = getFactory();
System.out.print("Coalesce: "+f.getProperty(XMLInputFactory.IS_COALESCING));
System.out.println(", NS-aware: "+f.getProperty(XMLInputFactory.IS_NAMESPACE_AWARE));
System.out.print("Entity-expanding: "+f.getProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES));
System.out.println(", validating: "+f.getProperty(XMLInputFactory.IS_VALIDATING));
int total = 0;
XMLStreamReader sr;
// Let's deal with gzipped files too?
FileInputStream fis = new FileInputStream(file);
if (file.getName().endsWith(".gz")) {
System.out.println("[gzipped input file!]");
sr = f.createXMLStreamReader(new GZIPInputStream(fis));
} else {
sr = f.createXMLStreamReader(file.toURL().toExternalForm(), fis);
}
int type = sr.getEventType();
System.out.println("START: version = '"+sr.getVersion()
+"', xml-encoding = '"+sr.getCharacterEncodingScheme()
+"', input encoding = '"+sr.getEncoding()+"'");
//while (sr.hasNext()) {
while (type != END_DOCUMENT) {
type = sr.next();
total += type; // so it won't be optimized out...
boolean hasName = sr.hasName();
System.out.print("["+type+"]");
// Uncomment for location info debugging:
/*
Location li = sr.getLocation();
System.out.println(" LOC: "+li);
*/
if (sr.hasText()) {
String text = sr.getText();
if (text != null) { // Ref. impl. returns nulls sometimes
total += text.length(); // to prevent dead code elimination
}
if (type == CHARACTERS || type == CDATA || type == COMMENT) {
System.out.println(" Text("+text.length()+") = '"+text+"'.");
if (text.length() == 1) {
System.out.println(" [first char code: 0x"+Integer.toHexString(text.charAt(0))+"]");
}
} else if (type == SPACE) {
System.out.print(" Ws = '"+text+"'.");
char c = (text.length() == 0) ? ' ': text.charAt(text.length()-1);
if (c != '\r' && c != '\n') {
System.out.println();
}
} else if (type == DTD) {
System.out.println(" DTD:");
List entities = (List) sr.getProperty("javax.xml.stream.entities");
List notations = (List) sr.getProperty("javax.xml.stream.notations");
int entCount = (entities == null) ? -1 : entities.size();
int notCount = (notations == null) ? -1 : notations.size();
System.out.print(" ("+entCount+" entities, "+notCount
+" notations), sysid ");
System.out.print(", declaration = <<");
System.out.print(text);
System.out.println(">>");
} else if (type == ENTITY_REFERENCE) {
// entity ref
System.out.println(" Entity ref: &"+sr.getLocalName()+" -> '"+sr.getText()+"'.");
hasName = false; // to suppress further output
} else { // PI?
;
}
}
if (type == PROCESSING_INSTRUCTION) {
System.out.println(" PI target = '"+sr.getPITarget()+"'.");
System.out.println(" PI data = '"+sr.getPIData()+"'.");
} else if (type == START_ELEMENT) {
String prefix = sr.getPrefix();
System.out.print('<');
if (prefix != null && prefix.length() > 0) {
System.out.print(prefix);
System.out.print(':');
}
System.out.print(sr.getLocalName());
System.out.print(" {ns '");
System.out.print(sr.getNamespaceURI());
System.out.print("'}> ");
int count = sr.getAttributeCount();
int nsCount = sr.getNamespaceCount();
System.out.println(" ["+nsCount+" ns, "+count+" attrs]");
// debugging:
for (int i = 0; i < nsCount; ++i) {
System.out.println(" ns#"+i+": '"+sr.getNamespacePrefix(i)
+"' -> '"+sr.getNamespaceURI(i)
+"'");
}
for (int i = 0; i < count; ++i) {
System.out.print(" attr#"+i+": "+sr.getAttributePrefix(i)
+":"+sr.getAttributeLocalName(i)
+" ("+sr.getAttributeNamespace(i)
+") -> '"+sr.getAttributeValue(i)
+"'");
System.out.println(sr.isAttributeSpecified(i) ?
"[specified]" : "[Default]");
}
} else if (type == END_ELEMENT) {
System.out.print("");
String prefix = sr.getPrefix();
if (prefix != null && prefix.length() > 0) {
System.out.print(prefix);
System.out.print(':');
}
System.out.print(sr.getLocalName());
System.out.print(" {ns '");
System.out.print(sr.getNamespaceURI());
System.out.print("'}> ");
int nsCount = sr.getNamespaceCount();
System.out.println(" ["+nsCount+" ns unbound]");
} else if (type == START_DOCUMENT) { // only for multi-doc mode
System.out.print("XML-DECL: version = '"+sr.getVersion()
+"', xml-decl-encoding = '"+sr.getCharacterEncodingScheme()
+"', app-encoding = '"+sr.getEncoding()
+"', stand-alone set: "+sr.standaloneSet());
}
}
return total;
}
public static void main(String[] args)
throws Exception
{
if (args.length != 1) {
System.err.println("Usage: java ... "+TestStreamReader.class+" [file]");
System.exit(1);
}
try {
int total = new TestStreamReader().test(new File(args[0]));
System.out.println();
System.out.println("Total: "+total);
} catch (Throwable t) {
System.err.println("Error: "+t);
t.printStackTrace();
}
}
}
stax-1.2.0.orig/src/samples/TestPi.java 0000644 0001750 0001750 00000002101 10444554662 017700 0 ustar twerner twerner package samples;
import com.bea.xml.stream.util.ElementTypeNames;
import java.io.StringReader;
import java.util.Iterator;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Namespace;
import javax.xml.stream.events.XMLEvent;
//http://jira.codehaus.org/browse/STAX-15 StringIndexOutOfBoundsException when parsing PI's
/**
* Requires StAX 1.0 (JSR 173) parser such as http://stax.codehaus.org/Download
*
*/
public class TestPi extends TestXml
{
static String sampleXML =
"\n"+
""+
""
;
public static void main(String[] s)
{
parseWithSTAX(sampleXML);
System.exit(0);
}
}
stax-1.2.0.orig/src/samples/TestSerializer.java 0000644 0001750 0001750 00000002535 10444554662 021454 0 ustar twerner twerner package samples;
import java.io.StringWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
/**
* Requires StAX RI 1.0 (JSR 173) available at http://stax.codehaus.org/Donwload
*/
public class TestSerializer
{
private final static String SOAP12 = "http://www.w3.org/2003/05/soap-envelope";
public static void doXmlOutput(boolean useRepairing) throws XMLStreamException {
StringWriter buffer = new StringWriter();
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
if (useRepairing) {
outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", Boolean.TRUE);
}
XMLStreamWriter out = outputFactory.createXMLStreamWriter(buffer);
out.writeStartDocument();
out.writeStartElement("env", "Envelope", SOAP12);
out.writeNamespace("env", SOAP12);
out.writeNamespace("test", "http://someTestUri");
out.writeEndElement();
out.writeEndDocument();
out.close();
System.out.println("Created "+(useRepairing ? "" : "not")+" using repairing :-");
System.out.println(buffer);
}
public static void main(String[] s) throws Exception {
doXmlOutput(false);
doXmlOutput(true);
}
}
stax-1.2.0.orig/src/samples/TestCdataReport.java 0000644 0001750 0001750 00000003752 10444554662 021555 0 ustar twerner twerner package samples;
import com.bea.xml.stream.util.ElementTypeNames;
import java.io.StringReader;
import java.util.Iterator;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Namespace;
import javax.xml.stream.events.XMLEvent;
/**
* Requires StAX 1.0 (JSR 173) available at http://jcp.org/en/jsr/detail?id=173
*
*/
public class TestCdataReport extends TestXml
{
static String sampleXML =
//"Some xt \n";
//""+
//""
"\n"
+" baz\n"
+" \n"
+" baz\n"
+" \n"
+" baz\n"
+" \n"
+" ]]>\n"
+"\n"
;
public static void main(String[] s)
{
parseWithSTAX(sampleXML, configureStaxFactory());
System.exit(0);
}
public static XMLInputFactory configureStaxFactory() throws IllegalArgumentException, FactoryConfigurationError {
XMLInputFactory factory_d = TestXml.configureStaxFactory();
final String REPORT_CDATA = "http://java.sun.com/xml/stream/properties/report-cdata-event";
//Boolean enableCdataReport = Boolean.FALSE;
Boolean enableCdataReport = Boolean.TRUE;
try {
factory_d.setProperty(REPORT_CDATA, enableCdataReport);
} catch(IllegalArgumentException e) {
System.out.println("WARNING: property "+REPORT_CDATA+" not supported");
e.printStackTrace();
}
return factory_d;
}
}
stax-1.2.0.orig/src/samples/TestXml.java 0000644 0001750 0001750 00000030326 10444554662 020102 0 ustar twerner twerner // copied from http://www.dynamicobjects.com/d2r/archives/TextXML.java.txt
package samples;
import com.bea.xml.stream.util.ElementTypeNames;
import java.io.StringReader;
import java.util.Iterator;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Namespace;
import javax.xml.stream.events.XMLEvent;
import sun.security.krb5.internal.ai;
//import org.xmlpull.v1.XmlPullParser;
//import org.xmlpull.v1.XmlPullParserException;
//import org.xmlpull.v1.XmlPullParserFactory;
/**
* TextXML.java
* demonstrates bug in StAX
* Requires StAX 1.0 (JSR 173) available at http://jcp.org/en/jsr/detail?id=173
* and kXML 2 available at http://www.kxml.org/ (based on the Common XML Pull parsing API at http://www.xmlpull.org/)
*
* @author diego http://www.dynamicobjects.com/d2r/
*/
public class TestXml
{
//static String sampleXML = "\n" +
static String XML = "\n" +
"<code01>" +
"<code02>" +
"<code03>" +
"<code04>" +
"<code05>" +
"
";
public static void main(String[] s)
{
if (s != null && s.length == 1 && s[0].equals("xmlpull")) {
//parseWithXMLPull();
/*
* Result will be: (Correct)
id =
id =
id =
id =
id =
*/
}
else {
parseWithSTAX(XML);
/*
* Result will be: (Incorrect)
id = ");
break;
case XMLEvent.END_ELEMENT:
System.out.print("");
printName(xmlr);
printNamespaces(com.bea.xml.stream.XMLEventAllocatorBase.getNamespaces(xmlr));
System.out.print(">");
break;
case XMLEvent.SPACE:
case XMLEvent.CHARACTERS:
//System.out.print(xmlr.getText());
int start = xmlr.getTextStart();
int length = xmlr.getTextLength();
System.out.print(new String(xmlr.getTextCharacters(),
start,
length));
break;
case XMLEvent.PROCESSING_INSTRUCTION:
System.out.print("");
System.out.print(xmlr.getPITarget());
System.out.print(" ");
System.out.print(xmlr.getPIData());
System.out.print("?>");
break;
case XMLEvent.CDATA:
System.out.print("");
break;
case XMLEvent.COMMENT:
System.out.print("");
break;
case XMLEvent.ENTITY_REFERENCE:
System.out.print(xmlr.getLocalName()+"=");
if (xmlr.hasText())
System.out.print("["+xmlr.getText()+"]");
break;
case XMLEvent.START_DOCUMENT:
System.out.print("");
break;
}
System.out.println("]");
}
private static void printEventType(int eventType) {
System.out.print("EVENT TYPE("+eventType+"):");
System.out.println(getEventTypeString(eventType));
}
private static void printName(XMLStreamReader xmlr){
if(xmlr.hasName()){
String prefix = xmlr.getPrefix();
String uri = xmlr.getNamespaceURI();
String localName = xmlr.getLocalName();
printName(prefix,uri,localName);
}
}
private static void printName(String prefix,
String uri,
String localName) {
if (uri != null && !("".equals(uri)) ) System.out.print("['"+uri+"']:");
if (prefix != null) System.out.print(prefix+":");
if (localName != null) System.out.print(localName);
}
private static void printValue(XMLStreamReader xmlr){
if(xmlr.hasText()){
System.out.println("HAS VALUE: " + xmlr.getText());
} else {
System.out.println("HAS NO VALUE");
}
}
private static void printAttributes(XMLStreamReader xmlr){
if(xmlr.getAttributeCount()>0){
Iterator ai = com.bea.xml.stream.XMLEventAllocatorBase.getAttributes(xmlr);
while(ai.hasNext()){
System.out.print(" ");
Attribute a = (Attribute) ai.next();
printAttribute(a);
}
}
}
private static void printAttribute(Attribute a) {
printName(a.getName().getPrefix(),a.getName().getNamespaceURI(),
a.getName().getLocalPart());
System.out.print("='"+a.getValue()+"'");
}
private static void printNamespaces(Iterator ni){
while(ni.hasNext()){
System.out.print(" ");
Namespace n = (Namespace) ni.next();
printNamespace(n);
}
}
private static void printNamespace(Namespace n) {
if (n.isDefaultNamespaceDeclaration())
System.out.print("xmlns='"+n.getNamespaceURI()+"'");
else
System.out.print("xmlns:"+n.getPrefix()+"='"+n.getNamespaceURI()+"'");
}
// private static void parseWithXMLPull()
// {
// try {
// XmlPullParserFactory factory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null);
// XmlPullParser parser = factory.newPullParser();
// parser.setInput(new StringReader(sampleXML));
// parser.next();
// while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
// if (parser.getEventType() == XmlPullParser.START_TAG) {
// String element = parser.getName();
// if (element.equals("id")) {
// while (parser.getEventType() != XmlPullParser.TEXT) {
// parser.next();
// }
// String txt = parser.getText();
// System.err.println(element + " = "+txt);
// }
// }
// parser.next();
// }
// }
// catch (XmlPullParserException e) {
// e.printStackTrace();
// }
// catch (IOException e) {
// e.printStackTrace();
// }
// catch (FactoryConfigurationError e) {
// e.printStackTrace();
// }
// //parser.close();
//
// }
// private static void parseWithSTAX() throws FactoryConfigurationError
// {
//
// XMLInputFactory factory_d = XMLInputFactory.newInstance();
// factory_d.setProperty("javax.xml.stream.isValidating", Boolean.FALSE);
// factory_d.setProperty("javax.xml.stream.isCoalescing", Boolean.TRUE);
// factory_d.setProperty("javax.xml.stream.isNamespaceAware", Boolean.FALSE);
//
// try {
// XMLStreamReader parser_d = factory_d.createXMLStreamReader(new StringReader(sampleXML));
// parser_d.next();
// while (parser_d.getEventType() != XMLStreamConstants.END_DOCUMENT) {
// if (parser_d.getEventType() == XMLStreamConstants.START_ELEMENT) {
// String element = parser_d.getLocalName();
// if (element.equals("id")) {
// String txt = parser_d.getElementText();
// System.err.println(element + " = "+txt);
// }
// }
// parser_d.next();
// }
//
// parser_d.close();
// }
// catch (XMLStreamException e) {
// e.printStackTrace();
// }
// catch (NumberFormatException e) {
// e.printStackTrace();
// }
// }
}
stax-1.2.0.orig/src/samples/TestSerializeEmptyEl.java 0000644 0001750 0001750 00000003613 10444554662 022570 0 ustar twerner twerner package samples;
import java.io.StringWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
/**
* Requires StAX RI 1.0 (JSR 173) available at http://stax.codehaus.org/
* @author Alek
*/
public class TestSerializeEmptyEl
{
private final static String SOAP12 = "http://www.w3.org/2003/05/soap-envelope";
public static void doXmlOutput(boolean useRepairing) throws XMLStreamException {
StringWriter buffer = new StringWriter();
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
if (useRepairing) {
outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", Boolean.TRUE);
}
XMLStreamWriter out = outputFactory.createXMLStreamWriter(buffer);
out.writeStartDocument();
out.writeStartElement("env", "Envelope", SOAP12);
out.writeNamespace("env", SOAP12);
out.writeNamespace("test", "http://someTestUri");
out.writeStartElement("env", "Body", SOAP12);
out.writeStartElement("test");
out.writeAttribute("foo", "bar");
out.writeEndElement();
out.writeStartElement("test");
out.writeAttribute("foo", "bar");
out.writeCharacters("");
out.writeEndElement();
out.writeStartElement("test");
out.writeAttribute("foo", "bar");
out.writeCharacters(" ");
out.writeEndElement();
out.writeEndElement();
out.writeEndElement();
out.writeEndDocument();
out.close();
System.out.println("Created "+(useRepairing ? "" : "not")+" using repairing :-");
System.out.println(buffer);
}
public static void main(String[] s) throws Exception {
doXmlOutput(false);
doXmlOutput(true);
}
}
stax-1.2.0.orig/src/org/ 0000755 0001750 0001750 00000000000 10444554662 014756 5 ustar twerner twerner stax-1.2.0.orig/src/org/codehaus/ 0000755 0001750 0001750 00000000000 10444554662 016551 5 ustar twerner twerner stax-1.2.0.orig/src/org/codehaus/stax/ 0000755 0001750 0001750 00000000000 10444554662 017530 5 ustar twerner twerner stax-1.2.0.orig/src/org/codehaus/stax/test/ 0000755 0001750 0001750 00000000000 10444554662 020507 5 ustar twerner twerner stax-1.2.0.orig/src/org/codehaus/stax/test/evt/ 0000755 0001750 0001750 00000000000 10444554662 021305 5 ustar twerner twerner stax-1.2.0.orig/src/org/codehaus/stax/test/evt/TestEventWriter.java 0000644 0001750 0001750 00000014616 10444554662 025276 0 ustar twerner twerner package org.codehaus.stax.test.evt;
import java.io.StringWriter;
import java.util.*;
import javax.xml.stream.*;
import javax.xml.stream.events.*;
/**
* Class that contains simple tests for making sure that event objects
* get serialized properly when using {@link XMLEventWriter}.
*
* @author Tatu Saloranta
*/
public class TestEventWriter
extends BaseEventTest
{
public void testNonRepairingNsWrite()
throws XMLStreamException
{
XMLOutputFactory f = getOutputFactory();
StringWriter strw = new StringWriter();
XMLEventWriter w = f.createXMLEventWriter(strw);
XMLEventFactory evtf = getEventFactory();
ArrayList attrs = new ArrayList();
attrs.add(evtf.createAttribute("attr", "value"));
attrs.add(evtf.createAttribute("ns", "uri", "attr2", "value2"));
ArrayList ns = new ArrayList();
ns.add(evtf.createNamespace("ns", "uri"));
StartElement elem = evtf.createStartElement("", "", "root",
attrs.iterator(),
ns.iterator());
w.add(elem);
w.add(evtf.createEndElement("", "", "root"));
w.close();
// Ok, let's read it back:
String contents = strw.toString();
XMLStreamReader sr = getReader(contents, true, true);
assertTokenType(START_DOCUMENT, sr.getEventType());
assertTokenType(START_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
assertEquals(2, sr.getAttributeCount());
// Ordering of attrs is not guaranteed...
String ln = sr.getAttributeLocalName(0);
if (ln.equals("attr")) {
assertEquals("attr2", sr.getAttributeLocalName(1));
assertEquals("ns", sr.getAttributePrefix(1));
assertEquals("uri", sr.getAttributeNamespace(1));
} else if (ln.equals("attr2")) {
assertEquals("attr", sr.getAttributeLocalName(1));
assertEquals("ns", sr.getAttributePrefix(0));
assertEquals("uri", sr.getAttributeNamespace(0));
} else {
fail("Unexpected attr local name '"+ln+"' for attribute #0; expected 'attr' or 'attr2'");
}
assertTokenType(END_ELEMENT, sr.next());
}
/**
* The idea of this test is to basically verify that given a simplish
* input document, we can parse, output and re-parse it; and second
* time around still get the same events (at least by type, and maybe
* doing some simple sanity checks).
*/
public void testPassThrough()
throws XMLStreamException
{
final String INPUT =
""
+"\n"
+"\n"
+" \n"
+" \n"
+" \n"
+" ]]>\n"
+" \n"
+" "
+"";
;
XMLEventReader er = getEventReader(INPUT, true, true);
List list1 = collectEvents(er);
StringWriter strw = new StringWriter();
XMLOutputFactory f = getOutputFactory();
XMLEventWriter ew = f.createXMLEventWriter(strw);
Iterator it = list1.iterator();
while (it.hasNext()) {
ew.add((XMLEvent) it.next());
}
// And re-parse...
er = getEventReader(INPUT, true, true);
List list2 = collectEvents(er);
assertEquals("Should have gotten same number of events",
list1.size(), list2.size());
// And finally, let's at least compare types we have:
it = list1.iterator();
Iterator it2 = list2.iterator();
for (int ix = 0; it.hasNext(); ++ix) {
XMLEvent evt1 = (XMLEvent) it.next();
XMLEvent evt2 = (XMLEvent) it2.next();
if (evt1.getEventType() != evt2.getEventType()) {
fail("Event #"+ix+"; first time got event "+evt1.getEventType()
+", second time "+evt2.getEventType());
}
if (evt1.isStartElement()) {
/* ok, should have same attrs and ns decls. For now, let's
* just verify raw counts; can/should test contents too
* in future.
*/
StartElement se1 = evt1.asStartElement();
StartElement se2 = evt2.asStartElement();
List attrs1 = fetchElems(se1.getAttributes());
List attrs2 = fetchElems(se2.getAttributes());
assertEquals(attrs1.size(), attrs2.size());
List ns1 = fetchElems(se1.getNamespaces());
List ns2 = fetchElems(se2.getNamespaces());
assertEquals(ns1.size(), ns2.size());
}
}
}
private List fetchElems(Iterator it)
{
ArrayList l = new ArrayList();
while (it.hasNext()) {
l.add(it.next());
}
return l;
}
/*
////////////////////////////////////////
// Private methods, other
////////////////////////////////////////
*/
private XMLStreamReader getReader(String contents, boolean nsAware,
boolean coalesce)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setNamespaceAware(f, nsAware);
setCoalescing(f, coalesce);
setSupportDTD(f, true);
setValidating(f, false);
return constructStreamReader(f, contents);
}
private XMLEventReader getEventReader(String contents, boolean nsAware,
boolean coalesce)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setNamespaceAware(f, nsAware);
setCoalescing(f, coalesce);
setSupportDTD(f, true);
setValidating(f, false);
XMLStreamReader sr = constructStreamReader(f, contents);
return f.createXMLEventReader(sr);
}
private List collectEvents(XMLEventReader er)
throws XMLStreamException
{
ArrayList events = new ArrayList();
while (er.hasNext()) {
events.add(er.nextEvent());
}
return events;
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/evt/BaseEventTest.java 0000644 0001750 0001750 00000011472 10444554662 024671 0 ustar twerner twerner package org.codehaus.stax.test.evt;
import java.io.*;
import java.util.Iterator;
import javax.xml.stream.*;
import javax.xml.stream.events.*;
import org.codehaus.stax.test.BaseStaxTest;
/**
* Base class for all StaxTest unit tests that test Event API
* functionality.
*
* @author Tatu Saloranta
*/
public class BaseEventTest
extends BaseStaxTest
{
protected BaseEventTest() { super(); }
/*
///////////////////////////////////////////////////
// Utility methods
///////////////////////////////////////////////////
*/
protected XMLEventFactory getEventFactory()
throws FactoryConfigurationError
{
return XMLEventFactory.newInstance();
}
protected static XMLEventReader constructEventReader(XMLInputFactory f, String content)
throws XMLStreamException
{
return f.createXMLEventReader(new StringReader(content));
}
protected static XMLEventReader constructEventReaderForFile(XMLInputFactory f, String filename)
throws IOException, XMLStreamException
{
File inf = new File(filename);
XMLEventReader er = f.createXMLEventReader(inf.toURL().toString(),
new FileReader(inf));
return er;
}
/**
* Method that will iterate through contents of an XML document
* using specified event reader; will also access some of data
* to make sure reader reads most of lazy-loadable data.
* Method is usually called to try to get an exception for invalid
* content.
*
* @return Dummy value calculated on contents; used to make sure
* no dead code is eliminated
*/
protected int streamThrough(XMLEventReader er)
throws XMLStreamException
{
int result = 0;
while (er.hasNext()) {
XMLEvent evt = er.nextEvent();
int type = evt.getEventType();
result += type;
if (evt.isCharacters()) {
result += evt.asCharacters().getData().hashCode();
}
}
return result;
}
protected int calcAttrCount(StartElement elem)
throws XMLStreamException
{
int count = 0;
Iterator it = elem.getAttributes();
if (it != null) {
while (it.hasNext()) {
Attribute attr = (Attribute) it.next();
++count;
}
}
return count;
}
public static void checkEventIsMethods(int type, XMLEvent evt)
{
int actualType = evt.getEventType();
if (actualType != type) {
/* Minor deviation; should Characters objects that are constructed
* for CDATA and SPACE return true type or CHARACTERS?
*/
if (type == CHARACTERS &&
(actualType == SPACE || actualType == CDATA)) {
// for now let's let this pass...
} else {
assertTokenType(type, actualType); // this'll fail and output descs for types
}
}
/* Hmmh. Whether Namespace object should return true or false
* is an open question. So let's accept both
*/
if (type == NAMESPACE) {
/* for now let's just ask for it (to make sure it won't throw
* exceptions), but not verify the value
*/
boolean isAttr = evt.isAttribute();
} else {
assertEquals((type == ATTRIBUTE), evt.isAttribute());
}
assertEquals((type == CHARACTERS), evt.isCharacters());
assertEquals((type == START_DOCUMENT), evt.isStartDocument());
assertEquals((type == END_DOCUMENT), evt.isEndDocument());
assertEquals((type == START_ELEMENT), evt.isStartElement());
assertEquals((type == END_ELEMENT), evt.isEndElement());
assertEquals((type == ENTITY_REFERENCE), evt.isEntityReference());
assertEquals((type == NAMESPACE), evt.isNamespace());
assertEquals((type == PROCESSING_INSTRUCTION), evt.isProcessingInstruction());
}
/**
* Simple test utility method that just calls output method, to verify
* it does not throw anything nasty, and does output something.
* Not enough to verify actual working, but should exercise code path
* to check for fatal problems.
*/
public void testEventWritability(XMLEvent evt)
throws XMLStreamException
{
StringWriter sw = new StringWriter();
evt.writeAsEncodedUnicode(sw);
// Some events do not (have to) output anything:
switch (evt.getEventType()) {
case END_DOCUMENT: // nothing to output, usually
return;
}
assertTrue(sw.toString().length() > 0);
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/evt/TestFilteredReader.java 0000644 0001750 0001750 00000003766 10444554662 025705 0 ustar twerner twerner package org.codehaus.stax.test.evt;
import javax.xml.stream.*;
import javax.xml.stream.events.*;
/**
* Simple unit test suite that tries to if filtered stream readers are
* constructed and can be used.
*
* One thing to note, though, is that the StAX specs do not tell much
* anything about expected ways that the implementation is to deal with
* problems resulting from filtering END_DOCUMENT event and so forth.
*
* @author Tatu Saloranta
*/
public class TestFilteredReader
extends BaseEventTest
{
/**
* Simplest possible test: let's only check that we can actually
* construct an instance with dummy filter that accepts everything,
* and that we can traverse through all the events as usual.
*/
public void testCreation()
throws XMLStreamException
{
XMLEventReader er = createFilteredReader(new MyFilter(), "text", true);
assertTokenType(START_DOCUMENT, er.nextEvent().getEventType());
XMLEvent evt = er.nextEvent();
assertTokenType(START_ELEMENT, evt.getEventType());
assertNotNull(evt.asStartElement().getName());
assertTokenType(CHARACTERS, er.nextEvent().getEventType());
assertTokenType(END_ELEMENT, er.nextEvent().getEventType());
assertTokenType(END_DOCUMENT, er.nextEvent().getEventType());
}
/*
////////////////////////////////////////
// Non-test methods
////////////////////////////////////////
*/
private XMLEventReader createFilteredReader(EventFilter filter, String content,
boolean nsAware)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setNamespaceAware(f, nsAware);
XMLEventReader base = constructEventReader(f, content);
return f.createFilteredReader(base, filter);
}
final static class MyFilter
implements EventFilter
{
public boolean accept(XMLEvent event) {
return true;
}
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/evt/TestEventReader.java 0000644 0001750 0001750 00000047246 10444554662 025231 0 ustar twerner twerner package org.codehaus.stax.test.evt;
import java.util.NoSuchElementException;
import javax.xml.stream.*;
import javax.xml.stream.events.*;
import java.util.*;
/**
* Class that contains simple tests for making sure that event objects
* created by the {@link XMLEventFactory} have expected properties.
*
* @author Tatu Saloranta
*/
public class TestEventReader
extends BaseEventTest
{
public void testSimpleValid()
throws XMLStreamException
{
/* Whether prolog/epilog white space is reported is not defined
* by StAX specs, thus, let's not add any
*/
String XML = ""
+""
+"\n"
+"";
for (int i = 0; i < 4; ++i) {
boolean ns = (i & 1) != 0;
boolean coal = (i & 2) != 0;
XMLEventReader er = getReader(XML, ns, coal);
assertTokenType(START_DOCUMENT, er.nextEvent().getEventType());
assertTokenType(DTD, er.nextEvent().getEventType());
assertTokenType(START_ELEMENT, er.nextEvent().getEventType());
assertTokenType(COMMENT, er.nextEvent().getEventType());
// for fun, let's just use next() instead of nextEvent()
XMLEvent evt = (XMLEvent) er.next();
assertTokenType(CHARACTERS, evt.getEventType());
assertTokenType(END_ELEMENT, er.nextEvent().getEventType());
assertTokenType(END_DOCUMENT, er.nextEvent().getEventType());
assertFalse(er.hasNext());
er.close();
}
}
public void testInvalidUsage()
throws XMLStreamException
{
String XML = "";
for (int i = 0; i < 4; ++i) {
boolean ns = (i & 1) != 0;
boolean coal = (i & 2) != 0;
XMLEventReader er = getReader(XML, ns, coal);
XMLEvent evt = er.nextEvent();
// Let's try removal:
String msg = null;
try {
er.remove();
msg = "Was expecting UnsupportedOperationException for XMLEventReader.remove()";
} catch (UnsupportedOperationException e) {
; // good
} catch (Throwable t) {
msg = "Was expecting UnsupportedOperationException for XMLEventReader.remove(); instead got: "+t;
}
if (msg != null) {
fail(msg);
}
}
}
/**
* Test that checks that entity objects are properly returned in
* non-expanding mode
*/
public void testNonExpandingEntities()
throws XMLStreamException
{
/* Let's test all entity types
*/
String XML = ""
+"\n"
+"\n"
+"\n"
// Hmmh: can't test this, but let's declare it anyway
+"\n"
+"]>"
//+"&intEnt;&extParsedEnt;&extUnparsedEnt;"
+"&intEnt;&extParsedEnt;"
;
for (int i = 0; i < 4; ++i) {
boolean ns = (i & 1) != 0;
boolean coal = (i & 2) != 0;
// false -> do not expand entities
XMLEventReader er = getReader(XML, ns, coal, false);
assertTokenType(START_DOCUMENT, er.nextEvent().getEventType());
assertTokenType(DTD, er.nextEvent().getEventType());
XMLEvent evt = er.nextEvent();
assertTrue(evt.isStartElement());
evt = er.nextEvent();
assertTokenType(ENTITY_REFERENCE, evt.getEventType());
EntityReference ref = (EntityReference) evt;
assertNotNull(ref);
assertTrue(ref.isEntityReference());
assertEquals("intEnt", ref.getName());
EntityDeclaration ed = ref.getDeclaration();
assertNotNull("Declaration of internal entity 'intEnt' should not be null", ed);
assertEquals("intEnt", ed.getName());
assertEquals("internal", ed.getReplacementText());
assertNullOrEmpty(ed.getNotationName());
assertNullOrEmpty(ed.getPublicId());
assertNullOrEmpty(ed.getSystemId());
evt = er.nextEvent();
assertTokenType(ENTITY_REFERENCE, evt.getEventType());
ref = (EntityReference) evt;
assertNotNull(ref);
assertTrue(ref.isEntityReference());
assertEquals("extParsedEnt", ref.getName());
ed = ref.getDeclaration();
assertNotNull("Declaration of external entity 'extParsedEnt' should not be null", ed);
assertEquals("extParsedEnt", ed.getName());
assertNullOrEmpty(ed.getNotationName());
assertNullOrEmpty(ed.getPublicId());
assertEquals("url:dummy", ed.getSystemId());
/*
evt = er.nextEvent();
assertTokenType(ENTITY_REFERENCE, evt.getEventType());
ref = (EntityReference) evt;
assertEquals("extUnparsedEnt", ref.getName());
assertNotNull(ref);
assertTrue(ref.isEntityReference());
ed = ref.getDeclaration();
assertNotNull(ed);
assertEquals("notation", ed.getNotationName());
*/
evt = er.nextEvent();
assertTrue(evt.isEndElement());
assertTokenType(END_DOCUMENT, er.nextEvent().getEventType());
assertFalse(er.hasNext());
}
}
/**
* This unit test checks that a DTD event that results from parsing
* a valid document, to the degree it is done without having to
* validate anything
*/
public void testValidDtdEvent()
throws XMLStreamException
{
String XML = ""
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"]>"
+""
;
for (int i = 0; i < 4; ++i) {
boolean ns = (i & 1) != 0;
boolean coal = (i & 2) != 0;
XMLEventReader er = getReader(XML, ns, coal);
assertTokenType(START_DOCUMENT, er.nextEvent().getEventType());
XMLEvent evt = er.nextEvent();
assertTokenType(DTD, evt.getEventType());
DTD dtd = (DTD) evt;
/* isXxx() methods and writability are tested by a different
* unit test (in TestEventTypes()); here let's just check for
* entities and notations
*/
List entities = dtd.getEntities();
assertNotNull("Entity list for a DTD declaration with entities should not be null", entities);
assertEquals(3, entities.size());
// Let's also verify they are all of right type...
testListElems(entities, EntityDeclaration.class);
List notations = dtd.getNotations();
// Let's also verify they are all of right type...
testListElems(notations, NotationDeclaration.class);
assertNotNull("Notation list for a DTD declaration with notations should not be null", entities);
assertNotNull(notations);
assertEquals(2, notations.size());
}
}
/**
* The main purpose of this test is to ensure that an exception
* is thrown at the end.
*/
public void testIterationEndException()
throws XMLStreamException
{
String XML = "";
for (int i = 0; i < 4; ++i) {
boolean coal = (i & 1) != 0;
boolean checkHasNext = (i & 2) != 0;
XMLEventReader er = getReader(XML, true, coal);
assertTokenType(START_DOCUMENT, er.nextEvent().getEventType());
assertTokenType(START_ELEMENT, er.nextEvent().getEventType());
assertTokenType(END_ELEMENT, er.nextEvent().getEventType());
assertTokenType(END_DOCUMENT, er.nextEvent().getEventType());
if (checkHasNext) {
assertFalse(er.hasNext());
}
XMLEvent ev = null;
try {
ev = er.nextEvent();
} catch (NoSuchElementException nex) {
continue; // good
} catch (Throwable t) {
fail("Expected a NoSuchElementException after iterating through the document; got "+t);
}
// Shouldn't get this far...
fail("Expected a NoSuchElementException after iterating through the document; got event: "+ev);
}
}
public void testNextTagOk()
throws XMLStreamException
{
String XML = "\n"
+" "
+"";
for (int i = 0; i < 4; ++i) {
boolean ns = (i & 1) != 0;
boolean coal = (i & 2) != 0;
XMLEventReader er = getReader(XML, ns, coal);
assertTokenType(START_DOCUMENT, er.nextEvent().getEventType());
assertTokenType(START_ELEMENT, er.nextTag().getEventType());
assertTokenType(START_ELEMENT, er.nextTag().getEventType());
/* Ok, let's mix in bit of peeking to ensure reader won't
* be confused too badly...
*/
// This should be space between and ...
assertTokenType(CHARACTERS, er.peek().getEventType());
// And then the leaf
assertTokenType(START_ELEMENT, er.nextTag().getEventType());
assertTokenType(END_ELEMENT, er.nextTag().getEventType());
assertTokenType(END_ELEMENT, er.nextTag().getEventType());
assertTokenType(END_ELEMENT, er.nextTag().getEventType());
assertTokenType(END_DOCUMENT, er.nextEvent().getEventType());
assertFalse(er.hasNext());
}
}
public void testNextTagInvalid()
throws XMLStreamException
{
String XML = " non-empty";
String XML2 = "text ";
for (int i = 0; i < 4; ++i) {
boolean ns = (i & 1) != 0;
boolean coal = (i & 2) != 0;
XMLEventReader er = getReader(XML, ns, coal);
assertTokenType(START_DOCUMENT, er.nextEvent().getEventType());
assertTokenType(START_ELEMENT, er.nextEvent().getEventType());
String msg = null;
try {
XMLEvent evt = er.nextTag();
msg = "Expected a XMLStreamException when trying to call XMLEventReader.nextTag() on non-empty CHARACTERS";
} catch (XMLStreamException sex) {
// fine!
} catch (Throwable t) {
msg = "Expected a XMLStreamException when trying to call XMLEventReader.nextTag() on non-empty CHARACTERS; got ("+t.getClass()+"): "+t;
}
if (msg != null) {
fail(msg);
}
er.close();
/* any other easily failing cases? Maybe if we are on top of
* END_ELEMENT, and will hit another one?
*/
er = getReader(XML2, ns, coal);
assertTokenType(START_DOCUMENT, er.nextEvent().getEventType());
assertTokenType(START_ELEMENT, er.nextEvent().getEventType());
assertTokenType(START_ELEMENT, er.nextEvent().getEventType());
assertTokenType(END_ELEMENT, er.nextEvent().getEventType());
try {
XMLEvent evt = er.nextTag();
msg = "Expected a XMLStreamException when trying to call XMLEventReader.nextTag() on END_ELEMENT and hitting non-ws text; got event "+tokenTypeDesc(evt);
} catch (XMLStreamException sex) {
msg = null; // fine!
} catch (Throwable t) {
msg = "Expected a XMLStreamException when trying to call XMLEventReader.nextTag() on END_ELEMENT and hitting non-ws text; got: "+t;
}
if (msg != null) {
fail(msg);
}
er.close();
}
}
public void testSkip()
throws XMLStreamException
{
String XML = "\n"
+" "
+"";
for (int i = 0; i < 4; ++i) {
boolean ns = (i & 1) != 0;
boolean coal = (i & 2) != 0;
XMLEventReader er = getReader(XML, ns, coal);
XMLEvent ev;
assertTokenType(START_DOCUMENT, er.peek().getEventType());
assertTokenType(START_DOCUMENT, er.nextEvent().getEventType());
assertTokenType(DTD, er.peek().getEventType());
assertTokenType(DTD, er.nextEvent().getEventType());
assertTokenType(START_ELEMENT, er.peek().getEventType());
assertTokenType(START_ELEMENT, er.nextEvent().getEventType());
assertTokenType(CHARACTERS, er.peek().getEventType());
assertTokenType(CHARACTERS, er.nextEvent().getEventType());
// branch
assertTokenType(START_ELEMENT, er.peek().getEventType());
assertTokenType(START_ELEMENT, er.nextEvent().getEventType());
assertTokenType(CHARACTERS, er.peek().getEventType());
assertTokenType(CHARACTERS, er.nextEvent().getEventType());
// leaf
assertTokenType(START_ELEMENT, er.peek().getEventType());
assertTokenType(START_ELEMENT, er.nextEvent().getEventType());
assertTokenType(CHARACTERS, er.peek().getEventType());
assertTokenType(CHARACTERS, er.nextEvent().getEventType());
assertTokenType(END_ELEMENT, er.peek().getEventType());
assertTokenType(END_ELEMENT, er.nextEvent().getEventType());
assertTokenType(END_ELEMENT, er.peek().getEventType());
assertTokenType(END_ELEMENT, er.nextEvent().getEventType());
assertTokenType(COMMENT, er.peek().getEventType());
assertTokenType(COMMENT, er.nextEvent().getEventType());
assertTokenType(END_ELEMENT, er.peek().getEventType());
assertTokenType(END_ELEMENT, er.nextEvent().getEventType());
assertTokenType(END_DOCUMENT, er.peek().getEventType());
assertTokenType(END_DOCUMENT, er.nextEvent().getEventType());
assertFalse(er.hasNext());
}
}
/**
* This test was inspired by an actual bug in one of implementations:
* initial state was not properly set if nextTag() was called (instead
* of nextEvent()), and subsequent peek() failed.
*/
public void testPeek()
throws XMLStreamException
{
String XML = "text";
for (int i = 0; i < 4; ++i) {
boolean ns = (i & 1) != 0;
boolean coal = (i & 2) != 0;
XMLEventReader er = getReader(XML, ns, coal);
assertTokenType(START_DOCUMENT, er.nextEvent().getEventType());
XMLEvent tag = er.nextTag();
assertTokenType(START_ELEMENT, tag.getEventType());
// Now, peek() should produce text..
XMLEvent text = er.peek();
assertTokenType(CHARACTERS, text.getEventType());
Characters chars = text.asCharacters();
assertNotNull(chars);
assertEquals("text", chars.getData());
// and need nextEvent() to get rid of it, too:
text = er.nextEvent();
// Let's verify it again:
assertTokenType(CHARACTERS, text.getEventType());
chars = text.asCharacters();
assertNotNull(chars);
assertEquals("text", chars.getData());
assertTokenType(END_ELEMENT, er.nextTag().getEventType());
assertTokenType(END_DOCUMENT, er.nextEvent().getEventType());
// And at the end, peek() should return null
assertNull(er.peek());
}
}
public void testElementText()
throws XMLStreamException
{
String TEXT1 = "some\ntest";
String TEXT2 = "inside CDATA too!";
String XML = ""+TEXT1+"";
// First, let's see how things work without peeking:
for (int i = 0; i < 4; ++i) {
boolean ns = (i & 1) != 0;
boolean coal = (i & 2) != 0;
XMLEventReader er = getReader(XML, ns, coal);
assertTokenType(START_DOCUMENT, er.nextEvent().getEventType());
XMLEvent elem = er.nextEvent();
assertTokenType(START_ELEMENT, elem.getEventType());
try {
assertEquals(TEXT1+TEXT2, er.getElementText());
} catch (XMLStreamException sex) {
fail("Failed on XMLEventReader.getElementText(): "+sex);
}
/* 06-Jan-2006, TSa: I'm really not sure whether to expect
* END_ELEMENT, or END_DOCUMENT here... maybe the latter
* makes more sense? For now let's accept both, however.
*/
elem = er.nextEvent();
if (elem.getEventType() != END_DOCUMENT
&& elem.getEventType() != END_ELEMENT) {
fail("Expected END_DOCUMENT or END_ELEMENT, got "+tokenTypeDesc(elem.getEventType()));
}
}
// and then with peeking:
for (int i = 0; i < 4; ++i) {
boolean ns = (i & 1) != 0;
boolean coal = (i & 2) != 0;
XMLEventReader er = getReader(XML, ns, coal);
assertTokenType(START_DOCUMENT, er.nextEvent().getEventType());
XMLEvent elem = er.nextEvent();
assertTokenType(START_ELEMENT, elem.getEventType());
XMLEvent peeked = er.peek();
assertTokenType(CHARACTERS, peeked.getEventType());
assertEquals(TEXT1+TEXT2, er.getElementText());
/* 06-Jan-2006, TSa: I'm really not sure whether to expect
* END_ELEMENT, or END_DOCUMENT here... maybe the latter
* makes more sense? For now let's accept both, however.
*/
elem = er.nextEvent();
if (elem.getEventType() != END_DOCUMENT
&& elem.getEventType() != END_ELEMENT) {
fail("Expected END_DOCUMENT or END_ELEMENT, got "+tokenTypeDesc(elem.getEventType()));
}
}
}
/*
/////////////////////////////////////////////////
// Internal methods:
/////////////////////////////////////////////////
*/
private XMLEventReader getReader(String contents, boolean nsAware,
boolean coalesce)
throws XMLStreamException
{
return getReader(contents, nsAware, coalesce, true);
}
private XMLEventReader getReader(String contents, boolean nsAware,
boolean coalesce, boolean expandEnt)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setNamespaceAware(f, nsAware);
setCoalescing(f, coalesce);
setSupportDTD(f, true);
setValidating(f, false);
setReplaceEntities(f, expandEnt);
return constructEventReader(f, contents);
}
private void testListElems(List l, Class expType)
{
Iterator it = l.iterator();
while (it.hasNext()) {
Object o = it.next();
assertNotNull(o);
assertTrue(expType.isAssignableFrom(o.getClass()));
}
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/evt/TestEventTypes.java 0000644 0001750 0001750 00000012717 10444554662 025126 0 ustar twerner twerner package org.codehaus.stax.test.evt;
import javax.xml.namespace.QName;
import javax.xml.stream.*;
import javax.xml.stream.events.*;
/**
* Class that contains simple tests for making sure that event types
* produced have expected settings.
*
* @author Tatu Saloranta
*/
public class TestEventTypes
extends BaseEventTest
{
public void testTypes()
throws XMLStreamException
{
doTestTypes(false); // non-namespace
doTestTypes(true); // namespace-aware
}
/*
////////////////////////////////////////
// Private methods, tests
////////////////////////////////////////
*/
private void doTestTypes(boolean useNs)
throws XMLStreamException
{
String INPUT =
""
+""
+""
+""
+"some text"
+"";
XMLEventReader er = getReader(INPUT, useNs);
// First, should get START_DOCUMENT:
XMLEvent evt = er.nextEvent();
assertEquals(START_DOCUMENT, evt.getEventType());
assertTrue(evt.isStartDocument());
{
StartDocument doc = (StartDocument) evt;
assertFalse(doc.encodingSet());
/* Not sure how to test getCharacterEncodingScheme(); problem
* is, XML parser are allowed to auto-detect things... but don't
* have to.
*/
// ... same is true about system id too
if (doc.standaloneSet()) {
fail("Reporting stand-alone as set, even though xml declaration has no value (should assume 'false')");
}
// I guess parser should NOT think it is stand-alone without decl?
assertFalse("Should assume 'no' as stand-alone value if no extra information", doc.isStandalone());
}
// Then, proc. instr:
evt = er.nextEvent();
assertEquals(PROCESSING_INSTRUCTION, evt.getEventType());
assertTrue(evt.isProcessingInstruction());
{
ProcessingInstruction pi = (ProcessingInstruction) evt;
assertEquals("proc", pi.getTarget());
// data may or may not contain the space between target and data...
String data = pi.getData().trim();
assertEquals("instr", data);
}
// Then COMMENT
evt = er.nextEvent();
assertEquals(COMMENT, evt.getEventType());
{
Comment c = (Comment) evt;
assertEquals("comment - - contents", c.getText());
}
// Then DTD
evt = er.nextEvent();
assertEquals(DTD, evt.getEventType());
{
DTD dtd = (DTD) evt;
checkEventIsMethods(DTD, dtd);
testEventWritability(dtd);
assertNotNull(dtd.getDocumentTypeDeclaration());
}
// Then START_ELEMENT
evt = er.nextEvent();
assertEquals(START_ELEMENT, evt.getEventType());
assertTrue(evt.isStartElement());
QName elemName;
{
StartElement elem = evt.asStartElement();
elemName = elem.getName();
assertEquals("root", elemName.getLocalPart());
assertEquals(1, calcAttrCount(elem));
Attribute noSuchAttr = elem.getAttributeByName(new QName("foobar"));
assertNull("Should not have found attribute 'foobar' from the element", noSuchAttr);
Attribute attr = elem.getAttributeByName(new QName("attr"));
assertNotNull("Should have found attribute 'attr' from the element", attr);
assertTrue(attr.isAttribute());
assertEquals("value", attr.getValue());
assertEquals("CDATA", attr.getDTDType());
assertTrue(attr.isSpecified());
QName an = attr.getName();
assertEquals("attr", an.getLocalPart());
}
// Then CHARACTERS
evt = er.nextEvent();
assertEquals(CHARACTERS, evt.getEventType());
assertTrue(evt.isCharacters());
{
Characters ch = evt.asCharacters();
assertFalse(ch.isCData());
assertFalse(ch.isIgnorableWhiteSpace());
assertFalse(ch.isWhiteSpace());
assertEquals("some text", ch.getData());
}
// Then END_ELEMENT
evt = er.nextEvent();
assertEquals(END_ELEMENT, evt.getEventType());
assertTrue(evt.isEndElement());
{
EndElement elem = evt.asEndElement();
QName endName = elem.getName();
assertEquals("root", endName.getLocalPart());
// Let's also verify it's equal to the start element name...
assertEquals(elemName, endName);
}
// And finally END_DOCUMENT
evt = er.nextEvent();
assertEquals(END_DOCUMENT, evt.getEventType());
assertTrue(evt.isEndDocument());
// Nothing to test, but let's case to ensure it's of right type
{
EndDocument doc = (EndDocument) evt;
}
}
/*
////////////////////////////////////////
// Private methods, other
////////////////////////////////////////
*/
private XMLEventReader getReader(String contents, boolean nsAware)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setCoalescing(f, true);
setNamespaceAware(f, nsAware);
setValidating(f, false);
setSupportDTD(f, true);
return constructEventReader(f, contents);
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/evt/TestEventFactory.java 0000644 0001750 0001750 00000021545 10444554662 025430 0 ustar twerner twerner package org.codehaus.stax.test.evt;
import java.io.StringWriter;
import javax.xml.namespace.QName;
import javax.xml.stream.*;
import javax.xml.stream.events.*;
/**
* Class that contains simple tests for making sure that event objets
* created by the {@link XMLEventFactory} have expected properties.
*
* @author Tatu Saloranta
*/
public class TestEventFactory
extends BaseEventTest
{
public void testAttribute()
throws XMLStreamException
{
XMLEventFactory f = getEventFactory();
final String URI = "http://foo.com";
QName attrName = new QName(URI, "attr", "ns");
Attribute attr = f.createAttribute(attrName, "value");
checkEventIsMethods(ATTRIBUTE, attr);
testEventWritability(attr);
Attribute attr2 = f.createAttribute("ns", URI, "attr", "value'2'");
Attribute attr3 = f.createAttribute("attr", "this&more");
/* No way to associate with a DTD, should have fairly basic
* settings:
*/
assertEquals("CDATA", attr.getDTDType());
assertEquals("CDATA", attr2.getDTDType());
assertEquals("CDATA", attr3.getDTDType());
assertTrue("Attribute 'ns:attr' should be created as 'defined'",
attr.isSpecified());
assertTrue("Attribute 'ns:attr' should be created as 'defined'",
attr2.isSpecified());
assertTrue("Attribute 'attr' should be created as 'defined'",
attr3.isSpecified());
assertEquals("value", attr.getValue());
assertEquals("value'2'", attr2.getValue());
assertEquals("this&more", attr3.getValue());
// Ok, then names...
assertEquals(attrName, attr.getName());
assertEquals(attrName, attr2.getName());
QName name3 = attr3.getName();
/* Alas, QName doesn't seem to retain nulls... so let's
* be bit more lenient here:
*/
assertEquals("attr", name3.getLocalPart());
String str = name3.getPrefix();
assertTrue(str == null || str.length() == 0);
str = name3.getNamespaceURI();
assertTrue(str == null || str.length() == 0);
}
public void testCData()
throws XMLStreamException
{
final String contents = "test text & more! [[]] --";
XMLEventFactory f = getEventFactory();
Characters c = f.createCData(contents);
checkEventIsMethods(CHARACTERS, c);
testEventWritability(c);
assertEquals(contents, c.getData());
assertTrue(c.isCData());
assertFalse(c.isIgnorableWhiteSpace());
assertFalse(c.isWhiteSpace());
}
public void testCharacters()
throws XMLStreamException
{
final String contents = "test text & more! [[]] --";
XMLEventFactory f = getEventFactory();
Characters c = f.createCharacters(contents);
checkEventIsMethods(CHARACTERS, c);
testEventWritability(c);
assertEquals(contents, c.getData());
assertFalse(c.isCData());
assertFalse(c.isIgnorableWhiteSpace());
assertFalse(c.isWhiteSpace());
}
public void testComment()
throws XMLStreamException
{
final String content = "Comment - how interesting!";
XMLEventFactory f = getEventFactory();
Comment c = f.createComment(content);
checkEventIsMethods(COMMENT, c);
testEventWritability(c);
assertEquals(content, c.getText());
}
public void testDTD()
throws XMLStreamException
{
XMLEventFactory f = getEventFactory();
DTD d = f.createDTD("");
checkEventIsMethods(DTD, d);
testEventWritability(d);
// !!! TBI
}
public void testEndDocument()
throws XMLStreamException
{
XMLEventFactory f = getEventFactory();
EndDocument ed = f.createEndDocument();
// No properties -- as long as we got instance of right type, it's ok
checkEventIsMethods(END_DOCUMENT, ed);
testEventWritability(ed);
}
public void testEndElement()
throws XMLStreamException
{
XMLEventFactory f = getEventFactory();
final String LOCALNAME = "elem";
// prefix, uri, localName
EndElement ee = f.createEndElement("", "", LOCALNAME);
checkEventIsMethods(END_ELEMENT, ee);
testEventWritability(ee);
QName n = ee.getName();
assertNotNull(n);
assertEquals(LOCALNAME, n.getLocalPart());
}
public void testEntityReference()
throws XMLStreamException
{
XMLEventFactory f = getEventFactory();
/* 22-Dec-2005, TSa: ... but how can we create the entity declaration
* that is needed? Should null be ok? For now, can't really test...
*/
//EntityReference ref = f.createEntityReference("ref", decl);
//checkEventIsMethods(ENTITY_REFERENCE, ref);
//testEventWritability(ref);
}
public void testIgnorableSpace()
throws XMLStreamException
{
final String contents = " \t \n ";
XMLEventFactory f = getEventFactory();
Characters c = f.createIgnorableSpace(contents);
checkEventIsMethods(CHARACTERS, c);
testEventWritability(c);
assertEquals(contents, c.getData());
assertFalse(c.isCData());
assertTrue(c.isIgnorableWhiteSpace());
assertTrue(c.isWhiteSpace());
}
public void testNamespace()
throws XMLStreamException
{
XMLEventFactory f = getEventFactory();
final String PREFIX = "prefix";
final String URI = "http://foo";
// First default:
Namespace ns = f.createNamespace(URI);
checkEventIsMethods(NAMESPACE, ns);
testEventWritability(ns);
String prefix = ns.getPrefix();
// Both null and empty are ok?
if (prefix != null && prefix.length() > 0) {
fail("Expected prefix to be null or empty for default namespace event object");
}
assertEquals(URI, ns.getNamespaceURI());
assertTrue(ns.isDefaultNamespaceDeclaration());
// Then non-default:
ns = f.createNamespace(PREFIX, URI);
checkEventIsMethods(NAMESPACE, ns);
assertEquals(PREFIX, ns.getPrefix());
assertEquals(URI, ns.getNamespaceURI());
assertFalse(ns.isDefaultNamespaceDeclaration());
}
public void testProcInstr()
throws XMLStreamException
{
XMLEventFactory f = getEventFactory();
ProcessingInstruction pi = f.createProcessingInstruction("target", "data");
checkEventIsMethods(PROCESSING_INSTRUCTION, pi);
testEventWritability(pi);
assertEquals("target", pi.getTarget());
assertEquals("data", pi.getData());
}
public void testSpace()
throws XMLStreamException
{
final String contents = " \t \n ";
XMLEventFactory f = getEventFactory();
Characters c = f.createSpace(contents);
assertEquals(contents, c.getData());
checkEventIsMethods(CHARACTERS, c);
testEventWritability(c);
assertFalse(c.isCData());
assertFalse(c.isIgnorableWhiteSpace());
assertTrue(c.isWhiteSpace());
}
public void testStartDocument()
throws XMLStreamException
{
XMLEventFactory f = getEventFactory();
StartDocument sd = f.createStartDocument();
checkEventIsMethods(START_DOCUMENT, sd);
testEventWritability(sd);
assertFalse(sd.encodingSet());
assertFalse(sd.standaloneSet());
final String ENCODING = "ISO-8859-1";
final String VERSION = "1.0";
sd = f.createStartDocument(ENCODING, VERSION, true);
checkEventIsMethods(START_DOCUMENT, sd);
assertTrue(sd.encodingSet());
assertTrue(sd.standaloneSet());
assertEquals(ENCODING, sd.getCharacterEncodingScheme());
assertEquals(VERSION, sd.getVersion());
}
public void testStartElement()
throws XMLStreamException
{
final String LOCALNAME = "root";
final String PREFIX = "ns";
final String URI = "urn:whatever";
XMLEventFactory f = getEventFactory();
// prefix, uri, localname
StartElement se = f.createStartElement("", "", LOCALNAME);
testEventWritability(se);
checkEventIsMethods(START_ELEMENT, se);
QName n = se.getName();
assertNotNull(n);
assertEquals(LOCALNAME, n.getLocalPart());
se = f.createStartElement(PREFIX, URI, LOCALNAME);
checkEventIsMethods(START_ELEMENT, se);
n = se.getName();
assertNotNull(n);
assertEquals(LOCALNAME, n.getLocalPart());
assertEquals(PREFIX, n.getPrefix());
assertEquals(URI, n.getNamespaceURI());
}
/*
////////////////////////////////////////
// Private methods, tests
////////////////////////////////////////
*/
}
stax-1.2.0.orig/src/org/codehaus/stax/test/evt/TestStartElem.java 0000644 0001750 0001750 00000022742 10444554662 024717 0 ustar twerner twerner package org.codehaus.stax.test.evt;
import java.util.*;
import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
import javax.xml.stream.*;
import javax.xml.stream.events.*;
/**
* Unit tests for testing that START_ELEMENT event object behaves
* as expected
*
* @author Tatu Saloranta
*/
public class TestStartElem
extends BaseEventTest
{
/**
* Simple tests to ensure that the namespace declarations are properly
* parsed and accessible via {@link StartElement}.
*/
public void testStartElemNs()
throws XMLStreamException
{
String XML = "";
XMLEventReader er = getReader(XML, true, false);
assertTokenType(START_DOCUMENT, er.nextEvent().getEventType());
XMLEvent evt = er.nextEvent();
assertTokenType(START_ELEMENT, evt.getEventType());
// Ok, got the start element... is it ok?
assertTrue(evt.isStartElement());
StartElement se = evt.asStartElement();
NamespaceContext nsCtxt = se.getNamespaceContext();
assertNotNull("StartElement.getNamespaceContext() should never return null", nsCtxt);
// First, ones we shouldn't get:
assertNull(nsCtxt.getPrefix("a"));
assertNull(nsCtxt.getPrefix("http://foobar"));
assertNull(nsCtxt.getNamespaceURI("b"));
assertNull(nsCtxt.getNamespaceURI("http://my"));
{
Iterator it = nsCtxt.getPrefixes("http://foobar");
// Specs don't specify if we should get null, or empty iterator
assertTrue((it == null) || !it.hasNext());
it = nsCtxt.getPrefixes("a");
assertTrue((it == null) || !it.hasNext());
}
// Then ones we should:
assertEquals("a", nsCtxt.getPrefix("ns:attrs"));
assertEquals("", nsCtxt.getPrefix("http://my"));
assertEquals("http://my", nsCtxt.getNamespaceURI(""));
assertEquals("ns:attrs", nsCtxt.getNamespaceURI("a"));
// Plus, let's check the other namespace access:
Iterator it = se.getNamespaces();
assertEquals(2, countElements(it));
assertTokenType(END_ELEMENT, er.nextEvent().getEventType());
assertTokenType(END_DOCUMENT, er.nextEvent().getEventType());
assertFalse(er.hasNext());
}
public void testNestedStartElemNs()
throws XMLStreamException
{
String XML = ""
+""
+""
+"";
XMLEventReader er = getReader(XML, true, false);
assertTokenType(START_DOCUMENT, er.nextEvent().getEventType());
XMLEvent evt = er.nextEvent();
assertTokenType(START_ELEMENT, evt.getEventType());
StartElement se = evt.asStartElement();
// Let's first check that it has 1 declaration:
assertEquals(0, countElements(se.getNamespaces()));
NamespaceContext nsCtxt = se.getNamespaceContext();
assertNotNull("StartElement.getNamespaceContext() should never return null", nsCtxt);
assertNull(nsCtxt.getPrefix("a"));
assertNull(nsCtxt.getNamespaceURI("b"));
// then first leaf:
evt = er.nextEvent();
assertTrue(evt.isStartElement());
se = evt.asStartElement();
assertEquals("leaf", se.getName().getLocalPart());
assertEquals(1, countElements(se.getNamespaces()));
assertEquals("x", se.getName().getNamespaceURI());
nsCtxt = se.getNamespaceContext();
assertEquals("x", nsCtxt.getNamespaceURI(""));
assertEquals("", nsCtxt.getPrefix("x"));
assertTrue(er.nextEvent().isEndElement());
// Ok, branch:
evt = er.nextEvent();
assertTrue(evt.isStartElement());
se = evt.asStartElement();
assertEquals("branch", se.getName().getLocalPart());
assertEquals(2, countElements(se.getNamespaces()));
nsCtxt = se.getNamespaceContext();
assertEquals("a", nsCtxt.getPrefix("b"));
assertEquals("b", nsCtxt.getNamespaceURI("a"));
assertEquals("x", nsCtxt.getPrefix("url"));
assertEquals("url", nsCtxt.getNamespaceURI("x"));
// second leaf
evt = er.nextEvent();
assertTrue(evt.isStartElement());
se = evt.asStartElement();
nsCtxt = se.getNamespaceContext();
assertEquals("leaf", se.getName().getLocalPart());
// only one declared in this particular element
assertEquals(1, countElements(se.getNamespaces()));
// but should still show the other bound ns from parent
nsCtxt = se.getNamespaceContext();
assertEquals("a", nsCtxt.getPrefix("c"));
assertEquals("c", nsCtxt.getNamespaceURI("a"));
assertEquals("x", nsCtxt.getPrefix("url"));
assertEquals("url", nsCtxt.getNamespaceURI("x"));
// ok, but how about masking:
assertNull(nsCtxt.getPrefix("b"));
// Ok, fine... others we don't care about:
assertTrue(er.nextEvent().isEndElement());
}
/**
* Another unit test, one that checks a special case of namespace
* enclosures and namespace context objects.
*/
public void testNestedStartElemNs2()
throws XMLStreamException
{
String XML = "";
XMLEventReader er = getReader(XML, true, false);
assertTokenType(START_DOCUMENT, er.nextEvent().getEventType());
XMLEvent evt = er.nextEvent(); // root
assertTokenType(START_ELEMENT, evt.getEventType());
StartElement se = evt.asStartElement();
assertEquals("root", se.getName().getLocalPart());
assertEquals(0, countElements(se.getNamespaces()));
evt = er.nextEvent(); // branch
assertTokenType(START_ELEMENT, evt.getEventType());
se = evt.asStartElement();
assertEquals("branch", se.getName().getLocalPart());
assertEquals(1, countElements(se.getNamespaces()));
NamespaceContext nsCtxt = se.getNamespaceContext();
assertNotNull("StartElement.getNamespaceContext() should never return null", nsCtxt);
assertEquals("url", nsCtxt.getNamespaceURI("a"));
assertEquals("a", nsCtxt.getPrefix("url"));
evt = er.nextEvent(); // leaf
assertTokenType(START_ELEMENT, evt.getEventType());
se = evt.asStartElement();
assertEquals("leaf", se.getName().getLocalPart());
assertEquals(0, countElements(se.getNamespaces()));
nsCtxt = se.getNamespaceContext();
assertEquals("url", nsCtxt.getNamespaceURI("a"));
assertEquals("a", nsCtxt.getPrefix("url"));
assertTrue(er.nextEvent().isEndElement()); // /leaf
assertTrue(er.nextEvent().isEndElement()); // /branch
assertTrue(er.nextEvent().isEndElement()); // /root
}
/**
* Test to check that attributes can be accessed normally via
* {@link StartElement} instances.
*/
public void testStartElemAttrs()
throws XMLStreamException
{
String XML = "";
XMLEventReader er = getReader(XML, true, false);
assertTokenType(START_DOCUMENT, er.nextEvent().getEventType());
XMLEvent evt = er.nextEvent();
assertTokenType(START_ELEMENT, evt.getEventType());
StartElement se = evt.asStartElement();
assertAttr(se, "", "attr1", "value1");
assertAttr(se, "ns:attrs", "attr2", "value2");
assertAttr(se, "", "attr2", null);
assertAttr(se, "ns:attrs", "attr1", null);
evt = er.nextEvent();
assertTokenType(START_ELEMENT, evt.getEventType());
se = evt.asStartElement();
// One we should find (note: def. ns is not used!)
assertAttr(se, "", "attr", "x");
// and then ones that aren't there...
assertAttr(se, "url:ns2", "attr", null);
assertAttr(se, "url:ns2", "x", null);
assertAttr(se, "ns:foo", "foobar", null);
assertAttr(se, "", "attr1", null);
assertTokenType(END_ELEMENT, er.nextEvent().getEventType());
assertTokenType(END_ELEMENT, er.nextEvent().getEventType());
assertTokenType(END_DOCUMENT, er.nextEvent().getEventType());
}
/*
/////////////////////////////////////////////////
// Internal methods:
/////////////////////////////////////////////////
*/
private int countElements(Iterator it) {
int count = 0;
if (it != null) {
while (it.hasNext()) {
++count;
it.next();
}
}
return count;
}
private void assertAttr(StartElement se, String nsURI, String localName,
String expValue)
{
QName qn = new QName(nsURI, localName);
Attribute attr = se.getAttributeByName(qn);
if (expValue == null) {
assertNull("Should not find attribute '"+qn+"'", attr);
} else {
assertNotNull("Should find attribute '"+qn+"' but got null", attr);
assertEquals("Attribute '"+qn+"' has unexpected value",
expValue, attr.getValue());
}
}
private XMLEventReader getReader(String contents, boolean nsAware,
boolean coalesce)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setNamespaceAware(f, nsAware);
setCoalescing(f, coalesce);
setSupportDTD(f, true);
setValidating(f, false);
return constructEventReader(f, contents);
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/wstream/ 0000755 0001750 0001750 00000000000 10444554662 022171 5 ustar twerner twerner stax-1.2.0.orig/src/org/codehaus/stax/test/wstream/TestSimpleWriter.java 0000644 0001750 0001750 00000050030 10444554662 026320 0 ustar twerner twerner package org.codehaus.stax.test.wstream;
import javax.xml.stream.*;
import java.io.*;
/**
* Set of unit tests for verifying operation of {@link XMLStreamWriter}
* in "non-repairing" mode. It also includes writer tests for things
* for which repair/non-repair modes should not matter (comments, PIs
* etc).
*
* @author Tatu Saloranta
*/
public class TestSimpleWriter
extends BaseWriterTest
{
final String ISO_LATIN_ENCODING = "ISO-8859-1";
public void testCData()
throws IOException, XMLStreamException
{
StringWriter strw = new StringWriter();
XMLStreamWriter w = getNonRepairingWriter(strw);
final String CDATA_TEXT = "Let's test it with some ]] ]> data; s and && chars and all!";
w.writeStartDocument();
w.writeStartElement("test");
w.writeCData(CDATA_TEXT);
w.writeEndElement();
w.writeEndDocument();
w.close();
// And then let's parse and verify it all:
XMLStreamReader sr = constructNsStreamReader(strw.toString(), true);
assertTokenType(START_DOCUMENT, sr.getEventType());
assertTokenType(START_ELEMENT, sr.next());
// Now, parsers are allowed to report CHARACTERS or CDATA
int tt = sr.next();
if (tt != CHARACTERS && tt != CDATA) {
assertTokenType(CDATA, tt); // to cause failure
}
assertFalse(sr.isWhiteSpace());
assertEquals(CDATA_TEXT, getAndVerifyText(sr));
assertTokenType(END_ELEMENT, sr.next());
assertTokenType(END_DOCUMENT, sr.next());
}
public void testCharacters()
throws IOException, XMLStreamException
{
StringWriter strw = new StringWriter();
XMLStreamWriter w = getNonRepairingWriter(strw);
final String TEXT = "Ok; some content\nwith linefeeds and stuff (let's leave encoding as is though, no entities)\n";
w.writeStartDocument();
w.writeStartElement("test");
w.writeCharacters(TEXT);
w.writeStartElement("leaf");
// Let's also test the other method...
char[] tmp = new char[TEXT.length() + 4];
TEXT.getChars(0, TEXT.length(), tmp, 2);
w.writeCharacters(tmp, 2, TEXT.length());
w.writeEndElement();
w.writeEndElement();
w.writeEndDocument();
w.close();
// And then let's parse and verify it all:
XMLStreamReader sr = constructNsStreamReader(strw.toString(), true);
assertTokenType(START_DOCUMENT, sr.getEventType());
assertTokenType(START_ELEMENT, sr.next());
assertTokenType(CHARACTERS, sr.next());
assertFalse(sr.isWhiteSpace());
assertEquals(TEXT, getAndVerifyText(sr));
assertTokenType(START_ELEMENT, sr.next());
assertTokenType(CHARACTERS, sr.next());
assertFalse(sr.isWhiteSpace());
assertEquals(TEXT, getAndVerifyText(sr));
assertTokenType(END_ELEMENT, sr.next());
assertTokenType(END_ELEMENT, sr.next());
assertTokenType(END_DOCUMENT, sr.next());
}
public void testComment()
throws IOException, XMLStreamException
{
StringWriter strw = new StringWriter();
XMLStreamWriter w = getNonRepairingWriter(strw);
final String COMMENT1 = "comments are cool";
final String COMMENT2 = " some more\ncomments & other stuff";
final String COMMENT3 = "Hah: ";
final String COMMENT4 = " - - - \t - - \t";
w.writeStartDocument();
// Let's start with a comment
w.writeComment(COMMENT1);
w.writeStartElement("root");
w.writeCharacters(" ");
w.writeComment(COMMENT2);
w.writeStartElement("branch");
w.writeEndElement();
w.writeStartElement("branch");
w.writeComment(COMMENT3);
w.writeEndElement();
w.writeEndElement();
// and trailing comment too
w.writeComment(COMMENT4);
w.writeEndDocument();
w.close();
// And then let's parse and verify it all:
XMLStreamReader sr = constructNsStreamReader(strw.toString());
assertTokenType(START_DOCUMENT, sr.getEventType());
// First, PI with just target:
assertTokenType(COMMENT, sr.next());
assertEquals(COMMENT1, sr.getText());
// start root element:
assertTokenType(START_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
int tt = sr.next();
if (tt != CHARACTERS && tt != SPACE) {
fail("Expected a single space (CHARACTERS or SPACE), got "
+tokenTypeDesc(tt));
}
assertTokenType(COMMENT, sr.next());
assertEquals(COMMENT2, sr.getText());
// empty element ('branch')
assertTokenType(START_ELEMENT, sr.next());
assertEquals("branch", sr.getLocalName());
assertTokenType(END_ELEMENT, sr.next());
assertEquals("branch", sr.getLocalName());
// another 'branch' element:
assertTokenType(START_ELEMENT, sr.next());
assertEquals("branch", sr.getLocalName());
assertTokenType(COMMENT, sr.next());
assertEquals(COMMENT3, sr.getText());
assertTokenType(END_ELEMENT, sr.next());
assertEquals("branch", sr.getLocalName());
// closing root element
assertTokenType(END_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
// trailing (prolog) comment:
assertTokenType(COMMENT, sr.next());
assertEquals(COMMENT4, sr.getText());
assertTokenType(END_DOCUMENT, sr.next());
}
public void testDTD()
throws IOException, XMLStreamException
{
// !!! TBI
}
/**
* Unit test that tests how element writing works, including
* checks for the namespace output.
*/
public void testElements()
throws IOException, XMLStreamException
{
StringWriter strw = new StringWriter();
XMLStreamWriter w = getNonRepairingWriter(strw);
final String URL_P1 = "http://p1.org";
final String URL_P2 = "http://ns.p2.net/yeehaw.html";
final String URL_DEF = "urn:default";
final String TEXT = " some text\n";
w.writeStartDocument();
w.setPrefix("p1", URL_P1);
w.writeStartElement("test");
w.writeNamespace("p1", URL_P1);
w.setDefaultNamespace(URL_DEF);
w.setPrefix("p2", URL_P2);
w.writeStartElement("", "branch", URL_DEF);
w.writeDefaultNamespace(URL_DEF);
w.writeNamespace("p2", URL_P2);
// Ok, let's see that we can also clear out the def ns:
w.setDefaultNamespace("");
w.writeStartElement("", "leaf", "");
w.writeDefaultNamespace("");
w.writeCharacters(TEXT);
w.writeEndElement(); // first leaf
w.writeEmptyElement(URL_P1, "leaf"); // second leaf
w.writeEndElement(); // branch
w.writeEndElement(); // root elem
w.writeEndDocument();
w.close();
/* And then let's parse and verify it all:
*/
XMLStreamReader sr = constructNsStreamReader(strw.toString());
assertTokenType(START_DOCUMENT, sr.getEventType());
// root element
assertTokenType(START_ELEMENT, sr.next());
assertEquals("test", sr.getLocalName());
assertNoPrefixOrNs(sr);
assertEquals(1, sr.getNamespaceCount());
assertEquals("p1", sr.getNamespacePrefix(0));
assertEquals(URL_P1, sr.getNamespaceURI(0));
// first branch:
assertTokenType(START_ELEMENT, sr.next());
assertEquals("branch", sr.getLocalName());
assertEquals(2, sr.getNamespaceCount());
assertNoPrefix(sr);
assertEquals(URL_DEF, sr.getNamespaceURI());
// leaf
assertTokenType(START_ELEMENT, sr.next());
assertEquals("leaf", sr.getLocalName());
assertEquals(1, sr.getNamespaceCount());
assertNoPrefix(sr);
assertTokenType(CHARACTERS, sr.next());
assertEquals(TEXT, getAllText(sr));
// not: getAllText ^^^ moves cursor!
assertTokenType(END_ELEMENT, sr.getEventType());
assertEquals("leaf", sr.getLocalName());
assertNoPrefixOrNs(sr);
// another leaf:
assertTokenType(START_ELEMENT, sr.next());
assertEquals("leaf", sr.getLocalName());
assertEquals(0, sr.getNamespaceCount());
assertEquals("p1", sr.getPrefix());
assertEquals(URL_P1, sr.getNamespaceURI());
assertTokenType(END_ELEMENT, sr.next());
assertEquals("leaf", sr.getLocalName());
assertEquals("p1", sr.getPrefix());
assertEquals(URL_P1, sr.getNamespaceURI());
// (close) branch
try { // catching exception to add more info to failure msg...
assertTokenType(END_ELEMENT, sr.next());
} catch (XMLStreamException sex) {
fail("Failed when trying to match (input '"+strw+"'): "+sex);
}
assertEquals("branch", sr.getLocalName());
assertNoPrefix(sr);
// closing root element
assertTokenType(END_ELEMENT, sr.next());
assertEquals("test", sr.getLocalName());
assertNoPrefixOrNs(sr);
assertTokenType(END_DOCUMENT, sr.next());
}
/**
* Unit tests for documents that just do not use namespaces (independent
* of whether namespace support is enabled for the writer or not)
*/
public void testNonNsElements()
throws IOException, XMLStreamException
{
StringWriter strw = new StringWriter();
XMLStreamWriter w = getNonRepairingWriter(strw);
final String TEXT = "Just some text...";
final String TEXT_SPACE = "\n ";
w.writeStartDocument();
w.writeStartElement("doc");
w.writeCharacters(TEXT);
w.writeStartElement("branch");
w.writeEndElement();
w.writeCharacters(TEXT_SPACE);
w.writeStartElement("branch.2");
w.writeCData(TEXT);
w.writeEndElement();
w.writeEmptyElement("_empty");
w.writeEndElement();
w.writeEndDocument();
w.close();
// And then let's parse and verify it all:
XMLStreamReader sr = constructNsStreamReader(strw.toString());
assertTokenType(START_DOCUMENT, sr.getEventType());
// opening doc element
assertTokenType(START_ELEMENT, sr.next());
assertEquals("doc", sr.getLocalName());
assertNoPrefixOrNs(sr);
assertTokenType(CHARACTERS, sr.next());
assertEquals(TEXT, getAllText(sr));
// not: getAllText ^^^ moves cursor!
// branch elements:
assertTokenType(START_ELEMENT, sr.getEventType());
assertEquals("branch", sr.getLocalName());
assertNoPrefixOrNs(sr);
assertTokenType(END_ELEMENT, sr.next());
assertEquals("branch", sr.getLocalName());
assertNoPrefixOrNs(sr);
assertTokenType(CHARACTERS, sr.next());
assertEquals(TEXT_SPACE, getAllText(sr));
assertTokenType(START_ELEMENT, sr.getEventType());
assertEquals("branch.2", sr.getLocalName());
assertNoPrefixOrNs(sr);
assertTextualTokenType(sr.next());
assertEquals(TEXT, getAllText(sr));
assertTokenType(END_ELEMENT, sr.getEventType());
assertEquals("branch.2", sr.getLocalName());
assertNoPrefixOrNs(sr);
assertTokenType(START_ELEMENT, sr.next());
assertEquals("_empty", sr.getLocalName());
assertNoPrefixOrNs(sr);
assertTokenType(END_ELEMENT, sr.next());
assertEquals("_empty", sr.getLocalName());
assertNoPrefixOrNs(sr);
// closing doc element
try {
assertTokenType(END_ELEMENT, sr.next());
} catch (XMLStreamException sex) {
fail("Failed when trying to match (input '"+strw+"'): "+sex);
}
assertEquals("doc", sr.getLocalName());
assertNoPrefixOrNs(sr);
assertTokenType(END_DOCUMENT, sr.next());
}
public void testEmptyElements()
throws IOException, XMLStreamException
{
StringWriter strw = new StringWriter();
XMLStreamWriter w = getNonRepairingWriter(strw);
w.writeStartDocument();
w.writeStartElement("root");
w.writeStartElement("branch");
w.writeEmptyElement("leaf");
w.writeEndElement(); // branch
w.writeComment("comment"); // should be at same level as branch
w.writeEndElement(); // root elem
w.writeEndDocument();
w.close();
/* And then let's parse and verify it all:
*/
//System.err.println("DEBUG: doc = '"+strw.toString()+"'");
XMLStreamReader sr = constructNsStreamReader(strw.toString());
assertTokenType(START_DOCUMENT, sr.getEventType());
// root element
assertTokenType(START_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
// branch:
assertTokenType(START_ELEMENT, sr.next());
assertEquals("branch", sr.getLocalName());
// leaf
assertTokenType(START_ELEMENT, sr.next());
assertEquals("leaf", sr.getLocalName());
assertTokenType(END_ELEMENT, sr.next());
assertEquals("leaf", sr.getLocalName());
assertTokenType(END_ELEMENT, sr.next());
assertEquals("branch", sr.getLocalName());
assertTokenType(COMMENT, sr.next());
assertEquals("comment", getAndVerifyText(sr));
assertTokenType(END_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
assertTokenType(END_DOCUMENT, sr.next());
}
public void testEntityRef()
throws IOException, XMLStreamException
{
// !!! TBI
}
public void testProcInstr()
throws IOException, XMLStreamException
{
StringWriter strw = new StringWriter();
XMLStreamWriter w = getNonRepairingWriter(strw);
final String LONG_DATA = "content & spaces ... \t ";
final String LONG_DATA2 = "? >? ? > ";
w.writeStartDocument();
// Let's start with a proc instr:
w.writeProcessingInstruction("my_target");
w.writeStartElement("root");
w.writeCharacters("x");
w.writeProcessingInstruction("target", "data");
w.writeStartElement("branch");
w.writeEndElement();
w.writeStartElement("branch");
w.writeProcessingInstruction("t", LONG_DATA);
w.writeEndElement();
w.writeEndElement();
// and trailing proc instr too
w.writeProcessingInstruction("xxx", LONG_DATA2);
w.writeEndDocument();
w.close();
// And then let's parse and verify it all:
XMLStreamReader sr = constructNsStreamReader(strw.toString());
assertTokenType(START_DOCUMENT, sr.getEventType());
// First, PI with just target:
assertTokenType(PROCESSING_INSTRUCTION, sr.next());
assertEquals("my_target", sr.getPITarget());
String data = sr.getPIData();
if (data != null && data.length() > 0) {
fail("Expected empty (or null) data; got '"+data+"'");
}
// start root element:
assertTokenType(START_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
assertTokenType(CHARACTERS, sr.next());
assertEquals("x", sr.getText());
// 'full' PI:
assertTokenType(PROCESSING_INSTRUCTION, sr.next());
assertEquals("target", sr.getPITarget());
assertEquals("data", sr.getPIData());
// empty element ('branch')
assertTokenType(START_ELEMENT, sr.next());
assertEquals("branch", sr.getLocalName());
assertTokenType(END_ELEMENT, sr.next());
assertEquals("branch", sr.getLocalName());
// another 'branch' element:
assertTokenType(START_ELEMENT, sr.next());
assertEquals("branch", sr.getLocalName());
assertTokenType(PROCESSING_INSTRUCTION, sr.next());
assertEquals("t", sr.getPITarget());
assertEquals(LONG_DATA, sr.getPIData());
assertTokenType(END_ELEMENT, sr.next());
assertEquals("branch", sr.getLocalName());
// closing root element
assertTokenType(END_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
// trailing (prolog) PI:
assertTokenType(PROCESSING_INSTRUCTION, sr.next());
assertEquals("xxx", sr.getPITarget());
assertEquals(LONG_DATA2, sr.getPIData());
assertTokenType(END_DOCUMENT, sr.next());
}
public void testXmlDeclImplicit()
throws IOException, XMLStreamException
{
doTextXmlDecl(3);
}
public void testXmlDecl0args()
throws IOException, XMLStreamException
{
doTextXmlDecl(0);
}
public void testXmlDecl1arg()
throws IOException, XMLStreamException
{
doTextXmlDecl(1);
}
public void testXmlDecl2args()
throws IOException, XMLStreamException
{
doTextXmlDecl(2);
}
/*
//////////////////////////////////
// Private methods
//////////////////////////////////
*/
private void doTextXmlDecl(int i)
throws IOException, XMLStreamException
{
/* 4 modes: writeStartDocument with 0 args, 1 arg, 2 args,
* and without a call
*/
StringWriter strw = new StringWriter();
XMLStreamWriter w = getNonRepairingWriter(strw);
switch (i) {
case 0:
w.writeStartDocument();
break;
case 1:
/* Might well be ok to output other than 1.0, but the
* reader may choke on others (like 1.1)?
*/
w.writeStartDocument("1.0");
break;
case 2:
w.writeStartDocument(ISO_LATIN_ENCODING, "1.0");
break;
case 3:
// No output (shouldn't print out xml decl)
break;
}
w.writeEmptyElement("root");
w.writeEndDocument();
w.close();
XMLStreamReader sr = constructNsStreamReader(strw.toString());
assertTokenType(START_DOCUMENT, sr.getEventType());
// correct version?
if (i == 3) {
// Shouldn't have output anything:
String ver = sr.getVersion();
if (ver != null && ver.length() > 0) {
fail("Non-null/empty version ('"+ver+"') when no START_DOCUMENT written explicitly");
}
} else {
assertEquals("1.0", sr.getVersion());
}
// encoding?
String enc = sr.getCharacterEncodingScheme();
switch (i) {
case 0:
/* Not sure why the encoding has to default to utf-8... would
* make sense to rather leave it out
*/
/* quick note: the proper usage (as per xml specs) would be to
* use UTF-8; Stax 1.0 mentions "utf-8", so let's accept
* both for now (but let's not accept mixed cases)
*/
if (!"utf-8".equals(enc) && !"UTF-8".equals(enc)) {
fail("Expected either 'UTF-8' (xml specs) or 'utf-8' (stax specs) as the encoding output with no-arg 'writeStartDocument()' call");
}
break;
case 1:
/* Interestingly enough, API comments do not indicate an encoding
* default for 1-arg method!
*/
assertNull(enc);
break;
case 2:
assertEquals(ISO_LATIN_ENCODING, enc);
break;
case 3:
assertNull(enc);
break;
}
// What should sr.getEncoding() return? null? can't check...
/* but stand-alone we can check; specifically:
*/
assertFalse("XMLStreamReader.standalonSet() should return false if pseudo-attr not found",
sr.standaloneSet());
/* now... it's too bad there's no way to explicitly specify
* stand-alone value... so probably can not really test the
* other method
*/
//assertFalse("XMLStreamReader.isStandalone() should return false if pseudo-attr not found", sr.isStandalone());
sr.close();
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/wstream/BaseWriterTest.java 0000644 0001750 0001750 00000001635 10444554662 025750 0 ustar twerner twerner package org.codehaus.stax.test.wstream;
import java.io.*;
import javax.xml.stream.*;
import org.codehaus.stax.test.BaseStaxTest;
/**
* Base class for all StaxTest unit tests that test basic
* stream (cursor) writer API functionality.
*
* @author Tatu Saloranta
*/
public class BaseWriterTest
extends BaseStaxTest
{
public XMLStreamWriter getRepairingWriter(Writer w)
throws XMLStreamException
{
XMLOutputFactory f = getOutputFactory();
f.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES,
Boolean.TRUE);
return f.createXMLStreamWriter(w);
}
public XMLStreamWriter getNonRepairingWriter(Writer w)
throws XMLStreamException
{
XMLOutputFactory f = getOutputFactory();
f.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES,
Boolean.FALSE);
return f.createXMLStreamWriter(w);
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/wstream/TestRepairingWriter.java 0000644 0001750 0001750 00000021622 10444554662 027014 0 ustar twerner twerner package org.codehaus.stax.test.wstream;
import java.io.*;
import javax.xml.stream.*;
/**
* Set of unit tests for verifying operation of {@link XMLStreamWriter}
* in "repairing" mode.
*
* @author Tatu Saloranta
*/
public class TestRepairingWriter
extends BaseWriterTest
{
/**
* Test similar to the one in {@link TestSimpleWriter}.
*/
public void testElements()
throws IOException, XMLStreamException
{
StringWriter strw = new StringWriter();
XMLStreamWriter w = getRepairingWriter(strw);
final String URL_P1 = "http://p1.org";
final String URL_P2 = "http://ns.p2.net/yeehaw.html";
final String URL_DEF = "urn:default";
final String TEXT = " some text\n";
w.writeStartDocument();
/* Calling setPrefix() should be optional; but if we call it,
* exceptation is that it does properly cause URL to be bound.
*/
w.setPrefix("p1", URL_P1);
w.writeStartElement(URL_P1, "test");
w.writeStartElement("p2", "branch", URL_P2);
// And then a dynamically created prefix...
w.writeStartElement(URL_DEF, "leaf");
w.writeCharacters(TEXT);
w.writeEndElement(); // first leaf
w.writeEmptyElement(URL_P1, "leaf"); // second leaf
w.writeStartElement("", "third"); // may need dynamic NS too
w.writeEndElement();
w.writeEndElement(); // branch
w.writeEndElement(); // root elem
w.writeEndDocument();
w.close();
// And then let's parse and verify it all:
//System.err.println("Doc -> '"+strw.toString()+"'");
XMLStreamReader sr = constructNsStreamReader(strw.toString());
assertTokenType(START_DOCUMENT, sr.getEventType(), sr);
// root element
assertTokenType(START_ELEMENT, sr.next(), sr);
assertEquals("test", sr.getLocalName());
// ??? is writer obligated to honor the prefix suggestion
assertEquals(URL_P1, sr.getNamespaceURI());
/* note: can not really verify number of namespace bindings, since
* writer should be in charge... and it may output extra bindings,
* too (and use default ns or explicit ones etc)
*/
// first branch:
assertTokenType(START_ELEMENT, sr.next(), sr);
assertEquals("branch", sr.getLocalName());
assertEquals(URL_P2, sr.getNamespaceURI());
// first leaf
assertTokenType(START_ELEMENT, sr.next(), sr);
assertEquals("leaf", sr.getLocalName());
assertEquals(URL_DEF, sr.getNamespaceURI());
assertTokenType(CHARACTERS, sr.next(), sr);
assertEquals(TEXT, getAllText(sr));
// not: getAllText ^^^ moves cursor!
assertTokenType(END_ELEMENT, sr.getEventType(), sr);
assertEquals("leaf", sr.getLocalName());
assertEquals(URL_DEF, sr.getNamespaceURI());
// another leaf:
assertTokenType(START_ELEMENT, sr.next(), sr);
assertEquals("leaf", sr.getLocalName());
assertEquals(URL_P1, sr.getNamespaceURI());
assertTokenType(END_ELEMENT, sr.next(), sr);
assertEquals("leaf", sr.getLocalName());
assertEquals(URL_P1, sr.getNamespaceURI());
// "third"
assertTokenType(START_ELEMENT, sr.next(), sr);
assertEquals("third", sr.getLocalName());
assertNoNsURI(sr);
assertTokenType(END_ELEMENT, sr.next(), sr);
assertEquals("third", sr.getLocalName());
assertNoNsURI(sr);
// (close) branch
assertTokenType(END_ELEMENT, sr.next(), sr);
assertEquals("branch", sr.getLocalName());
assertEquals(URL_P2, sr.getNamespaceURI());
// closing root element
assertTokenType(END_ELEMENT, sr.next(), sr);
assertEquals("test", sr.getLocalName());
assertEquals(URL_P1, sr.getNamespaceURI());
assertTokenType(END_DOCUMENT, sr.next(), sr);
}
public void testAttributeSimple()
throws IOException, XMLStreamException
{
StringWriter strw = new StringWriter();
XMLStreamWriter w = getRepairingWriter(strw);
final String URL_P1 = "http://p1.org";
final String ATTR_VALUE = "'value'&\"another\"";
w.writeStartDocument();
w.writeStartElement("", "test");
w.writeAttribute(URL_P1, "attr", ATTR_VALUE);
w.writeEndElement();
w.writeEndDocument();
w.close();
//System.err.println("testAttributeSimple: doc = '"+strw+"'");
// And then let's parse and verify it all:
XMLStreamReader sr = constructNsStreamReader(strw.toString());
assertTokenType(START_DOCUMENT, sr.getEventType(), sr);
// root element
assertTokenType(START_ELEMENT, sr.next(), sr);
assertEquals("test", sr.getLocalName());
assertNoNsURI(sr);
assertEquals(1, sr.getAttributeCount());
assertEquals("attr", sr.getAttributeLocalName(0));
assertEquals(URL_P1, sr.getAttributeNamespace(0));
assertEquals(ATTR_VALUE, sr.getAttributeValue(0));
assertTokenType(END_ELEMENT, sr.next(), sr);
assertEquals("test", sr.getLocalName());
assertNoNsURI(sr);
assertTokenType(END_DOCUMENT, sr.next(), sr);
}
public void testAttributes()
throws IOException, XMLStreamException
{
StringWriter strw = new StringWriter();
XMLStreamWriter w = getRepairingWriter(strw);
final String URL_P1 = "http://p1.org";
final String URL_DEF = "urn:default";
final String ATTR_VALUE = "'value\"";
final String ATTR_VALUE2 = "";
w.writeStartDocument();
/* Calling this method should be optional; but if we call it,
* exceptation is that it does properly bind the prefix and URL
* as the 'preferred' combination. In this case we'll just try
* to make URL bound as the default namespace
*/
w.setDefaultNamespace(URL_DEF);
w.writeStartElement(URL_DEF, "test");
/* And let's further make element and attribute(s) belong to that
* same namespace
*/
w.writeStartElement("", "leaf", URL_DEF);
w.writeAttribute(URL_DEF, "attr", ATTR_VALUE);
w.writeEndElement();
w.writeEmptyElement("", "leaf"); // in empty/no namespace!
w.writeStartElement(URL_DEF, "leaf");
w.writeAttribute("", "attr2", ATTR_VALUE2); // in empty/no namespace
w.writeEndElement();
w.writeEndElement(); // root elem
w.writeEndDocument();
w.close();
// And then let's parse and verify it all:
//System.err.println("testAttributes: doc = '"+strw+"'");
XMLStreamReader sr = constructNsStreamReader(strw.toString());
assertTokenType(START_DOCUMENT, sr.getEventType(), sr);
// root element
assertTokenType(START_ELEMENT, sr.next(), sr);
assertEquals("test", sr.getLocalName());
assertEquals(URL_DEF, sr.getNamespaceURI());
// first leaf:
assertTokenType(START_ELEMENT, sr.next(), sr);
assertEquals("leaf", sr.getLocalName());
assertEquals(URL_DEF, sr.getNamespaceURI());
assertEquals(1, sr.getAttributeCount());
assertEquals("attr", sr.getAttributeLocalName(0));
String uri = sr.getAttributeNamespace(0);
if (!URL_DEF.equals(uri)) {
fail("Expected attribute 'attr' to have NS '"+URL_DEF+"', was "+valueDesc(uri)+"; input = '"+strw+"'");
}
assertEquals(ATTR_VALUE, sr.getAttributeValue(0));
assertTokenType(END_ELEMENT, sr.next(), sr);
assertEquals("leaf", sr.getLocalName());
assertEquals(URL_DEF, sr.getNamespaceURI());
// empty leaf
assertTokenType(START_ELEMENT, sr.next(), sr);
assertEquals("leaf", sr.getLocalName());
assertNull("Element should not be in a namespace", sr.getNamespaceURI());
assertTokenType(END_ELEMENT, sr.next(), sr);
assertEquals("leaf", sr.getLocalName());
assertNull(sr.getNamespaceURI());
// third leaf
assertTokenType(START_ELEMENT, sr.next(), sr);
assertEquals("leaf", sr.getLocalName());
assertEquals(URL_DEF, sr.getNamespaceURI());
assertEquals(1, sr.getAttributeCount());
assertEquals("attr2", sr.getAttributeLocalName(0));
String nsURI = sr.getAttributeNamespace(0);
if (nsURI != null) {
fail("Attribute 'attr2' should not belong to a namespace; reported to belong to '"+nsURI+"'");
}
assertEquals(ATTR_VALUE2, sr.getAttributeValue(0));
assertTokenType(END_ELEMENT, sr.next(), sr);
assertEquals("leaf", sr.getLocalName());
assertEquals(URL_DEF, sr.getNamespaceURI());
// closing root element
assertTokenType(END_ELEMENT, sr.next(), sr);
assertEquals("test", sr.getLocalName());
assertEquals(URL_DEF, sr.getNamespaceURI());
assertTokenType(END_DOCUMENT, sr.next(), sr);
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/wstream/TestOutputEncoding.java 0000644 0001750 0001750 00000007142 10444554662 026647 0 ustar twerner twerner package org.codehaus.stax.test.wstream;
import javax.xml.stream.*;
import java.io.*;
/**
* Set of unit tests for verifying operation of {@link XMLStreamWriter}
* when outputting text nodes that contain characters that should
* be quoted.
*
* @author Tatu Saloranta
*/
public class TestOutputEncoding
extends BaseWriterTest
{
final String ISO_LATIN_ENCODING = "ISO-8859-1";
final String UTF8_ENCODING = "UTF-8";
public void testSimpleContentQuoting()
throws IOException, XMLStreamException
{
String TEXT = "&";
doTestSimpleQuoting(ISO_LATIN_ENCODING, TEXT);
doTestSimpleQuoting(UTF8_ENCODING, TEXT);
TEXT = "Need to quote this too: ]]>";
doTestSimpleQuoting(ISO_LATIN_ENCODING, TEXT);
doTestSimpleQuoting(UTF8_ENCODING, TEXT);
TEXT = "And nbsp: \u00A0.";
doTestSimpleQuoting(ISO_LATIN_ENCODING, TEXT);
doTestSimpleQuoting(UTF8_ENCODING, TEXT);
}
public void testSimpleAttrQuoting()
throws IOException, XMLStreamException
{
String TEXT = "&";
doTestSimpleAttr(ISO_LATIN_ENCODING, TEXT);
doTestSimpleAttr(UTF8_ENCODING, TEXT);
// Plus, need to quote single/double quotes properly
TEXT = "'\"fab\"'";
doTestSimpleAttr(ISO_LATIN_ENCODING, TEXT);
doTestSimpleAttr(UTF8_ENCODING, TEXT);
// And let's test non-ascii char too:
TEXT = "Nbsp -> \u00A0.";
doTestSimpleAttr(ISO_LATIN_ENCODING, TEXT);
doTestSimpleAttr(UTF8_ENCODING, TEXT);
}
/*
/////////////////////////////////////////////////////
// Helper methods
/////////////////////////////////////////////////////
*/
private void doTestSimpleQuoting(String encoding, String content)
throws IOException, XMLStreamException
{
StringWriter strw = new StringWriter();
XMLStreamWriter w = getNonRepairingWriter(strw);
w.writeStartDocument(encoding, "1.0");
w.writeStartElement("root");
w.writeCharacters(content);
w.writeEndElement();
w.writeEndDocument();
w.close();
// And then let's parse and verify it all:
XMLStreamReader sr = constructNsStreamReader(strw.toString(), true);
assertTokenType(START_DOCUMENT, sr.getEventType());
assertEquals(encoding, sr.getCharacterEncodingScheme());
assertTokenType(START_ELEMENT, sr.next());
// May get multiple segments..
assertTokenType(CHARACTERS, sr.next());
assertEquals(content, getAllText(sr));
assertTokenType(END_ELEMENT, sr.getEventType());
assertTokenType(END_DOCUMENT, sr.next());
}
private void doTestSimpleAttr(String encoding, String attrValue)
throws IOException, XMLStreamException
{
StringWriter strw = new StringWriter();
XMLStreamWriter w = getNonRepairingWriter(strw);
w.writeStartDocument(encoding, "1.0");
w.writeStartElement("root");
w.writeAttribute("attr", attrValue);
w.writeEndElement();
w.writeEndDocument();
w.close();
// And then let's parse and verify it all:
XMLStreamReader sr = constructNsStreamReader(strw.toString(), true);
assertTokenType(START_DOCUMENT, sr.getEventType());
assertEquals(encoding, sr.getCharacterEncodingScheme());
assertTokenType(START_ELEMENT, sr.next());
assertEquals(1, sr.getAttributeCount());
assertEquals(attrValue, sr.getAttributeValue(0));
assertTokenType(END_ELEMENT, sr.next());
assertTokenType(END_DOCUMENT, sr.next());
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/SimpleResolver.java 0000644 0001750 0001750 00000001533 10444554662 024327 0 ustar twerner twerner package org.codehaus.stax.test;
import javax.xml.stream.XMLResolver;
/**
* This is a simple and stupid resolver, that does not check what is
* being resolved; and thus it should only be used if only one thing
* (a single external entity; a single external subset) is to
* be expanded (although that single entity can be repeated multiple
* times).
*/
public class SimpleResolver
implements XMLResolver
{
final String ENC = "UTF-8";
final byte[] mData;
public SimpleResolver(String content)
{
try {
mData = content.getBytes(ENC);
} catch (java.io.IOException ioe) {
throw new Error(ioe.toString());
}
}
public Object resolveEntity(String publicID, String systemID, String baseURI, String namespace)
{
return new java.io.ByteArrayInputStream(mData);
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/stream/ 0000755 0001750 0001750 00000000000 10444554662 022002 5 ustar twerner twerner stax-1.2.0.orig/src/org/codehaus/stax/test/stream/TestStreaming.java 0000644 0001750 0001750 00000005063 10444554662 025442 0 ustar twerner twerner package org.codehaus.stax.test.stream;
import java.io.*;
import javax.xml.stream.*;
/**
* Unit test suite that tests that the stream is really fully streaming:
* that is, it doesn't need to fill buffers completely before being
* able to return events for things for which it has already read
* text. Tests were added after reports that some implementations did
* in fact have problems with such buffering, and as a result using
* such readers on network (http, tcp) streams wasn't working as well
* as it should.
*
* Note: should we test Ascii or ISO-Latin, or only UTF-8 (since that's
* the only encoding XML parsers HAVE to understand)? Most parsers handle
* them all. Also; is sub-optimal behaviour (blocking too early) really
* a bug, or just sub-standard implementation?
*/
public class TestStreaming
extends BaseStreamTest
{
public TestStreaming(String name) {
super(name);
}
public void testAscii()
throws XMLStreamException, UnsupportedEncodingException
{
testWith("US-ASCII");
}
public void testISOLatin()
throws XMLStreamException, UnsupportedEncodingException
{
testWith("ISO-8859-1");
}
public void testUTF8()
throws XMLStreamException, UnsupportedEncodingException
{
testWith("UTF-8");
}
/*
////////////////////////////////////////
// Private methods, tests
////////////////////////////////////////
*/
private void testWith(String enc)
throws XMLStreamException, UnsupportedEncodingException
{
BlockingStream bs = getStream(enc);
XMLStreamReader sr = getReader(bs);
assertTokenType(START_ELEMENT, sr.next());
if (bs.hasBlocked()) {
fail("Stream reader causes blocking before returning START_ELEMENT event that should be parsed before blocking");
}
}
/*
////////////////////////////////////////
// Private methods, other
////////////////////////////////////////
*/
private BlockingStream getStream(String enc)
throws XMLStreamException, UnsupportedEncodingException
{
String contents = "Some test";
byte[] data = contents.getBytes(enc);
return new BlockingStream(new ByteArrayInputStream(data));
}
private XMLStreamReader getReader(BlockingStream in)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setValidating(f, false);
return f.createXMLStreamReader((InputStream) in);
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/stream/TestNamespaces.java 0000644 0001750 0001750 00000056207 10444554662 025576 0 ustar twerner twerner package org.codehaus.stax.test.stream;
import java.util.Iterator;
import javax.xml.XMLConstants;
import javax.xml.namespace.*;
import javax.xml.stream.*;
/**
* Unit test suite that tests handling of the namespace declarations,
* both in namespace aware and non-namespace modes.
*/
public class TestNamespaces
extends BaseStreamTest
{
final String VALID_NS_XML
= ""
+""
+""
+""
+"";
public TestNamespaces(String name) {
super(name);
}
public void testValidNs()
throws XMLStreamException
{
XMLStreamReader sr = getNsReader(VALID_NS_XML, true);
assertEquals(START_ELEMENT, sr.next());
assertEquals(1, sr.getNamespaceCount());
assertEquals(2, sr.getAttributeCount());
// element properties:
assertNull(sr.getPrefix());
assertEquals("root", sr.getLocalName());
String uri = sr.getNamespaceURI();
if (uri != null) {
fail("Undeclared (default) namespace should have null URI; had \""+uri+"\" (len "+uri.length()+")");
}
// ns/attr properties:
assertEquals("value", sr.getAttributeValue(null, "attr1"));
assertEquals("", sr.getAttributeValue("myurl", "attr1"));
try {
String str = sr.getAttributeValue(-1);
fail("Expected an exception when trying to access attribute #-1.");
} catch (Exception e) { }
try {
String str = sr.getAttributeValue(2);
fail("Expected an exception when trying to access attribute #2 (only 2 attibutes, #0 and #1.");
} catch (Exception e) { }
// Shouldn't be able to use prefix, just URI:
assertNull(sr.getAttributeValue("xmlns", "a"));
assertEquals("myurl", sr.getNamespaceURI("a"));
assertNull(sr.getNamespaceURI("myurl"));
assertNull(sr.getNamespaceURI(""));
assertNull(sr.getNamespaceURI("nosuchurl"));
NamespaceContext nc = sr.getNamespaceContext();
assertNotNull(nc);
assertEquals(XMLConstants.XML_NS_URI, nc.getNamespaceURI(XMLConstants.XML_NS_PREFIX));
assertEquals(XMLConstants.XML_NS_PREFIX, nc.getPrefix(XMLConstants.XML_NS_URI));
assertEquals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, nc.getNamespaceURI(XMLConstants.XMLNS_ATTRIBUTE));
assertEquals(XMLConstants.XMLNS_ATTRIBUTE, nc.getPrefix(XMLConstants.XMLNS_ATTRIBUTE_NS_URI));
assertEquals("myurl", nc.getNamespaceURI("a"));
assertEquals("a", nc.getPrefix("myurl"));
Iterator it = nc.getPrefixes("foobar");
// Hmmmh. Can it be null or not? For now let's allow null too
if (it == null) {
;
} else {
assertFalse(it.hasNext());
}
it = nc.getPrefixes("myurl");
assertNotNull(it);
assertTrue(it.hasNext());
assertEquals("a", (String) it.next());
assertFalse(it.hasNext());
// // Ok, then the second element:
assertEquals(START_ELEMENT, sr.next());
assertEquals(2, sr.getNamespaceCount());
assertEquals(1, sr.getAttributeCount());
assertEquals("a", sr.getPrefix());
assertEquals("branch", sr.getLocalName());
assertEquals("whatever", sr.getNamespaceURI());
assertEquals("value", sr.getAttributeValue(null, "attr"));
assertEquals("value", sr.getAttributeValue(0));
assertEquals("someurl", sr.getNamespaceURI(""));
// // And finally the third
assertEquals(START_ELEMENT, sr.next());
assertEquals(0, sr.getNamespaceCount());
assertEquals(2, sr.getAttributeCount());
assertNull(sr.getPrefix());
assertEquals("leaf", sr.getLocalName());
assertEquals("yyy", sr.getAttributeValue("whatever", "a"));
assertEquals("xxx", sr.getAttributeValue(null, "a"));
assertEquals(END_ELEMENT, sr.next());
assertEquals(0, sr.getNamespaceCount());
assertNull(sr.getPrefix());
assertEquals("leaf", sr.getLocalName());
assertEquals(END_ELEMENT, sr.next());
assertEquals(2, sr.getNamespaceCount());
assertEquals("a", sr.getPrefix());
assertEquals("branch", sr.getLocalName());
assertEquals(END_ELEMENT, sr.next());
assertEquals(1, sr.getNamespaceCount());
assertNull(sr.getPrefix());
assertEquals("root", sr.getLocalName());
assertEquals(END_DOCUMENT, sr.next());
assertFalse(sr.hasNext());
}
final String VALID_NS_XML2
=""
+"text"
+"";
/**
* Another unit test that checks that valid namespace declarations
* are handled properly.
*/
public void testMultipleValidNs()
throws XMLStreamException
{
XMLStreamReader sr = getNsReader(VALID_NS_XML2, true);
assertEquals(START_ELEMENT, sr.next());
// Let's thoroughly check the root elem
assertEquals(2, sr.getNamespaceCount());
assertEquals(0, sr.getAttributeCount());
assertNull(sr.getPrefix());
assertEquals("root", sr.getLocalName());
assertEquals("http://foo", sr.getNamespaceURI());
assertEquals("myurl", sr.getNamespaceURI("a"));
// first empty elem
while (sr.next() == CHARACTERS) { }
assertTokenType(START_ELEMENT, sr.getEventType());
assertEquals(0, sr.getNamespaceCount());
assertEquals(1, sr.getAttributeCount());
assertNull(sr.getPrefix());
assertEquals("empty", sr.getLocalName());
assertEquals("http://foo", sr.getNamespaceURI());
assertEquals("myurl", sr.getNamespaceURI("a"));
assertNull(sr.getAttributeNamespace(0));
assertNull(sr.getAttributePrefix(0));
assertEquals("&", sr.getAttributeValue(0));
assertTokenType(END_ELEMENT, sr.next());
// second empty elem
assertTokenType(START_ELEMENT, sr.next());
assertEquals(0, sr.getNamespaceCount());
assertEquals(0, sr.getAttributeCount());
assertEquals("empty", sr.getLocalName());
assertEquals("a", sr.getPrefix());
assertEquals("myurl", sr.getNamespaceURI());
assertEquals("myurl", sr.getNamespaceURI("a"));
assertEquals("http://foo", sr.getNamespaceURI(""));
assertTokenType(END_ELEMENT, sr.next());
// And closing 'root'
assertTokenType(END_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
assertEquals("http://foo", sr.getNamespaceURI());
assertTokenType(END_DOCUMENT, sr.next());
}
/**
* Test proper handling of valid xml content in non-namespace aware mode.
* Since not all implementations (like the ref. impl.) support non-ns
* aware mode, this unit test is skipped if not applicable.
*/
public void testValidNonNs()
throws XMLStreamException
{
XMLStreamReader sr = getNsReader(VALID_NS_XML, false);
if (sr == null) {
reportNADueToNS("testValidNonNs");
return;
}
assertEquals(START_ELEMENT, sr.next());
assertEquals(0, sr.getNamespaceCount());
assertEquals(3, sr.getAttributeCount());
// element properties:
assertNull(sr.getPrefix());
assertEquals("root", sr.getLocalName());
// Hmmmh. Should we expect null here or not?
assertEquals(null, sr.getNamespaceURI());
// ns/attr properties:
assertEquals("value", sr.getAttributeValue(null, "attr1"));
assertEquals(null, sr.getAttributeValue(null, "foobar"));
try {
String str = sr.getAttributeValue(-1);
fail("Expected an exception when trying to access attribute #-1.");
} catch (Exception e) { }
try {
String str = sr.getAttributeValue(3);
fail("Expected an exception when trying to access attribute #3 (only 3 attibutes, #0 and #1.");
} catch (Exception e) { }
/* ... not sure if how namespace access should work, ie. is it ok
* to throw an exception, return null or what
*/
// // Ok, then the second element:
assertEquals(START_ELEMENT, sr.next());
assertEquals(0, sr.getNamespaceCount());
assertEquals(3, sr.getAttributeCount());
assertNull(sr.getPrefix());
assertEquals("a:branch", sr.getLocalName());
// // And finally the third
assertEquals(START_ELEMENT, sr.next());
assertEquals(0, sr.getNamespaceCount());
assertEquals(2, sr.getAttributeCount());
assertNull(sr.getPrefix());
assertEquals("leaf", sr.getLocalName());
assertEquals("xxx", sr.getAttributeValue(null, "a"));
assertEquals("yyy", sr.getAttributeValue(null, "a:a"));
// // And then the end elements
assertEquals(END_ELEMENT, sr.next());
assertEquals(0, sr.getNamespaceCount());
assertNull(sr.getPrefix());
assertEquals("leaf", sr.getLocalName());
assertEquals(END_ELEMENT, sr.next());
assertEquals(0, sr.getNamespaceCount());
assertNull(sr.getPrefix());
assertEquals("a:branch", sr.getLocalName());
assertEquals(END_ELEMENT, sr.next());
assertEquals(0, sr.getNamespaceCount());
assertNull(sr.getPrefix());
assertEquals("root", sr.getLocalName());
assertEquals(END_DOCUMENT, sr.next());
assertFalse(sr.hasNext());
}
public void testInvalidNs()
throws XMLStreamException
{
testPotentiallyInvalid(true, "testInvalidNs");
}
public void testInvalidNonNs()
throws XMLStreamException
{
// Some things are ok, some not, when namespace support is not enabled:
testPotentiallyInvalid(false, "testInvalidNonNs");
}
public void testInvalidStandardBindings()
throws XMLStreamException
{
doTestXmlBinding(true, "testInvalidStandardBindings");
doTestXmlnsBinding(true, "testInvalidStandardBindings");
}
public void testInvalidStandardBindingsNonNs()
throws XMLStreamException
{
doTestXmlBinding(false, "testInvalidStandardBindingsNonNs");
doTestXmlnsBinding(false, "testInvalidStandardBindingsNonNs");
}
public void testDefaultNs()
throws XMLStreamException
{
String XML = "";
XMLStreamReader sr = getNsReader(XML, true);
assertEquals(START_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
assertNull(sr.getPrefix());
assertEquals("url", sr.getNamespaceURI());
NamespaceContext ctxt = sr.getNamespaceContext();
assertEquals(1, sr.getNamespaceCount());
assertEquals("url", sr.getNamespaceURI(0));
assertNull(sr.getNamespacePrefix(0));
assertEquals("url", ctxt.getNamespaceURI(""));
assertEquals("", ctxt.getPrefix("url"));
assertNull(ctxt.getNamespaceURI("b"));
assertNull(ctxt.getPrefix("ns:b"));
XML = "";
sr = getNsReader(XML, true);
assertEquals(START_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
assertNull(sr.getPrefix());
assertNull(sr.getNamespaceURI());
assertEquals(1, sr.getNamespaceCount());
assertEquals("url", sr.getNamespaceURI(0));
assertEquals("a", sr.getNamespacePrefix(0));
}
/**
* Test case that verifies that namespaces properly nest, and
* inner definitions (ns in child element) can mask outer
* definitions (ns in parent element)
*/
public void testMaskingNs()
throws XMLStreamException
{
final String XML =
"";
XMLStreamReader sr = getNsReader(XML, true);
assertEquals(START_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
assertEquals("a", sr.getPrefix());
assertEquals("ns:a", sr.getNamespaceURI());
NamespaceContext ctxt = sr.getNamespaceContext();
assertEquals("ns:a", ctxt.getNamespaceURI("a"));
assertNull(ctxt.getNamespaceURI("b"));
assertEquals("a", ctxt.getPrefix("ns:a"));
assertNull(ctxt.getPrefix("ns:b"));
assertEquals(START_ELEMENT, sr.next());
assertEquals("child", sr.getLocalName());
assertEquals("a", sr.getPrefix());
assertEquals("ns:b", sr.getNamespaceURI());
ctxt = sr.getNamespaceContext();
assertEquals("ns:b", ctxt.getNamespaceURI("a"));
assertEquals("a", ctxt.getPrefix("ns:b"));
assertNull(ctxt.getNamespaceURI("b"));
// This is testing of actual masking, using NamespaceContext
{
// Previous binding should be masked by now!
String prefix = ctxt.getPrefix("ns:a");
if (prefix != null) {
fail("Failed: second declaration for prefix 'a' should have masked previous one; and there should not be a prefix for 'ns:a'. Instead, prefix '"+prefix+"' was considered to (still) be bound");
}
}
}
/**
* Unit test that verifies that the default namespace masking works
* as expected.
*/
public void testMaskingDefaultNs()
throws XMLStreamException
{
final String XML =
""
+""
+""
;
XMLStreamReader sr = getNsReader(XML, true);
assertEquals(START_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
assertNoPrefix(sr);
assertEquals("someurl", sr.getNamespaceURI());
assertEquals(1, sr.getNamespaceCount());
assertEquals(START_ELEMENT, sr.next());
assertEquals("branch", sr.getLocalName());
assertNoPrefix(sr);
assertNoNsURI(sr);
assertEquals(1, sr.getNamespaceCount());
assertEquals(START_ELEMENT, sr.next());
assertEquals("leaf", sr.getLocalName());
assertNoPrefix(sr);
assertNoNsURI(sr);
assertEquals(0, sr.getNamespaceCount());
assertEquals(END_ELEMENT, sr.next()); // leaf
assertEquals(0, sr.getNamespaceCount());
assertEquals(START_ELEMENT, sr.next());
assertEquals("leaf", sr.getLocalName());
assertNoPrefix(sr);
assertEquals("anotherurl", sr.getNamespaceURI());
assertEquals(1, sr.getNamespaceCount());
assertEquals(END_ELEMENT, sr.next()); // leaf
assertEquals(1, sr.getNamespaceCount());
assertEquals(END_ELEMENT, sr.next()); // branch
assertEquals(1, sr.getNamespaceCount());
assertEquals(END_ELEMENT, sr.next()); // root
assertEquals(1, sr.getNamespaceCount());
}
/**
* Unit test that verifies that the namespace with prefix 'xml' is
* always predefined without further work.
*/
public void testPredefinedXmlNs()
throws XMLStreamException
{
final String XML = "";
XMLStreamReader sr = getNsReader(XML, true);
assertEquals(START_ELEMENT, sr.next());
assertEquals("xml", sr.getAttributePrefix(0));
assertEquals("lang", sr.getAttributeLocalName(0));
assertEquals(XMLConstants.XML_NS_URI, sr.getAttributeNamespace(0));
assertEquals(START_ELEMENT, sr.next());
assertEquals("xml", sr.getPrefix());
assertEquals("a", sr.getLocalName());
assertEquals(XMLConstants.XML_NS_URI, sr.getNamespaceURI());
assertEquals(END_ELEMENT, sr.next());
assertEquals(END_ELEMENT, sr.next());
}
/*
////////////////////////////////////////
// Private methods, shared test code
////////////////////////////////////////
*/
private void testPotentiallyInvalid(boolean nsAware, String method)
throws XMLStreamException
{
// First, check that undeclared namespace prefixes are not kosher
try {
XMLStreamReader sr = getNsReader("", nsAware);
if (sr == null) {
reportNADueToNS(method);
return;
}
streamThrough(sr);
if (nsAware) {
fail("Was expecting an exception for content that uses undeclared namespace prefix.");
}
} catch (Exception e) {
if (!nsAware) {
fail("Was not expecting an exception for undeclared namespace when namespaces support not enabled: "+e);
}
}
// Plus, can't redeclare default namespace
try {
XMLStreamReader sr = getNsReader("",
nsAware);
streamThrough(sr);
fail("Was expecting an exception for content that has duplicate declaration of the default namespace.");
} catch (Exception e) {
; // both should get here
}
// Nor other prefixes
try {
XMLStreamReader sr = getNsReader("",
nsAware);
streamThrough(sr);
fail("Was expecting an exception for content that has duplicate declaration for a prefix.");
} catch (Exception e) {
; // both should get here
}
/* And then, two attribute names may be equivalent if prefixes
* point to same URI; but only in namespace-aware mode
*/
try {
XMLStreamReader sr = getNsReader
("",
nsAware);
streamThrough(sr);
if (nsAware) {
fail("Was expecting an exception for content that has duplicate attribute (even though prefixes differe, as they point to the same URI)");
}
} catch (Exception e) {
if (!nsAware) {
fail("Was NOT expecting an exception since in non-namespace mode attributes 'a:attr1' and 'b:attr1' are not equivalent: "+e);
}
}
}
private void doTestXmlBinding(boolean nsAware, String method)
throws XMLStreamException
{
// And 'xml' can only be bound to its correct URI
{ // this should be fine
XMLStreamReader sr = getNsReader("", nsAware);
if (sr == null) {
reportNADueToNS(method);
return;
}
streamThrough(sr);
}
// But not to anything else:
try {
XMLStreamReader sr = getNsReader("", nsAware);
streamThrough(sr);
if (nsAware) {
fail("Was expecting an exception for content that tries to redeclare 'xml' to different URI.");
}
} catch (Exception e) {
if (!nsAware) {
fail("Was not expecting an exception for redeclaration of 'xml' when namespace support not enabled: "+e);
}
}
// Also, nothing else can bind to that URI, neither explicit prefix
try {
XMLStreamReader sr = getNsReader("", nsAware);
streamThrough(sr);
if (nsAware) {
fail("Was expecting an exception for content that tries to bind prefix other than 'xml' to URI '"+XMLConstants.XML_NS_URI+"'");
}
} catch (Exception e) {
if (!nsAware) {
fail("Was not expecting an exception for binding 'xml' URI");
}
}
// Nor default namespace
try {
XMLStreamReader sr = getNsReader("", nsAware);
streamThrough(sr);
if (nsAware) {
fail("Was expecting an exception for content that tries to bind the default namespace to 'xml' URI '"+XMLConstants.XML_NS_URI+"'");
}
} catch (Exception e) {
if (!nsAware) {
fail("Was not expecting an exception for binding default namespace to 'xml' URI");
}
}
}
private void doTestXmlnsBinding(boolean nsAware, String method)
throws XMLStreamException
{
// Illegal to try to (re)declare 'xmlns' in any way
try {
XMLStreamReader sr = getNsReader("", nsAware);
if (sr == null) {
reportNADueToNS(method);
return;
}
streamThrough(sr);
if (nsAware) {
fail("Was expecting an exception for content that tries to redeclare 'xml' or 'xmlns' to different URI.");
}
} catch (Exception e) {
if (!nsAware) {
fail("Was not expecting an exception for redeclaration of 'xmlns' when namespace support not enabled: "+e);
}
}
// Also, nothing else can bind to that URI, neither explicit prefix
try {
XMLStreamReader sr = getNsReader("", nsAware);
streamThrough(sr);
if (nsAware) {
fail("Was expecting an exception for content that tries to bind prefix other than 'xml' to URI '"+XMLConstants.XMLNS_ATTRIBUTE_NS_URI+"'");
}
} catch (Exception e) {
if (!nsAware) {
fail("Was not expecting an exception for binding 'xml' URI");
}
}
// Nor default namespace
try {
XMLStreamReader sr = getNsReader("", nsAware);
streamThrough(sr);
if (nsAware) {
fail("Was expecting an exception for content that tries to bind the default namespace to 'xml' URI '"+XMLConstants.XMLNS_ATTRIBUTE_NS_URI+"'");
}
} catch (Exception e) {
if (!nsAware) {
fail("Was not expecting an exception for binding default namespace to 'xml' URI");
}
}
}
/*
////////////////////////////////////////
// Private methods, other
////////////////////////////////////////
*/
/**
* @return Stream reader constructed if initialization succeeded (all
* setting supported by the impl); null if some settings (namespace
* awareness) not supported.
*/
private XMLStreamReader getNsReader(String contents, boolean nsAware)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
if (!setNamespaceAware(f, nsAware)) {
return null;
}
setCoalescing(f, true);
setValidating(f, false);
return constructStreamReader(f, contents);
}
/*
////////////////////////////////////////////////////////////
// Local test driver, for quick access to individual cases...
////////////////////////////////////////////////////////////
*/
public static void main(String[] args)
throws Exception
{
new TestNamespaces("TestNamespaces").testValidNs();
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/stream/TestEpilog.java 0000644 0001750 0001750 00000006052 10444554662 024727 0 ustar twerner twerner package org.codehaus.stax.test.stream;
import javax.xml.stream.*;
/**
* Unit test suite that tests that events from prolog and epilog are
* correctly reported (and normalized if need be) by the stream reader.
*/
public class TestEpilog
extends BaseStreamTest
{
public TestEpilog(String name) {
super(name);
}
public void testValidEpilog()
throws XMLStreamException
{
String XML = " ";
XMLStreamReader sr = getReader(XML, true);
assertTokenType(COMMENT, sr.next());
assertEquals(" test comment ", getAndVerifyText(sr));
// May or may not get white space in epilog...
int type;
while ((type = sr.next()) == SPACE) {
;
}
assertTokenType(START_ELEMENT, type);
assertTokenType(END_ELEMENT, sr.next());
while ((type = sr.next()) == SPACE) {
;
}
assertTokenType(PROCESSING_INSTRUCTION, type);
assertEquals("some", sr.getPITarget());
// Not sure if the white space between target and data is included...
assertEquals("processing instruction", sr.getPIData().trim());
while ((type = sr.next()) == SPACE) {
;
}
assertTokenType(COMMENT, type);
assertEquals(" another comment! ", getAndVerifyText(sr));
while ((type = sr.next()) == SPACE) {
;
}
assertTokenType(END_DOCUMENT, type);
}
public void testInvalidEpilog()
throws XMLStreamException
{
/* Once again, ns/non-ns shouldn't matter... but you
* never know
*/
doTestInvalid(false);
doTestInvalid(true);
}
/*
////////////////////////////////////////
// Private methods, shared test code
////////////////////////////////////////
*/
private void doTestInvalid(boolean nsAware)
throws XMLStreamException
{
// Text before the root element:
String XML = " yeehaw! ";
try {
streamThrough(getReader(XML, nsAware));
fail("Expected an exception for text in prolog");
} catch (Exception e) {
; // good
}
// Text after the root element:
XML = " foobar";
try {
streamThrough(getReader(XML, nsAware));
fail("Expected an exception for text in epilog");
} catch (Exception e) {
; // good
}
}
/*
////////////////////////////////////////
// Private methods, other
////////////////////////////////////////
*/
private XMLStreamReader getReader(String contents, boolean nsAware)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
// Let's coalesce, makes it easier to skip white space
setCoalescing(f, true);
setNamespaceAware(f, nsAware);
setValidating(f, false);
return constructStreamReader(f, contents);
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/stream/TestElements.java 0000644 0001750 0001750 00000030723 10444554662 025266 0 ustar twerner twerner package org.codehaus.stax.test.stream;
import javax.xml.namespace.*;
import javax.xml.stream.*;
/**
* Unit test suite that tests handling of XML elements, both in namespace
* aware and non-namespace modes.
*/
public class TestElements
extends BaseStreamTest
{
public TestElements(String name) {
super(name);
}
/**
* Method that checks properties of START_ELEMENT and END_ELEMENT
* returned by the stream reader are correct according to StAX specs.
*/
public void testNsProperties()
throws XMLStreamException
{
testProperties(true, "testNsProperties");
}
public void testNonNsProperties()
throws XMLStreamException
{
testProperties(false, "testNonNsProperties");
}
/**
* Does test for simple element structure in namespace aware mode
*/
public void testValidNsElems()
throws XMLStreamException
{
testValid(true, "testValidNsElems");
}
public void testValidNonNsElems()
throws XMLStreamException
{
testValid(false, "testValidNonNsElems");
}
public void testInvalidNsElems()
throws XMLStreamException
{
testInvalid(true, "testInvalidNsElems");
}
public void testInvalidNonNsElems()
throws XMLStreamException
{
testInvalid(false, "testInvalidNonNsElems");
}
public void testEmptyDocument()
throws XMLStreamException
{
String EMPTY_XML = " ";
// Empty documents are not valid (missing root element)
streamThroughFailing(getElemReader(EMPTY_XML, true),
"empty document (not valid, missing root element)");
XMLStreamReader sr = getElemReader(EMPTY_XML, false);
if (sr != null) { // only if non-ns-aware mode supported
streamThroughFailing(sr,
"empty document (not valid, missing root element)");
}
}
public void testNoRootDocument()
throws XMLStreamException
{
String NOROOT_XML = "\n"
+" ";
// Documents without root are not valid
streamThroughFailing(getElemReader(NOROOT_XML, true),
"document without root element");
XMLStreamReader sr = getElemReader(NOROOT_XML, false);
if (sr != null) { // only if non-ns-aware mode supported
streamThroughFailing(sr, "document without root element");
}
}
public void testInvalidEmptyElem()
throws XMLStreamException
{
String XML = " ";
String MSG = "malformed empty element (space between '/' and '>')";
streamThroughFailing(getElemReader(XML, true), MSG);
XMLStreamReader sr = getElemReader(XML, false);
if (sr != null) { // only if non-ns-aware mode supported
streamThroughFailing(sr, MSG);
}
}
/*
////////////////////////////////////////
// Private methods, shared test code
////////////////////////////////////////
*/
private void testProperties(boolean nsAware, String method)
throws XMLStreamException
{
XMLStreamReader sr = getElemReader("", nsAware);
if (sr == null) {
reportNADueToNS(method);
return;
}
assertEquals(START_ELEMENT, sr.next());
testStartOrEnd(nsAware, sr, true);
assertEquals(END_ELEMENT, sr.next());
testStartOrEnd(nsAware, sr, false);
}
private void testStartOrEnd(boolean nsAware, XMLStreamReader sr,
boolean isStart)
throws XMLStreamException
{
int evtType = isStart ? START_ELEMENT : END_ELEMENT;
assertEquals(evtType, sr.getEventType());
String eventStr = tokenTypeDesc(evtType);
// simple type info
assertEquals(isStart, sr.isStartElement());
assertEquals(!isStart, sr.isEndElement());
assertEquals(false, sr.isCharacters());
assertEquals(false, sr.isWhiteSpace());
// indirect type info
assertEquals(true, sr.hasName());
assertEquals(false, sr.hasText());
assertNotNull(sr.getLocation());
QName n = sr.getName();
assertNotNull(n);
assertEquals("root", n.getLocalPart());
/* Hmmh. Seems like QName won't return null no matter what...
* so let's just check it's null or empty
*/
//assertEquals(null, n.getPrefix());
{
String prefix = n.getPrefix();
assertTrue((prefix == null) || prefix.length() == 0);
}
// Similarly, ns URI (from QName) apparently is never null...
//assertEquals((nsAware ? DEFAULT_URI_NS : DEFAULT_URI_NON_NS), n.getNamespaceURI());
{
String uri = n.getNamespaceURI();
assertTrue((uri == null) || uri.length() == 0);
}
if (isStart) {
assertEquals(0, sr.getAttributeCount());
} else {
try {
int count = sr.getAttributeCount();
fail("Expected an IllegalStateException when trying to call getAttributeCount() for "+eventStr);
} catch (IllegalStateException e) {
// good
}
}
assertEquals(0, sr.getNamespaceCount());
if (nsAware) {
/* but how about if namespaces are not supported? Can/should
* it return null?
*/
assertNotNull(sr.getNamespaceContext());
}
for (int i = 0; i < 4; ++i) {
String method = "";
try {
Object result = null;
switch (i) {
case 0:
method = "getText";
result = sr.getText();
break;
case 1:
method = "getTextCharacters";
result = sr.getTextCharacters();
break;
case 2:
method = "getPITarget";
result = sr.getPITarget();
break;
case 3:
method = "getPIData";
result = sr.getPIData();
break;
}
fail("Expected IllegalStateException, when calling "+method+"() for "+eventStr);
} catch (IllegalStateException iae) {
; // good
}
}
}
private void testValid(boolean nsAware, String method)
throws XMLStreamException
{
final String NS_URL1 = "http://www.stax.org";
final String NS_PREFIX1 = "prefix1";
final String NS_URL2 = "urn://mydummyid";
final String NS_PREFIX2 = "prefix2";
final String VALID_CONTENT
= "<"+NS_PREFIX1+":elem xmlns:"+NS_PREFIX1
+"='"+NS_URL1+"' "+NS_PREFIX1+":attr='value'>Text"
+""+NS_PREFIX1+":elem>"
+"";
/* First of all, let's check that it can be completely
* parsed:
*/
XMLStreamReader sr = getElemReader(VALID_CONTENT, nsAware);
if (sr == null) {
reportNADueToNS(method);
return;
}
streamThrough(sr);
// And then let's do it step by step
sr = getElemReader(VALID_CONTENT, nsAware);
// First, need to get
assertTokenType(START_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
String prefix = sr.getPrefix();
assertNull("Missing prefix should be reported as null", prefix);
String nsURI = sr.getNamespaceURI();
/* Hmmh. It's not defined by StAX API, whether null or "" is expected
* in non-ns mode... so let's accept either:
*/
if (nsAware) {
// In NS-mode, null is not allowed however
assertNull("Default (non-defined) namespace should be reported as empty String", nsURI);
} else {
assertNull("Default (non-defined) namespace should be reported as NULL in non-NS mode", nsURI);
}
// Let's also check QName seems valid:
QName name = sr.getName();
assertNotNull("Shouldn't get null QName for any start element", name);
assertEquals(name, new QName("root"));
// Hmmh. In ns-aware mode, is it ok to get null, ever?
assertNull(sr.getNamespaceURI());
assertEquals(0, sr.getAttributeCount());
assertEquals(0, sr.getNamespaceCount());
// And then
assertEquals(START_ELEMENT, sr.next());
if (nsAware) {
assertEquals("elem", sr.getLocalName());
assertEquals(NS_PREFIX1, sr.getPrefix());
assertEquals(NS_URL1, sr.getNamespaceURI());
} else {
assertEquals(NS_PREFIX1+":elem", sr.getLocalName());
assertEquals(null, sr.getPrefix());
assertNull(sr.getNamespaceURI());
}
int expNs = nsAware ? 1 : 0;
int expAttr = nsAware ? 1 : 2;
/* Let's just check counts, not values; attribute test can
* do thorough tests for values and access
*/
assertEquals(expAttr, sr.getAttributeCount());
assertEquals(expNs, sr.getNamespaceCount());
assertEquals(CHARACTERS, sr.next());
assertEquals("Text", getAndVerifyText(sr));
assertEquals(END_ELEMENT, sr.next());
if (nsAware) {
assertEquals("elem", sr.getLocalName());
assertEquals(NS_PREFIX1, sr.getPrefix());
assertEquals(NS_URL1, sr.getNamespaceURI());
} else {
assertEquals(NS_PREFIX1+":elem", sr.getLocalName());
assertNull(sr.getPrefix());
assertNull(sr.getNamespaceURI());
}
assertEquals(expNs, sr.getNamespaceCount());
assertEquals(START_ELEMENT, sr.next());
assertEquals("elem2", sr.getLocalName());
assertEquals(null, sr.getPrefix());
if (nsAware) {
assertEquals(NS_URL2, sr.getNamespaceURI());
} else {
assertNull(sr.getNamespaceURI());
}
assertEquals(expAttr, sr.getAttributeCount());
assertEquals(expNs, sr.getNamespaceCount());
assertEquals(END_ELEMENT, sr.next());
assertEquals("elem2", sr.getLocalName());
assertEquals(null, sr.getPrefix());
if (nsAware) {
assertEquals(NS_URL2, sr.getNamespaceURI());
} else {
assertNull(sr.getNamespaceURI());
}
assertEquals(expNs, sr.getNamespaceCount());
assertEquals(END_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
assertEquals(null, sr.getPrefix());
assertNull(sr.getNamespaceURI());
assertEquals(0, sr.getNamespaceCount());
}
/**
* Simple tests to check for incorrect nesting
*/
private void testInvalid(boolean nsAware, String method)
throws XMLStreamException
{
// Wrong end element:
String XML = " text ";
XMLStreamReader sr = getElemReader(XML, nsAware);
if (sr == null) {
reportNADueToNS(method);
return;
}
streamThroughFailing(sr, "incorrect nesting (wrong end element name)");
// For namespace mode, has to be same prefix (not just same URI)
if (nsAware) {
XML = " text ";
sr = getElemReader(XML, nsAware);
streamThroughFailing(sr, "incorrect nesting (namespace prefix in close element not the same as in start element)");
}
// Missing end element:
XML = " text ";
streamThroughFailing(getElemReader(XML, nsAware),
"incorrect nesting (missing end element)");
// More than one root:
XML = "";
streamThroughFailing(getElemReader(XML, nsAware),
"more than one root element");
}
/*
////////////////////////////////////////
// Private methods, other
////////////////////////////////////////
*/
private XMLStreamReader getElemReader(String contents, boolean nsAware)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
if (!setNamespaceAware(f, nsAware)) {
return null;
}
setCoalescing(f, true);
setValidating(f, false);
return constructStreamReader(f, contents);
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/stream/TestGetSegmentedText.java 0000644 0001750 0001750 00000023600 10444554662 026726 0 ustar twerner twerner package org.codehaus.stax.test.stream;
import java.io.*;
import java.util.Random;
import javax.xml.stream.*;
/**
* Unit test suite that ensures that the 'segmented' text accessors
* (multi-argument getTextCharacters) works as expected, with various
* combinations of access lengths, and orderings.
*
* @author Tatu Saloranta
*/
public class TestGetSegmentedText
extends BaseStreamTest
{
static String sXmlInput = null;
static String sExpResult = null;
public void testCoalescingAutoEntity()
throws Exception
{
doTest(false, true, true); // non-ns
doTest(true, true, true); // ns-aware
}
public void testNonCoalescingAutoEntity()
throws Exception
{
doTest(false, false, true); // non-ns
doTest(true, false, true); // ns-aware
}
public void testCoalescingNonAutoEntity()
throws Exception
{
doTest(false, true, false); // non-ns
doTest(true, true, false); // ns-aware
}
public void testNonCoalescingNonAutoEntity()
throws Exception
{
doTest(false, false, false); // non-ns
doTest(true, false, false); // ns-aware
}
public void testSegmentedGetCharacters()
throws XMLStreamException
{
final String TEXT = "Let's just add some content in here ('') to fill some of the parser buffers, to test multi-argument getTextCharacters() method";
final String XML = ""+TEXT+"";
XMLInputFactory f = getFactory(true, false, true);
XMLStreamReader sr = constructStreamReader(f, XML);
// May or may not get the prolog comment
int type = sr.next();
if (type == COMMENT) {
type = sr.next();
}
assertTokenType(START_ELEMENT, type);
assertTokenType(PROCESSING_INSTRUCTION, sr.next());
type = sr.next();
assertTokenType(CHARACTERS, type);
/* Ok... let's just access all the text, by one char reads, from
* possibly multiple events:
*/
StringBuffer sb = new StringBuffer();
while (type == CHARACTERS) {
char[] buf = new char[5];
int offset = 0;
int count;
while (true) { // let's use 2 different size of requests...
int start, len;
if ((offset & 1) == 0) {
start = 2;
len = 1;
} else {
start = 0;
len = buf.length;
}
count = sr.getTextCharacters(offset, buf, start, len);
if (count > 0) {
sb.append(buf, start, count);
offset += count;
}
if (count < len) {
break;
}
}
type = sr.next();
}
assertEquals(TEXT, sb.toString());
assertTokenType(END_ELEMENT, type);
}
/*
////////////////////////////////////////
// Private methods, common test code
////////////////////////////////////////
*/
private void doTest(boolean ns, boolean coalescing, boolean autoEntity)
throws Exception
{
// This is bit hacky, but speeds up testing...
if (sXmlInput == null) {
initData();
}
// And let's also check using different buffer sizes:
for (int sz = 0; sz < 3; ++sz) {
// Let's test different input methods too:
for (int j = 0; j < 3; ++j) {
XMLInputFactory f = getFactory(ns, coalescing, autoEntity);
XMLStreamReader sr;
switch (j) {
case 0: // simple StringReader:
sr = constructStreamReader(f, sXmlInput);
break;
case 1: // via InputStream and auto-detection
/* It shouldn't really contain anything outside ISO-Latin;
* however, detection may be tricky.. so let's just
* test with UTF-8, for now?
*/
{
ByteArrayInputStream bin = new ByteArrayInputStream
(sXmlInput.getBytes("UTF-8"));
sr = f.createXMLStreamReader(bin);
}
break;
case 2: // explicit UTF-8 stream
{
ByteArrayInputStream bin = new ByteArrayInputStream
(sXmlInput.getBytes("UTF-8"));
Reader br = new InputStreamReader(bin, "UTF-8");
sr = f.createXMLStreamReader(br);
}
break;
default: throw new Error("Internal error");
}
char[] cbuf;
if (sz == 0) {
cbuf = new char[23];
} else if (sz == 1) {
cbuf = new char[384];
} else {
cbuf = new char[4005];
}
assertEquals(START_ELEMENT, sr.next());
int segCount = 0;
int totalLen = sExpResult.length();
StringBuffer totalBuf = new StringBuffer(totalLen);
/* Ok; for each segment let's test separately first,
* and then combine all the results together as well
*/
while (sr.next() == CHARACTERS) {
// Where are we within the whole String?
int segOffset = totalBuf.length();
++segCount;
// Should not get multiple when coalescing...
if (coalescing && segCount > 1) {
fail("Didn't expect multiple CHARACTERS segments when coalescing: first segment contained "+segOffset+" chars from the whole expected "+totalLen+" chars");
}
StringBuffer sb = new StringBuffer();
int count;
int offset = 0;
int readCount = 0;
while ((count = sr.getTextCharacters(offset, cbuf, 0, cbuf.length)) > 0) {
++readCount;
sb.append(cbuf, 0, count);
offset += count;
}
int expLen = sr.getTextLength();
// Sanity check #1: should get matching totals
assertEquals
("Expected segment #"+segOffset+" (one-based; read with "+readCount+" reads) to have length of "
+expLen+"; reported to have gotten just "+offset+" chars",
expLen, offset);
// Sanity check #2: and string buf should have it too
assertEquals
("Expected segment #"+segOffset+" (one-based; read with "+readCount+" reads) to get "
+expLen+" chars; StringBuffer only has "+sb.length(),
expLen, sb.length());
totalBuf.append(sb);
}
assertTokenType(END_ELEMENT, sr.getEventType());
// Ok; all gotten, does it match?
assertEquals("Expected total of "+totalLen+" chars, got "+totalBuf.length(),
sExpResult.length(), totalBuf.length());
// Lengths are ok, but how about content?
if (!sExpResult.equals(totalBuf.toString())) {
// TODO: indicate where they differ?
String str1 = sExpResult;
String str2 = totalBuf.toString();
int len = str1.length();
int i = 0;
char c1 = 'x', c2 = 'x';
for (; i < len; ++i) {
c1 = str1.charAt(i);
c2 = str2.charAt(i);
if (c1 != c2) {
break;
}
}
fail("Expected Strings to equal; differed at character #"+i+" (length "+len+" was correct); expected '"+c1+"' ("+((int) c1)+"), got '"+c2+"' ("+((int) c2)+")");
sr.close();
}
}
}
}
/*
////////////////////////////////////////
// Private methods, other
////////////////////////////////////////
*/
private XMLInputFactory getFactory(boolean nsAware,
boolean coalescing, boolean autoEntity)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setNamespaceAware(f, nsAware);
setCoalescing(f, coalescing);
setReplaceEntities(f, autoEntity);
setSupportDTD(f, true);
setValidating(f, false);
return f;
}
private void initData()
throws XMLStreamException
{
StringBuffer sb = new StringBuffer("");
sb.append("");
/* Let's create a ~64kchar text segment for testing, first; and one
* including stuff like linefeeds and (pre-defined) entities.
*/
while (sb.length() < 65000) {
sb.append("abcd efgh\r\nijkl & mnop < > qrst\n uvwx\r yz A");
}
sb.append("");
final String XML = sb.toString();
/* But more than that, let's also see what we should get
* as a result...
*/
XMLInputFactory f = getFactory(true, false, true);
XMLStreamReader sr = constructStreamReader(f, XML);
assertTokenType(START_ELEMENT, sr.next());
StringBuffer sb2 = new StringBuffer(XML.length());
while (sr.next() == CHARACTERS) {
sb2.append(sr.getText());
}
sXmlInput = XML;
sExpResult = sb2.toString();
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/stream/TestCommentRead.java 0000644 0001750 0001750 00000020402 10444554662 025701 0 ustar twerner twerner package org.codehaus.stax.test.stream;
import javax.xml.stream.*;
/**
* Unit test suite that tests handling of XML comments (except for the
* linefeed normalization which is tested elsewhere); mostly just what
* properties is the stream reader returning when pointing to a comment.
*/
public class TestCommentRead
extends BaseStreamTest
{
public TestCommentRead(String name) {
super(name);
}
public void testValidComments()
throws XMLStreamException
{
String XML = " ";
streamThrough(getReader(XML, true, true));
streamThrough(getReader(XML, false, true));
XML = " ";
streamThrough(getReader(XML, true, true));
streamThrough(getReader(XML, false, true));
}
/**
* Method that checks properties of COMMENT
* returned by the stream reader are correct according to StAX specs.
*/
public void testCommentProperties()
throws XMLStreamException
{
/* Neither ns-awareness nor dtd-support should make any difference,
* but let's double check them...
*/
doTestProperties(true, true);
doTestProperties(true, false);
doTestProperties(false, true);
doTestProperties(false, false);
}
public void testInvalidComment()
throws XMLStreamException
{
String XML = " ";
String XML2 = "";
String XML3 = "";
for (int i = 0; i < 3; ++i) {
boolean ns = (i & 1) != 0;
boolean dtd = (i & 2) != 0;
streamThroughFailing(getReader(XML, ns, dtd),
"invalid comment content (embedded \"--\")");
streamThroughFailing(getReader(XML2, ns, dtd),
"malformed comment (extra space)");
streamThroughFailing(getReader(XML3, ns, dtd),
"malformed comment (extra space)");
}
}
public void testUnfinishedComment()
throws XMLStreamException
{
String XML = "";
XMLStreamReader sr = getReader(XML, true, true);
try {
// May get an exception when parsing entity declaration... ?
// (since it contains partial token)
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
int type = sr.next();
if (type != COMMENT) {
reportNADueToEntityExpansion("testRunawayComment", type);
return;
}
type = sr.next();
fail("Expected an exception for split/runaway comment (instead got event "+tokenTypeDesc(type)+")");
} catch (XMLStreamException sex) {
// good
} catch (RuntimeException rex) {
// some impls. throw lazy exceptions, too...
}
}
public void testLongComments()
throws XMLStreamException
{
final String COMMENT1 =
"Some longish comment to see if the input buffer size restrictions might apply here: the reference\nimplementation had problems beyond 256 characters\n"
+" so let's add at least that much, and preferably quite a bit more\n"
+"too... Blah blah yadda yadda: also, unquoted '&' and '<' are kosher here"
+"\nwithout any specific problems or issues."
+" Is this long enough now? :-)"
;
String XML = ""
+""
+""
+" \n"
+"]>"
;
XMLStreamReader sr = getReader(XML, true, true);
assertTokenType(COMMENT, sr.next());
assertEquals(COMMENT1, getAndVerifyText(sr));
assertTokenType(PROCESSING_INSTRUCTION, sr.next());
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
assertTokenType(COMMENT, sr.next());
assertEquals(COMMENT1, getAndVerifyText(sr));
assertTokenType(END_ELEMENT, sr.next());
}
/*
////////////////////////////////////////
// Private methods, shared test code
////////////////////////////////////////
*/
private void doTestProperties(boolean nsAware, boolean dtd)
throws XMLStreamException
{
XMLStreamReader sr = getReader("",
nsAware, dtd);
assertEquals(COMMENT, sr.next());
// Type info
assertEquals(false, sr.isStartElement());
assertEquals(false, sr.isEndElement());
assertEquals(false, sr.isCharacters());
assertEquals(false, sr.isWhiteSpace());
// indirect type info
assertEquals(false, sr.hasName());
assertEquals(true, sr.hasText());
assertNotNull(sr.getLocation());
if (nsAware) {
assertNotNull(sr.getNamespaceContext());
}
// And then let's check methods that should throw specific exception
for (int i = 0; i < 8; ++i) {
String method = "";
try {
Object result = null;
switch (i) {
case 0:
method = "getName";
result = sr.getName();
break;
case 1:
method = "getPrefix";
result = sr.getPrefix();
break;
case 2:
method = "getLocalName";
result = sr.getLocalName();
break;
case 3:
method = "getNamespaceURI";
result = sr.getNamespaceURI();
break;
case 4:
method = "getNamespaceCount";
result = new Integer(sr.getNamespaceCount());
break;
case 5:
method = "getAttributeCount";
result = new Integer(sr.getAttributeCount());
break;
case 6:
method = "getPITarget";
result = sr.getPITarget();
break;
case 7:
method = "getPIData";
result = sr.getPIData();
break;
}
fail("Expected IllegalStateException, when calling "
+method+"() for COMMENT");
} catch (IllegalStateException iae) {
; // good
}
}
String content = getAndVerifyText(sr);
assertEquals("comment & ", content);
}
/*
////////////////////////////////////////
// Private methods, other
////////////////////////////////////////
*/
private XMLStreamReader getReader(String contents, boolean nsAware,
boolean dtd)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setCoalescing(f, false); // shouldn't really matter
setNamespaceAware(f, nsAware);
setSupportDTD(f, dtd);
setValidating(f, false);
return constructStreamReader(f, contents);
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/stream/TestRandomStream.java 0000644 0001750 0001750 00000025632 10444554662 026111 0 ustar twerner twerner package org.codehaus.stax.test.stream;
import java.io.*;
import java.util.Random;
import javax.xml.stream.*;
/**
* Unit test suite that ensures that independent of combinations of settings
* such as namespace-awareness, coalescing, automatic entity replacement,
* parsing results remain the same when they should.
*/
public class TestRandomStream
extends BaseStreamTest
{
public TestRandomStream(String name) {
super(name);
}
public void testCoalescingAutoEntity()
throws Exception
{
doTest(false, true, true); // non-ns
doTest(true, true, true); // ns-aware
}
public void testNonCoalescingAutoEntity()
throws Exception
{
doTest(false, false, true); // non-ns
doTest(true, false, true); // ns-aware
}
public void testCoalescingNonAutoEntity()
throws Exception
{
doTest(false, true, false); // non-ns
doTest(true, true, false); // ns-aware
}
public void testNonCoalescingNonAutoEntity()
throws Exception
{
doTest(false, false, false); // non-ns
doTest(true, false, false); // ns-aware
}
/*
////////////////////////////////////////
// Private methods, common test code
////////////////////////////////////////
*/
private void doTest(boolean ns, boolean coalescing, boolean autoEntity)
throws Exception
{
//System.err.println("Ns: "+ns+", coal "+coalescing+" ent "+autoEntity);
// Let's generate seed from args so it's reproducible
long seed = 123457;
if (ns) {
seed ^= "ns".hashCode();
}
if (coalescing) {
seed ^= "coalescing".hashCode();
}
if (autoEntity) {
seed ^= "autoEntity".hashCode();
}
Random r = new Random(seed);
/* We can do multiple rounds, too, too get even wider coverage...
*/
final int ROUNDS = 5;
for (int i = 0; i < ROUNDS; ++i) {
StringBuffer inputBuf = new StringBuffer(1000);
StringBuffer expOutBuf = new StringBuffer(1000);
generateData(r, inputBuf, expOutBuf, autoEntity);
String input = inputBuf.toString();
String expOutput = expOutBuf.toString();
// Let's test different input methods too:
for (int j = 0; j < 3; ++j) {
XMLInputFactory f = getFactory(ns, coalescing, autoEntity);
XMLStreamReader sr;
switch (j) {
case 0: // simple StringReader:
sr = constructStreamReader(f, input);
break;
case 1: // via InputStream and auto-detection
/* It shouldn't really contain anything outside ISO-Latin;
* however, detection may be tricky.. so let's just
* test with UTF-8, for now?
*/
{
ByteArrayInputStream bin = new ByteArrayInputStream
(input.getBytes("UTF-8"));
sr = f.createXMLStreamReader(bin);
}
break;
case 2: // explicit UTF-8 stream
{
ByteArrayInputStream bin = new ByteArrayInputStream
(input.getBytes("UTF-8"));
Reader br = new InputStreamReader(bin, "UTF-8");
sr = f.createXMLStreamReader(br);
}
break;
default: throw new Error("Internal error");
}
String actual = null;
try {
actual = runTest(sr);
} catch (Exception e) {
// For debugging uncomment:
System.err.println("Error: "+e);
System.err.println("Ns: "+ns+", coalescing: "+coalescing+", auto-ent: "+autoEntity);
System.err.println("Input was '"+input+"'");
throw e;
}
// uncomment for debugging:
if (!expOutput.equals(actual)) {
System.err.println("Input: '"+input+"'");
System.err.println("Exp: '"+expOutput+"'");
System.err.println("Actual: '"+actual+"'");
}
assertEquals(expOutput, actual);
}
}
}
private String runTest(XMLStreamReader sr)
throws Exception
{
assertEquals(DTD, sr.next());
int type;
while ((type = sr.next()) == SPACE) {
;
}
assertEquals(START_ELEMENT, type);
StringBuffer act = new StringBuffer(1000);
do {
if (type == START_ELEMENT || type == END_ELEMENT) {
act.append('<');
if (type == END_ELEMENT) {
act.append('/');
}
String prefix = sr.getPrefix();
if (prefix != null && prefix.length() > 0) {
act.append(prefix);
act.append(':');
}
act.append(sr.getLocalName());
act.append('>');
} else if (type == CHARACTERS || type == SPACE || type == CDATA) {
// No quoting, doesn't have to result in legal XML
act.append(getAndVerifyText(sr));
} else if (type == COMMENT) {
act.append("");
} else if (type == ENTITY_REFERENCE) {
act.append(sr.getText());
} else {
fail("Unexpected event type "+type);
}
} while ((type = sr.next()) != END_DOCUMENT);
return act.toString();
}
private void generateData(Random r, StringBuffer input,
StringBuffer output, boolean autoEnt)
{
final String PREAMBLE =
""
+"\n"
+" \n"
+" \n"
+"]>";
/* Ok; template will use '*' chars as placeholders, to be replaced
* by pseudo-randomly selected choices.
*/
final String TEMPLATE =
""
// Short one for trouble shooting:
/*
+" * Text ****\n"
*/
// Real one for regression testing:
+" * Text ****\n"
+"** * xx\n"
+"Text ******\n"
+"*......**"
+"******"
+"***"
+"***"
+"a*b*c*d*e*f*g*h*i*j*k"
+""
;
input.append(TEMPLATE);
output.append(TEMPLATE);
for (int i = TEMPLATE.length(); --i >= 0; ) {
char c = TEMPLATE.charAt(i);
if (c == '*') {
replaceEntity(input, output, autoEnt, r, i);
}
}
// Let's also insert preamble into input now
input.insert(0, PREAMBLE);
}
private void replaceEntity(StringBuffer input, StringBuffer output,
boolean autoEnt,
Random r, int index)
{
String in, out;
switch (Math.abs(r.nextInt()) % 5) {
case 0: // Let's use one of pre-def'd entities:
switch (Math.abs(r.nextInt()) % 5) {
case 0:
in = "&";
out = "&";
break;
case 1:
in = "'";
out = "'";
break;
case 2:
in = "<";
out = "<";
break;
case 3:
in = ">";
out = ">";
break;
case 4:
in = """;
out = "\"";
break;
default: throw new Error("Internal error!");
}
break;
case 1: // How about some CDATA?
switch (Math.abs(r.nextInt()) % 4) {
case 0:
in = "]]>";
out = "]] >";
break;
case 1:
in = "";
out = "xyz&abc";
break;
case 2:
in = "";
out = "";
break;
case 3:
in = "";
out = " ";
break;
default: throw new Error("Internal error!");
}
break;
case 2: // Char entities?
switch (Math.abs(r.nextInt()) % 4) {
case 0:
in = "#";
out = "#";
break;
case 1:
in = "$";
out = "$";
break;
case 2:
in = "©"; // above US-Ascii, copyright symbol
out = "\u00A9";
break;
case 3:
in = "Ä"; // Upper-case a with umlauts
out = "\u00C4";
break;
default: throw new Error("Internal error!");
}
break;
case 3: // Full entities
switch (Math.abs(r.nextInt()) % 3) {
case 0:
in = "&ent1;";
out = "ent1Value";
break;
case 1:
in = "&x;";
out = "Y";
break;
case 2:
in = "&both;";
out = autoEnt ? "ent1ValueY" : "&ent1;&x;";
break;
default: throw new Error("Internal error!");
}
break;
case 4: // Plain text, ISO-Latin chars:
in = out = "(\u00A9)"; // copyright symbol
break;
default:
throw new Error("Internal error!");
}
input.replace(index, index+1, in);
output.replace(index, index+1, out);
}
/*
////////////////////////////////////////
// Private methods, other
////////////////////////////////////////
*/
private XMLInputFactory getFactory(boolean nsAware,
boolean coalescing, boolean autoEntity)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setNamespaceAware(f, nsAware);
setCoalescing(f, coalescing);
setReplaceEntities(f, autoEntity);
setSupportDTD(f, true);
setValidating(f, false);
return f;
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/stream/TestTextCoalescing.java 0000644 0001750 0001750 00000012356 10444554662 026430 0 ustar twerner twerner package org.codehaus.stax.test.stream;
import javax.xml.stream.*;
/**
* Unit test suite that tests that the stream reader does in fact
* coalesce adjacent text/CDATA segments when told to do so.
*/
public class TestTextCoalescing
extends BaseStreamTest
{
final static String VALID_XML = "Text /that's all!";
public TestTextCoalescing(String name) {
super(name);
}
public void testCoalescing()
throws XMLStreamException
{
XMLStreamReader sr = getReader(VALID_XML, true, true);
assertTokenType(START_ELEMENT, sr.next());
assertTokenType(CHARACTERS, sr.next());
String act = getAndVerifyText(sr);
String exp = "Text cdata\nin two lines!/that's all!";
if (!exp.equals(act)) {
failStrings("Coalescing failed", exp, act);
}
assertTokenType(END_ELEMENT, sr.next());
assertTokenType(END_DOCUMENT, sr.next());
}
/**
* Test that ensures that even when just skipping (ie not accessing
* any data), we'll still see just one event for the whole text
*/
public void testCoalescingSkipping()
throws XMLStreamException
{
XMLStreamReader sr = getReader(VALID_XML, true, true);
assertTokenType(START_ELEMENT, sr.next());
assertTokenType(CHARACTERS, sr.next());
assertTokenType(END_ELEMENT, sr.next());
assertTokenType(END_DOCUMENT, sr.next());
}
public void testNonCoalescing()
throws XMLStreamException
{
// VALID_XML = "Text /that's all!";
XMLStreamReader sr = getReader(VALID_XML, true, false);
assertTokenType(START_ELEMENT, sr.next());
/* Can not assume that all events are returned in one call...
* so let's play it safe:
*/
sr.next();
checkText(sr, CHARACTERS, "Text ");
int count = checkText(sr, CDATA, "cdata\nin two lines!");
if (count < 2) {
// Can't easily check boundaries... well, could but...
fail("Expected at least two CDATA events; parser coalesced them");
}
checkText(sr, CHARACTERS, "/that's all!");
assertTokenType(END_ELEMENT, sr.getEventType());
assertTokenType(END_DOCUMENT, sr.next());
}
public void testNonCoalescingSkipping()
throws XMLStreamException
{
// VALID_XML = "Text /that's all!";
XMLStreamReader sr = getReader(VALID_XML, true, false);
assertTokenType(START_ELEMENT, sr.next());
assertTokenType(CHARACTERS, sr.next());
/* ugh. Since implementations are allowed to return CHARACTERS,
* instead of CDATA, we can only check that we get at least
* 4 segments of any type...
*/
// Now, we may get more than one CHARACTERS
int count = 1;
StringBuffer sb = new StringBuffer();
sb.append('[');
sb.append(sr.getText());
sb.append(']');
int type;
while (true) {
type = sr.next();
if (type != CHARACTERS && type != CDATA) {
break;
}
++count;
sb.append('[');
sb.append(sr.getText());
sb.append(']');
}
if (count < 4) {
fail("Expected at least 4 separate segments (CDATA/CHARACTERS), in non-coalescing mode, got "+count+" (text: "+sb+")");
}
assertTokenType(END_ELEMENT, type);
assertTokenType(END_DOCUMENT, sr.next());
}
public void testInvalidTextWithCDataEndMarker()
throws XMLStreamException
{
String XML = " ]]> ";
streamThroughFailing(getReader(XML, true, true),
"text content that has ']]>' in it.");
}
/*
////////////////////////////////////////
// Private methods, other
////////////////////////////////////////
*/
private XMLStreamReader getReader(String contents, boolean nsAware,
boolean coalescing)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setNamespaceAware(f, nsAware);
setSupportDTD(f, true);
setCoalescing(f, coalescing);
setReplaceEntities(f, true);
setValidating(f, false);
// 13-Mar-2006, TSa: Let's try to get accurate CDATA reporting...
setReportCData(f, true);
return constructStreamReader(f, contents);
}
private int checkText(XMLStreamReader sr, int expType, String exp)
throws XMLStreamException
{
assertTokenType(expType, sr.getEventType());
//if (expType != sr.getEventType()) System.err.println("WARN: expected "+tokenTypeDesc(expType)+", got "+tokenTypeDesc(sr.getEventType()));
StringBuffer sb = new StringBuffer(getAndVerifyText(sr));
int count = 1;
while ((sr.next()) == expType) {
++count;
sb.append(getAndVerifyText(sr));
}
String act = sb.toString();
if (!exp.equals(act)) {
failStrings("Incorrect text contents", act, exp);
}
return count;
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/stream/TestLinefeeds.java 0000644 0001750 0001750 00000024750 10444554662 025413 0 ustar twerner twerner package org.codehaus.stax.test.stream;
import javax.xml.stream.*;
/**
* Unit test suite that tests linefeed normalization features of parsers.
*/
public class TestLinefeeds
extends BaseStreamTest
{
final String IN_SPACES1 = " \r \n \r\n ";
final String OUT_SPACES1 = " \n \n \n ";
final String IN_SPACES2 = "\r\r \n \r";
final String OUT_SPACES2 = "\n\n \n \n";
final String IN_SPACES3 = " \r\n \r\n \r\n";
final String OUT_SPACES3 = " \n \n \n";
final String IN_MIXED1 = "Something\nwonderful (?)\rhas...\r\r\n happened ";
final String OUT_MIXED1 = "Something\nwonderful (?)\nhas...\n\n happened ";
public TestLinefeeds(String name) {
super(name);
}
/**
* Test that checks that if ignorable whitespace is reported from
* epilog and/or prolog, it will be properly normalized.
*/
public void testLfInEpilog()
throws XMLStreamException
{
final String contents = IN_SPACES1+""+IN_SPACES2;
for (int i = 0; i < 4; ++i) {
XMLInputFactory f = getInputFactory();
boolean coal = ((i & 1) == 0);
boolean ns = ((i & 2) == 0);
setCoalescing(f, coal);
setNamespaceAware(f, ns);
XMLStreamReader sr = constructStreamReader(f, contents);
/* Since reporting (ignorable) white space is optional, have to
* be careful...
*/
int type = sr.next();
if (type == SPACE) { // ok
String str = getAndVerifyText(sr);
while ((type = sr.next()) == SPACE) {
str += getAndVerifyText(sr);
}
assertEquals(printable(OUT_SPACES1), printable(str));
}
// Either way, needs to have the root element now
assertEquals(START_ELEMENT, type);
assertEquals("root", sr.getLocalName());
assertEquals(null, sr.getPrefix());
// And then matching virtual close
assertEquals(END_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
assertEquals(null, sr.getPrefix());
// And then we may get more whitespace:
type = sr.next();
if (type == SPACE) { // ok
String str = getAndVerifyText(sr);
while ((type = sr.next()) == SPACE) {
str += getAndVerifyText(sr);
}
if (!str.equals(OUT_SPACES2)) {
String exp = printable(OUT_SPACES2);
String act = printable(str);
fail("Failed (coalesce: "+coal+", ns-aware: "+ns+"); expected '"+exp+"', got '"+act+"'.");
}
}
assertEquals(END_DOCUMENT, type);
}
}
public void testLfInCData()
throws XMLStreamException
{
/* Split into separate calls, to make it easier to see which
* combination failed (from stack trace)
*/
doTestLfInCData(false, false);
doTestLfInCData(false, true);
doTestLfInCData(true, false);
doTestLfInCData(true, true);
}
private void doTestLfInCData(boolean ns, boolean coalescing)
throws XMLStreamException
{
final String contents = "";
XMLInputFactory f = getInputFactory();
setCoalescing(f, coalescing);
setNamespaceAware(f, ns);
XMLStreamReader sr = constructStreamReader(f, contents);
// Then should get the root element:
// Either way, needs to have the root element now
assertEquals(START_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
assertEquals(null, sr.getPrefix());
/* Then we will get either CDATA or CHARACTERS type; let's
* NOT do thorough check here -- that'll be up to specific
* CDATA unit tests on a separate suite.
*/
int type = sr.next();
assertTrue("Expected either CDATA or CHARACTERS event, got "+type,
(type == CDATA || type == CHARACTERS));
String str = getAndVerifyText(sr);
/* If we are not coalescing, data can (in theory) be split
* up...
*/
if (coalescing) {
type = sr.next();
} else {
while (true) {
type = sr.next();
if (type != CDATA && type != CHARACTERS) {
break;
}
str += getAndVerifyText(sr);
}
}
String exp = OUT_SPACES1+OUT_SPACES2;
if (!str.equals(exp)) {
fail("Failed (coalesce: "+coalescing+", ns-aware: "+ns+"); expected '"
+printable(exp)+"', got '"+printable(str)+"'.");
}
// Plus, should get the close element too
assertEquals(END_ELEMENT, type);
assertEquals("root", sr.getLocalName());
assertEquals(null, sr.getPrefix());
// And then the end doc
assertEquals(END_DOCUMENT, sr.next());
}
public void testLfInProcInstr()
throws XMLStreamException
{
/* Since exact handling of the white space between target and
* data is not well-defined by the specs, let's just add markers
* and trim such white space out...
*/
final String contents = ""
+"";
/* There really shouldn't be any difference between coalescing/non
* or namespace aware/non-ns modes, let's try out the combinations
* just in case
*/
for (int i = 0; i < 4; ++i) {
XMLInputFactory f = getInputFactory();
setCoalescing(f, ((i & 1) == 0));
setNamespaceAware(f, ((i & 2) == 0));
XMLStreamReader sr = constructStreamReader(f, contents);
// Then should get the root element:
// Either way, needs to have the root element now
assertEquals(START_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
assertEquals(null, sr.getPrefix());
assertEquals(PROCESSING_INSTRUCTION, sr.next());
assertEquals("target", sr.getPITarget());
// Ok, how about the contents:
String data = sr.getPIData();
String exp = "["+OUT_SPACES1+OUT_SPACES2+"]";
assertEquals(printable(exp), printable(data));
// And some more white space + lf handling:
assertEquals(PROCESSING_INSTRUCTION, sr.next());
assertEquals("target", sr.getPITarget());
data = sr.getPIData();
exp = "["+OUT_SPACES3+"]";
System.out.println("PI: exp = '"+printable(exp)+"', act = '"+printable(data)+"'");
assertEquals(printable(exp), printable(data));
// Plus, should get the close element too
assertEquals(END_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
assertEquals(null, sr.getPrefix());
// And then the end doc
assertEquals(END_DOCUMENT, sr.next());
}
}
public void testLfInComment()
throws XMLStreamException
{
final String contents = ""
+""
+""
+""
+""
+"";
/* There really shouldn't be any difference between coalescing/non
* or namespace aware/non-ns modes, but let's try out the combinations
* just in case (some implementations may internally have differing
* handling)
*/
for (int i = 0; i < 4; ++i) {
XMLInputFactory f = getInputFactory();
setCoalescing(f, ((i & 1) == 0));
setNamespaceAware(f, ((i & 2) == 0));
XMLStreamReader sr = constructStreamReader(f, contents);
// Then should get the root element:
// Either way, needs to have the root element now
assertEquals(START_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
assertEquals(null, sr.getPrefix());
assertEquals(COMMENT, sr.next());
assertEquals(printable(OUT_SPACES1), printable(sr.getText()));
assertEquals(COMMENT, sr.next());
assertEquals(printable(OUT_SPACES2), printable(sr.getText()));
assertEquals(COMMENT, sr.next());
assertEquals(printable(OUT_SPACES3), printable(sr.getText()));
assertEquals(COMMENT, sr.next());
assertEquals(printable(OUT_MIXED1), printable(sr.getText()));
// Plus, should get the close element too
assertEquals(END_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
assertEquals(null, sr.getPrefix());
// And then the end doc
assertEquals(END_DOCUMENT, sr.next());
}
}
public void testLfInText()
throws XMLStreamException
{
final String contents = ""+IN_SPACES1+IN_SPACES2+"";
for (int i = 0; i < 4; ++i) { // to test coalescing and non-coalescing
XMLInputFactory f = getInputFactory();
boolean coalescing = ((i & 1) == 0);
setCoalescing(f, coalescing);
setNamespaceAware(f, ((i & 2) == 0));
XMLStreamReader sr = constructStreamReader(f, contents);
assertEquals(START_ELEMENT, sr.next());
assertEquals(CHARACTERS, sr.next());
int type;
String str = getAndVerifyText(sr);
/* If we are not coalescing, data can be split
* up... (but in practice would probably need longer input
* text?)
*/
if (coalescing) {
type = sr.next();
} else {
while (true) {
type = sr.next();
if (type != CDATA && type != CHARACTERS) {
break;
}
str += getAndVerifyText(sr);
}
}
assertEquals(printable(OUT_SPACES1+OUT_SPACES2),
printable(str));
// Plus, should get the close element too
assertEquals(END_ELEMENT, type);
// And then the end doc
assertEquals(END_DOCUMENT, sr.next());
}
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/stream/TestMisc.java 0000644 0001750 0001750 00000016431 10444554662 024405 0 ustar twerner twerner package org.codehaus.stax.test.stream;
import javax.xml.stream.*;
/**
* Unit test suite that tests miscallenous stream reader methods, such
* as require(), getElementText() and nextTag()
*/
public class TestMisc
extends BaseStreamTest
{
public TestMisc(String name) {
super(name);
}
public void testRequire()
throws XMLStreamException
{
String XML =
""
+""
+"Text"
+""
+""
+""
;
XMLStreamReader sr = getReader(XML, true, true);
sr.require(START_DOCUMENT, null, null);
assertTokenType(START_ELEMENT, sr.next());
assertTokenType(COMMENT, sr.next());
sr.require(COMMENT, null, null);
try { // should get an exception due to comments not having names
sr.require(COMMENT, null, "tag");
fail("Should have thrown an exception when checking local name of a COMMENT");
} catch (XMLStreamException e) {
; // good
}
assertTokenType(PROCESSING_INSTRUCTION, sr.next());
sr.require(PROCESSING_INSTRUCTION, null, null);
assertTokenType(START_ELEMENT, sr.next());
sr.require(START_ELEMENT, null, "tag");
sr.require(START_ELEMENT, "", "tag");
try { // should get an exception due to incorrect ns URI
sr.require(START_ELEMENT, "http://foo", "tag");
fail("Should have thrown an exception for incorrect NS URI");
} catch (XMLStreamException e) {
; // good
}
assertTokenType(CHARACTERS, sr.next());
sr.require(CHARACTERS, null, null);
assertTokenType(END_ELEMENT, sr.next());
sr.require(END_ELEMENT, null, "tag");
sr.require(END_ELEMENT, "", "tag");
assertTokenType(START_ELEMENT, sr.next());
/* Will get CHARACTERS instead of CDATA, because it's a
* coalescing reader...
*/
assertTokenType(CHARACTERS, sr.next());
sr.require(CHARACTERS, null, null);
assertTokenType(END_ELEMENT, sr.next());
assertTokenType(START_ELEMENT, sr.next()); // empty
sr.require(START_ELEMENT, "http://foo", "empty");
assertTokenType(END_ELEMENT, sr.next());
sr.require(END_ELEMENT, "http://foo", "empty");
sr.require(END_ELEMENT, "http://foo", null);
sr.require(END_ELEMENT, null, "empty");
assertTokenType(END_ELEMENT, sr.next());
sr.require(END_ELEMENT, "", "root");
assertTokenType(END_DOCUMENT, sr.next());
sr.require(END_DOCUMENT, null, null);
}
public void testGetElementText()
throws XMLStreamException
{
String XML =
""
+"Got some text 'n stuff!"
+"more "
+""
+""
;
XMLStreamReader sr = getReader(XML, true, false);
// First 2 valid cases:
assertTokenType(START_ELEMENT, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals("Got some text 'n stuff!", sr.getElementText());
assertTokenType(END_ELEMENT, sr.getEventType());
assertTokenType(START_ELEMENT, sr.next());
assertEquals("more stuff ", sr.getElementText());
assertTokenType(END_ELEMENT, sr.getEventType());
// and then invalid
assertTokenType(START_ELEMENT, sr.next());
try {
String str = sr.getElementText();
fail("Expected an exception for nested start element");
} catch (XMLStreamException ex) {
; // ok!
}
}
public void testNextTag()
throws XMLStreamException
{
String XML =
" "
+" "
+" "
+"text"
;
XMLStreamReader sr = getReader(XML, true, false);
// First valid cases:
assertTokenType(START_ELEMENT, sr.nextTag());
assertEquals("root", sr.getLocalName());
assertTokenType(START_ELEMENT, sr.nextTag());
assertTokenType(END_ELEMENT, sr.nextTag());
assertEquals("tag", sr.getLocalName());
assertTokenType(START_ELEMENT, sr.nextTag());
assertEquals("tag", sr.getLocalName());
assertTokenType(START_ELEMENT, sr.nextTag());
assertEquals("leaf", sr.getLocalName());
assertTokenType(END_ELEMENT, sr.nextTag());
assertEquals("leaf", sr.getLocalName());
assertTokenType(END_ELEMENT, sr.nextTag());
assertEquals("tag", sr.getLocalName());
// And then invalid:
assertTokenType(START_ELEMENT, sr.nextTag());
assertEquals("tag", sr.getLocalName());
try {
int type = sr.nextTag();
fail("Expected an exception for non-whitespace text");
} catch (XMLStreamException ex) {
; // ok!
}
}
public void testNextTagWithCommentsAndPIs()
throws XMLStreamException
{
String XML =
" \n"
+"\n"
+" \n"
+"\n"
+""
;
XMLStreamReader sr = getReader(XML, true, false);
assertTokenType(START_ELEMENT, sr.nextTag());
assertEquals("root", sr.getLocalName());
// First, an empty 'leaf' element
assertTokenType(START_ELEMENT, sr.nextTag());
assertEquals("leaf", sr.getLocalName());
assertTokenType(END_ELEMENT, sr.nextTag());
assertEquals("leaf", sr.getLocalName());
// Then one with a single PI in it
assertTokenType(START_ELEMENT, sr.nextTag());
assertEquals("leaf", sr.getLocalName());
assertTokenType(END_ELEMENT, sr.nextTag());
assertEquals("leaf", sr.getLocalName());
// Then one with multiple comments
assertTokenType(START_ELEMENT, sr.nextTag());
assertEquals("leaf", sr.getLocalName());
assertTokenType(END_ELEMENT, sr.nextTag());
assertEquals("leaf", sr.getLocalName());
// Then one with a mix:
assertTokenType(START_ELEMENT, sr.nextTag());
assertEquals("leaf", sr.getLocalName());
assertTokenType(END_ELEMENT, sr.nextTag());
assertEquals("leaf", sr.getLocalName());
// And then the closing root tag
assertTokenType(END_ELEMENT, sr.nextTag());
assertEquals("root", sr.getLocalName());
}
/*
////////////////////////////////////////
// Private methods, other
////////////////////////////////////////
*/
private XMLStreamReader getReader(String contents, boolean nsAware,
boolean coalescing)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setNamespaceAware(f, nsAware);
setSupportDTD(f, true);
setCoalescing(f, coalescing);
setReplaceEntities(f, true);
setValidating(f, false);
return constructStreamReader(f, contents);
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/stream/TestFilteredReader.java 0000644 0001750 0001750 00000004066 10444554662 026374 0 ustar twerner twerner package org.codehaus.stax.test.stream;
import java.io.*;
import javax.xml.stream.*;
/**
* Simple unit test suite that tries to if filtered stream readers are
* constructed and can be used.
*
* One thing to note, though, is that the StAX specs do not tell much
* anything about expected ways that the implementation is to deal with
* problems resulting from filtering END_DOCUMENT event and so forth.
*
* @author Tatu Saloranta
*/
public class TestFilteredReader
extends BaseStreamTest
{
/**
* Simplest possible test: let's only check that we can actually
* construct an instance with dummy filter that accepts everything,
* and that we can traverse through all the events as usual.
*/
public void testCreation()
throws XMLStreamException
{
XMLStreamReader sr = createFilteredReader(new MyFilter(), "text", true);
assertTokenType(START_DOCUMENT, sr.getEventType());
assertTokenType(START_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
assertEquals(0, sr.getAttributeCount());
assertNotNull(sr.getName());
assertTokenType(CHARACTERS, sr.next());
assertEquals("text", getAndVerifyText(sr));
assertTokenType(END_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
assertTokenType(END_DOCUMENT, sr.next());
}
/*
////////////////////////////////////////
// Non-test methods
////////////////////////////////////////
*/
private XMLStreamReader createFilteredReader(StreamFilter filter, String content,
boolean nsAware)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setNamespaceAware(f, nsAware);
XMLStreamReader base = constructStreamReader(f, content);
return f.createFilteredReader(base, filter);
}
final static class MyFilter
implements StreamFilter
{
public boolean accept(XMLStreamReader reader) {
return true;
}
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/stream/TestProcInstrRead.java 0000644 0001750 0001750 00000023433 10444554662 026231 0 ustar twerner twerner package org.codehaus.stax.test.stream;
import javax.xml.stream.*;
/**
* Unit test suite that tests handling of XML processing instructions (except
* for the linefeed normalization which is tested elsewhere); mostly just what
* properties is the stream reader returning when pointing to a comment.
*/
public class TestProcInstrRead
extends BaseStreamTest
{
public TestProcInstrRead(String name) {
super(name);
}
/**
* Method that checks properties of PROCESSING_INSTRUCTION
* returned by the stream reader are correct according to StAX specs.
*/
public void testProcInstrProperties()
throws XMLStreamException
{
/* Neither ns-awareness nor dtd-support should make any differnece,
* but let's double check them...
*/
doTestProperties(true, true);
doTestProperties(true, false);
doTestProperties(false, true);
doTestProperties(false, false);
}
public void testSpaceHandling()
throws XMLStreamException
{
String CONTENT_TEXT = "some data ";
String CONTENT = " "+CONTENT_TEXT;
String XML = "";
for (int i = 0; i < 3; ++i) {
boolean ns = (i & 1) != 0;
boolean dtd = (i & 2) != 0;
XMLStreamReader sr = getReader(XML, ns, dtd);
assertTokenType(PROCESSING_INSTRUCTION, sr.next());
assertEquals("target", sr.getPITarget());
String content = sr.getPIData();
// Is content exactly as expected?
if (!content.equals(CONTENT_TEXT)) {
// Nope... but would it be without white space?
if (CONTENT_TEXT.trim().equals(content.trim())) {
fail("Proc. instr. white space handling not correct: expected data '"
+CONTENT_TEXT+"', got '"+content+"'");
}
// Nah, totally wrong:
fail("Processing instruction data incorrect: expected '"
+CONTENT_TEXT+"', got '"+content+"'");
}
}
}
public void testInvalidProcInstr()
throws XMLStreamException
{
String XML = "";
String XML2 = " ?> ";
String XML3 = "";
for (int i = 0; i < 3; ++i) {
boolean ns = (i & 1) != 0;
boolean dtd = (i & 2) != 0;
streamThroughFailing(getReader(XML, ns, dtd),
"invalid processing instruction target ('xml' [case-insensitive] not legal) [ns: "+ns+", dtd: "+dtd+"]");
streamThroughFailing(getReader(XML2, ns, dtd),
"invalid processing instruction; empty proc. instr (missing target)");
streamThroughFailing(getReader(XML3, ns, dtd),
"invalid processing instruction; ends with '?', not \"?>\"");
}
}
public void testUnfinishedPI()
throws XMLStreamException
{
String XML = "";
for (int i = 0; i < 3; ++i) {
boolean ns = (i & 1) != 0;
streamThroughFailing(getReader(XML, ns, true),
"invalid proc. instr. (unfinished)");
}
}
/**
* This unit test checks that the parser does not allow split processing
* instructions; ones that start from within an entity expansion, but do
* not completely finish within entity expansion, but in the original
* input source that referenced the entity.
* Such markup is illegal according to XML specs.
*/
public void testRunawayProcInstr()
throws XMLStreamException
{
String XML = "\n"
+"]>"
+ "π?>";
XMLStreamReader sr = getReader(XML, true, true);
try {
// May get an exception when parsing entity declaration... ?
// (since it contains partial token)
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
int type = sr.next();
if (type != PROCESSING_INSTRUCTION) {
reportNADueToEntityExpansion("testRunawayProcInstr", type);
return;
}
type = sr.next();
fail("Expected an exception for split/runaway processing instruction (instead got event "+tokenTypeDesc(type)+")");
} catch (XMLStreamException sex) {
// good
} catch (RuntimeException rex) {
// some impls. throw lazy exceptions, too...
}
}
/**
* Unit test based on a bug found in the Stax reference implementation.
*/
public void testLongerProcInstr()
throws XMLStreamException
{
String XML = "\n\n"
+"\n\n"
+"\n\n"
+"\n"
+"]>\n\n"
+"\n"
+" &eduni-errata2e;\n"
+"\n";
XMLStreamReader sr = getReader(XML, true, true);
// May get an exception when parsing entity declaration... ?
// (since it contains partial token)
int type;
while ((type = sr.next()) == SPACE) { }
assertTokenType(COMMENT, type);
while ((type = sr.next()) == SPACE) { }
assertTokenType(PROCESSING_INSTRUCTION, type);
assertEquals("xml-stylesheet", sr.getPITarget());
while ((type = sr.next()) == SPACE) { }
assertTokenType(DTD, type);
while ((type = sr.next()) == SPACE) { }
assertTokenType(START_ELEMENT, type);
}
/*
////////////////////////////////////////
// Private methods, shared test code
////////////////////////////////////////
*/
private void doTestProperties(boolean ns, boolean dtd)
throws XMLStreamException
{
final String DATA = "data & more data (???) <>";
XMLStreamReader sr = getReader("", ns, dtd);
assertEquals(PROCESSING_INSTRUCTION, sr.next());
// Type info
assertEquals(false, sr.isStartElement());
assertEquals(false, sr.isEndElement());
assertEquals(false, sr.isCharacters());
assertEquals(false, sr.isWhiteSpace());
// indirect type info
assertFalse("Processing instructions have no names; XMLStreamReader.hasName() should return false", sr.hasName());
assertEquals(false, sr.hasText());
assertNotNull(sr.getLocation());
if (ns) {
assertNotNull(sr.getNamespaceContext());
}
// And then let's check methods that should throw specific exception
for (int i = 0; i < 10; ++i) {
String method = "";
try {
Object result = null;
switch (i) {
case 0:
method = "getName";
result = sr.getName();
break;
case 1:
method = "getPrefix";
result = sr.getPrefix();
break;
case 2:
method = "getLocalName";
result = sr.getLocalName();
break;
case 3:
method = "getNamespaceURI";
result = sr.getNamespaceURI();
break;
case 4:
method = "getNamespaceCount";
result = new Integer(sr.getNamespaceCount());
break;
case 5:
method = "getAttributeCount";
result = new Integer(sr.getAttributeCount());
break;
case 6:
method = "getText";
result = sr.getText();
break;
case 7:
method = "getTextCharacters";
result = sr.getTextCharacters();
break;
case 8:
method = "getTextStart";
result = new Integer(sr.getTextStart());
break;
case 9:
method = "getTextLength";
result = new Integer(sr.getTextLength());
break;
}
fail("Expected IllegalStateException, when calling "
+method+"() for PROCESSING_INSTRUCTION");
} catch (IllegalStateException iae) {
; // good
}
}
assertEquals("target", sr.getPITarget());
/* Now; specs are bit vague WRT white space handling between target
* and data; thus, let's just trim trailing/leading white space
*/
/* 13-Nov-2004, TSa: Actually, handling is to get rid
* of leading but not trailing white space, as per XML specs.
* StAX API is not clear, but another test will verify proper
* behaviour.
*/
assertEquals(DATA.trim(), sr.getPIData().trim());
}
/*
////////////////////////////////////////
// Private methods, other
////////////////////////////////////////
*/
private XMLStreamReader getReader(String contents, boolean nsAware,
boolean supportDTD)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setCoalescing(f, false); // shouldn't really matter
setNamespaceAware(f, nsAware);
setSupportDTD(f, supportDTD);
setValidating(f, false);
return constructStreamReader(f, contents);
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/stream/TestEntityRead.java 0000644 0001750 0001750 00000052335 10444554662 025565 0 ustar twerner twerner package org.codehaus.stax.test.stream;
import javax.xml.stream.*;
import org.codehaus.stax.test.SimpleResolver;
/**
* Unit test suite that tests handling of various kinds of entities.
*/
public class TestEntityRead
extends BaseStreamTest
{
public TestEntityRead(String name) {
super(name);
}
/**
* Method that tests properties of unresolved DTD event.
*/
public void testEntityProperties()
throws XMLStreamException
{
// Ns-awareness should make no different, but let's double-check it:
doTestProperties(true);
doTestProperties(false);
}
public void testValidPredefdEntities()
throws XMLStreamException
{
String EXP = "Testing \"this\" & 'that' !? !";
String XML = "Testing "this" & 'that' !? !";
XMLStreamReader sr = getReader(XML, false, true, true);
assertTokenType(START_ELEMENT, sr.next());
assertTokenType(CHARACTERS, sr.next());
// Let's not count on coalescing working, though...
StringBuffer sb = new StringBuffer(getAndVerifyText(sr));
int type;
while ((type = sr.next()) == CHARACTERS) {
sb.append(getAndVerifyText(sr));
}
assertEquals(EXP, sb.toString());
assertTokenType(END_ELEMENT, type);
}
/**
* This unit test checks that handling of character entities works
* as expected, including corner cases like characters that expand
* to surrogate pairs in Java.
*/
public void testValidCharEntities()
throws XMLStreamException
{
String XML = "surrogates: .";
XMLStreamReader sr = getReader(XML, true, true, true);
assertTokenType(START_ELEMENT, sr.next());
assertTokenType(CHARACTERS, sr.next());
// may still be split, though (buggy coalescing)
StringBuffer sb = new StringBuffer(getAndVerifyText(sr));
int type;
while ((type = sr.next()) == CHARACTERS) {
sb.append(getAndVerifyText(sr));
}
String result = sb.toString();
String exp = "surrogates: \uD900\uDC00.";
if (!exp.equals(result)) {
failStrings("Expected character entity &x#50000 to expand to surrogate pair with chars 0xD900 and 0xDC00", exp, result);
}
assertTokenType(END_ELEMENT, type);
sr.close();
}
public void testValidGeneralEntities()
throws XMLStreamException
{
String EXP = "y yabc abc&";
String XML = "\n"
+""
+""
+"]>\n"
+"&x; &both; &aa;&myAmp;";
XMLStreamReader sr = getReader(XML, false, true, true);
assertTokenType(DTD, sr.next());
int type = sr.next();
if (type == SPACE) {
type = sr.next();
}
assertTokenType(START_ELEMENT, type);
assertTokenType(CHARACTERS, sr.next());
String actual = getAndVerifyText(sr);
assertEquals(EXP, actual);
/* !!! TBI: test things like:
*
* - Allow using single and double quotes in entity expansion value
* via param entity expansion (see next entry)
* - Rules for expanding char entities vs. generic entities (esp.
* regarding parameter entities)
*/
}
/**
* Test that checks that generic parsed entities are returned as
* entity reference events, when automatic entity expansion is disabled.
*/
public void testUnexpandedEntities()
throws XMLStreamException
{
String TEXT1 = ""Start"";
String TEXT2 = "&End...";
String XML = "]>\n"
+"&Start"&myent;End!";
XMLStreamReader sr = getReader(XML, false, true, false);
assertTokenType(DTD, sr.next());
int type = sr.next();
// May or may not get SPACE events in epilog (before root)
while (type == SPACE) {
type = sr.next();
}
assertTokenType(START_ELEMENT, type);
assertTokenType(CHARACTERS, sr.next());
assertEquals("&Start\"", getAndVerifyText(sr));
assertTokenType(ENTITY_REFERENCE, sr.next());
assertEquals("myent", sr.getLocalName());
assertEquals("data", getAndVerifyText(sr));
assertTokenType(CHARACTERS, sr.next());
assertEquals("End!", getAndVerifyText(sr));
assertTokenType(END_ELEMENT, sr.next());
assertTokenType(END_DOCUMENT, sr.next());
/* And then, for good measure, let's just do a longer
* one, but without exact type checks, and both with and
* without coalescing:
*/
XML = "]>\n"
+"&Start"&myent;End!\n"
+" !&myent;&myent;&myent;&"
+"";
// First, no coalescing
sr = getReader(XML, false, false, false);
streamThrough(sr);
// then with coalescing
sr = getReader(XML, false, true, false);
streamThrough(sr);
}
public void testUnexpandedEntities2()
throws XMLStreamException
{
/* Note: as per XML 1.0 specs, non-char entities (including pre-defined
* entities like 'amp' and 'lt'!) are not to be expanded before entity
* that contains them is expanded... so they are returned unexpanded.
* Char entities, however, are to be expanded.
*/
String ENTITY_VALUE = "Something slightly longer & challenging\nwhich may or may not work";
String XML = "]>"
+"&myent;";
XMLStreamReader sr = getReader(XML, false, true, false);
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertTokenType(ENTITY_REFERENCE, sr.next());
assertEquals("myent", sr.getLocalName());
// Ok, let's try the other access method:
/* 05-Apr-2006, TSa: Actually, getTextXxx() methods are not
* legal for ENTITY_REFERENCEs, can't check:
*/
/*
int len = sr.getTextLength();
assertEquals(ENTITY_VALUE.length(), len);
int start = sr.getTextStart();
char[] ch = new char[len];
sr.getTextCharacters(0, ch, 0, len);
assertEquals(ENTITY_VALUE, new String(ch));
*/
assertEquals(ENTITY_VALUE, sr.getText());
assertTokenType(END_ELEMENT, sr.next());
assertTokenType(END_DOCUMENT, sr.next());
}
/**
* Test that checks that entities that expand to elements, comments
* and processing instructions are properly handled.
*/
public void testElementEntities()
throws XMLStreamException
{
String XML = "text
'>\n"
+" '>\n"
+" '>\n"
+" \n"
+" \n"
+"]>\n"
+"&ent1;&ent2;&ent3;&ent4a;";
XMLStreamReader sr = getReader(XML, true, true, true);
assertTokenType(DTD, sr.next());
// May or may not get whitespace
int type = sr.next();
if (type == SPACE) {
type = sr.next();
}
assertTokenType(START_ELEMENT, type);
assertEquals("root", sr.getLocalName());
// First, entity that expands to element
type = sr.next();
if (type != START_ELEMENT) { // failure
if (type == ENTITY_REFERENCE) { // most likely failure?
fail("Implementation fails to re-parse general entity expansion text: instead of element , received entity reference &"+sr.getLocalName()+";");
}
if (type == CHARACTERS) {
String text = sr.getText();
fail("Implementation fails to re-parse general entity expansion text: instead of element , received text ["+text.length()+"]: '"+text+"'");
}
assertTokenType(START_ELEMENT, type);
}
assertEquals("tag", sr.getLocalName());
assertTokenType(CHARACTERS, sr.next());
assertEquals("text", sr.getText());
assertTokenType(END_ELEMENT, sr.next());
assertEquals("tag", sr.getLocalName());
// Then one that expands to comment
assertTokenType(COMMENT, sr.next());
assertEquals("comment", sr.getText());
// Then one that expands to a PI
assertTokenType(PROCESSING_INSTRUCTION, sr.next());
assertEquals("proc", sr.getPITarget());
assertEquals("instr", sr.getPIData().trim());
// Then one that expands to text (single char)
assertTokenType(CHARACTERS, sr.next());
assertEquals("A", sr.getText());
assertTokenType(END_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
}
/**
* Test that verifies that it is possible to quote CDATA end marker
* ("]]>") using character and general entities.
*/
public void testQuotedCDataEndMarker()
throws XMLStreamException
{
try {
// First, using pre-defined/char entities
String XML = ""
+"Ok the usual one: ]]>"
+" and then alternatives: ]]>"
+", ]]>"
+"";
XMLStreamReader sr = getReader(XML, true, false, true);
streamThrough(sr);
} catch (Exception e) {
fail("Didn't except problems with pre-def/char entity quoted ']]>'; got: "+e);
}
try {
// Then using general entities:
String XML = "\n"
+"]>\n"
+""
+" &doubleBracket;> and &doubleBracket;>"
+"";
XMLStreamReader sr = getReader(XML, true, false, true);
streamThrough(sr);
} catch (Exception e) {
fail("Didn't except problems with general entity quoted ']]>'; got: "+e);
}
}
/**
* Test that ensures that entities can have quotes in them, if quotes
* are expanded from (parameter) entities. For that need to use
* external entities, or at least ext. subset.
*/
/*
public void testValidEntityWithQuotes()
throws XMLStreamException
{
}
*/
public void testInvalidEntityUndeclared()
throws XMLStreamException
{
XMLStreamReader sr = getReader("&myent;",
true, false, true);
try {
streamThrough(sr);
fail("Expected an exception for invalid comment content");
} catch (Exception e) { }
}
public void testInvalidEntityRecursive()
throws XMLStreamException
{
XMLStreamReader sr = getReader
("\n"
+"\n"
+"]> &ent1;",
false, true, true);
streamThroughFailing(sr, "recursive general entity/ies");
/* !!! TBI: test things like:
*
* - Incorrectly nested entities (only start element, no end etc)
*/
}
public void testInvalidEntityPEInIntSubset()
throws XMLStreamException
{
/* Although PEs are allowed in int. subset, they can only be
* used to replace whole declarations; not in entity value
* expansions.
*/
XMLStreamReader sr = getReader
("\n"
+"\n"
+"]> ",
false, true, true);
streamThroughFailing(sr, "declaring a parameter entity in the internal DTD subset");
}
/**
* Test that ensures that an invalid 'partial' entity is caught;
* partial meaning that only beginning part of an entity (ie ampersand
* and zero or more of the first characters of entity id) come from
* another expanded entity, and rest comes from content following.
* Such partial entities are not legal according to XML specs.
*/
public void testInvalidEntityPartial()
throws XMLStreamException
{
XMLStreamReader sr = getReader
("\n"
+"]>&partial;;",
false, false, true);
/* Hmmh. Actually, fully conforming implementations should throw
* an exception when parsing internal DTD subset. But better
* late than never; it's ok to fail on expansion too, as far as
* this test is concerned.
*/
int type1, type2;
int lastType;
try {
type1 = sr.next();
type2 = sr.next();
while ((lastType = sr.next()) == CHARACTERS) {
;
}
} catch (XMLStreamException e) {
return; // ok
} catch (RuntimeException e) { // some impls throw lazy exceptions
return; // ok
}
assertTokenType(DTD, type1);
assertTokenType(START_ELEMENT, type2);
fail("Expected an exception for partial entity reference: current token after text: "+tokenTypeDesc(lastType));
}
/**
* This unit test checks that external entities can be resolved; and
* to do that without requiring external files, will use a simple
* helper resolver
*/
public void testExternalEntityWithResolver()
throws XMLStreamException
{
String ENTITY_VALUE1 = "some text from the external entity";
String ACTUAL_VALUE1 = "ent='"+ENTITY_VALUE1+"'";
String XML =
"\n"
+"]>ent='&extEnt;'";
// ns-aware, coalescing (to simplify verifying), entity expanding
XMLInputFactory f = doGetFactory(true, true, true);
if (!setSupportExternalEntities(f, true)) {
reportNADueToExtEnt("testExternalEntityWithResolver");
return;
}
setResolver(f, new SimpleResolver(ENTITY_VALUE1));
// First, simple content without further expansion etc
XMLStreamReader sr = constructStreamReader(f, XML);
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertTokenType(CHARACTERS, sr.next());
assertEquals(ACTUAL_VALUE1, getAndVerifyText(sr));
assertTokenType(END_ELEMENT, sr.next());
sr.close();
// Then bit more complicated one:
String ENTITY_VALUE2 = "external entity: this & that &intEnt;";
String ACTUAL_VALUE2a = "ent='external entity: ";
String ACTUAL_VALUE2b = " this & that & more!'";
String XML2 =
"\n"
+"\n"
+"]>ent='&extEnt;'";
setResolver(f, new SimpleResolver(ENTITY_VALUE2));
sr = constructStreamReader(f, XML2);
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertTokenType(CHARACTERS, sr.next());
assertEquals(ACTUAL_VALUE2a, getAndVerifyText(sr));
assertTokenType(START_ELEMENT, sr.next());
assertEquals("leaf", sr.getLocalName());
assertTokenType(END_ELEMENT, sr.next());
assertTokenType(CHARACTERS, sr.next());
assertEquals(ACTUAL_VALUE2b, getAndVerifyText(sr));
assertTokenType(END_ELEMENT, sr.next());
sr.close();
}
/*
////////////////////////////////////////
// Private methods, shared test code
////////////////////////////////////////
*/
private void doTestProperties(boolean nsAware)
throws XMLStreamException
{
XMLStreamReader sr = getReader
("\n"
+"\n"
+"]>&myent;&ent2;",
nsAware, false, false);
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertTokenType(ENTITY_REFERENCE, sr.next());
/* Ok, now we can test actual properties we
* are interested in:
*/
// Type info
assertEquals(false, sr.isStartElement());
assertEquals(false, sr.isEndElement());
assertEquals(false, sr.isCharacters());
assertEquals(false, sr.isWhiteSpace());
// indirect type info
/* 29-Jul-2004: It's kind of unintuitive, but API says hasName()
* is only true for start/end elements...
*/
assertEquals(false, sr.hasName());
/* And this returns true at least for internal entities, like the one
* we hit first
*/
assertEquals(true, sr.hasText());
// Now, local name is accessible, still:
assertEquals("myent", sr.getLocalName());
// And replacement text too:
assertEquals("value", getAndVerifyText(sr));
assertNotNull(sr.getLocation());
if (nsAware) {
assertNotNull(sr.getNamespaceContext());
}
// And then let's check methods that should throw specific exception
for (int i = 0; i <= 9; ++i) {
String method = "";
try {
Object result = null;
switch (i) {
case 0:
method = "getName";
result = sr.getName();
break;
case 1:
method = "getPrefix";
result = sr.getPrefix();
break;
case 2:
method = "getNamespaceURI";
result = sr.getNamespaceURI();
break;
case 3:
method = "getNamespaceCount";
result = new Integer(sr.getNamespaceCount());
break;
case 4:
method = "getAttributeCount";
result = new Integer(sr.getAttributeCount());
break;
case 5:
method = "getPITarget";
result = sr.getPITarget();
break;
case 6:
method = "getPIData";
result = sr.getPIData();
break;
case 7:
method = "getTextCharacters";
result = sr.getTextCharacters();
break;
case 8:
method = "getTextStart";
result = new Integer(sr.getTextStart());
break;
case 9:
method = "getTextLength";
result = new Integer(sr.getTextLength());
break;
}
fail("Expected IllegalArgumentException, when calling "
+method+"() for ENTITY_REFERENCE");
} catch (IllegalStateException iae) {
; // good
}
}
// // Ok, and the second entity; an external one
assertTokenType(ENTITY_REFERENCE, sr.next());
assertEquals("ent2", sr.getLocalName());
/* Now, text replacement... it seems like hasText() should still
* return true, by default, but getText() (etc) should return
* null?
*/
String text = sr.getText();
if (text != null && text.length() > 0) {
fail("Expected getText() for external entity 'ent2' to return null or empty String; instead got '"+text+"'");
}
// // ok, should be good:
assertTokenType(END_ELEMENT, sr.next());
assertTokenType(END_DOCUMENT, sr.next());
}
/*
////////////////////////////////////////
// Private methods, other
////////////////////////////////////////
*/
/**
* Note: all readers for this set of unit tests enable DTD handling;
* otherwise entity definitions wouldn't be read. Validation shouldn't
* need to be enabled just for that purpose.
*/
private XMLStreamReader getReader(String contents, boolean nsAware,
boolean coalescing, boolean replEntities)
throws XMLStreamException
{
XMLInputFactory f = doGetFactory(nsAware, coalescing, replEntities);
return constructStreamReader(f, contents);
}
private XMLInputFactory doGetFactory(boolean nsAware,
boolean coalescing, boolean replEntities)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setNamespaceAware(f, nsAware);
setSupportDTD(f, true);
setCoalescing(f, coalescing);
setReplaceEntities(f, replEntities);
setValidating(f, false);
return f;
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/stream/TestDoctypeDecl.java 0000644 0001750 0001750 00000020143 10444554662 025704 0 ustar twerner twerner package org.codehaus.stax.test.stream;
import javax.xml.stream.*;
/**
* Unit test suite that tests handling of the DOCTYPE declaration event
* (XMLStreamConstants.DTD)
*/
public class TestDoctypeDecl
extends BaseStreamTest
{
public TestDoctypeDecl(String name) {
super(name);
}
/**
* Method that verifies properties that should be active when
* DTD is the current event.
*/
public void testProperties()
throws XMLStreamException
{
doTestProperties(false);
doTestProperties(true);
}
public void testMinimalValidDecl()
throws XMLStreamException
{
doTestMinimalValid(false);
doTestMinimalValid(true);
}
public void testSimpleValidDecl()
throws XMLStreamException
{
doTestSimpleValid(false);
doTestSimpleValid(true);
}
public void testTypicalValid()
throws XMLStreamException
{
doTestTypicalValid(false);
doTestTypicalValid(true);
}
public void testSimpleInvalidDecl()
throws XMLStreamException
{
doTestSimpleInvalid(false);
doTestSimpleInvalid(true);
}
/*
////////////////////////////////////////
// Private methods, shared test code
////////////////////////////////////////
*/
private void doTestProperties(boolean nsAware)
throws XMLStreamException
{
final String PROP_TEST =
" ]>";
XMLStreamReader sr = getReader(PROP_TEST, nsAware);
assertEquals(DTD, sr.next());
// Type info
assertEquals(false, sr.isStartElement());
assertEquals(false, sr.isEndElement());
assertEquals(false, sr.isCharacters());
assertEquals(false, sr.isWhiteSpace());
// indirect type info
assertEquals(false, sr.hasName());
assertEquals(true, sr.hasText());
// And then let's check methods that should throw specific exception
for (int i = 0; i <= 10; ++i) {
String method = "";
try {
Object result = null;
switch (i) {
case 0:
method = "getName";
result = sr.getName();
break;
case 1:
method = "getPrefix";
result = sr.getPrefix();
break;
case 2:
method = "getLocalName";
result = sr.getLocalName();
break;
case 3:
method = "getNamespaceURI";
result = sr.getNamespaceURI();
break;
case 4:
method = "getNamespaceCount";
result = new Integer(sr.getNamespaceCount());
break;
case 5:
method = "getAttributeCount";
result = new Integer(sr.getAttributeCount());
break;
case 6:
method = "getPITarget";
result = sr.getPITarget();
break;
case 7:
method = "getPIData";
result = sr.getPIData();
break;
case 8:
method = "getTextCharacters";
result = sr.getTextCharacters();
break;
case 9:
method = "getTextStart";
result = new Integer(sr.getTextStart());
break;
case 10:
method = "getTextLength";
result = new Integer(sr.getTextLength());
break;
}
fail("Expected IllegalArgumentException, when calling "
+method+"() for DTD");
} catch (IllegalStateException iae) {
; // good
}
}
/* Here let's only check it's not null or empty, not exact contents
* (there are other tests for checking contents)
*/
String str = sr.getText();
if (str == null || str.trim().length() == 0) {
fail("Internal subset not available; StreamReader.getText() returned an empty String (after trim())");
}
}
private void doTestMinimalValid(boolean nsAware)
throws XMLStreamException
{
final String VALID_TEST = "";
XMLStreamReader sr = getReader(VALID_TEST, nsAware);
assertEquals(DTD, sr.next());
assertEquals(START_ELEMENT, sr.next());
}
private void doTestSimpleValid(boolean nsAware)
throws XMLStreamException
{
final String INT_SUBSET = "";
final String VALID_TEST =
"";
XMLStreamReader sr = getReader(VALID_TEST, nsAware);
assertTokenType(DTD, sr.next());
/* Now... exactly what should be returned is not quite clear.
* Let's assume that leading/trailing white space may be truncated,
* but that otherwise we'll get stuff back, with linefeeds
* normalized?
*/
String str = getAndVerifyText(sr).trim();
/* 16-Aug-2004, TSa: Hmmh. Specs are bit confusing; in some places
* claiming it should be only the internal subset, in others that
* it should be the full DOCTYPE declaration production...
*/
assertEquals(INT_SUBSET, str);
sr.close();
/* 05-Apr-2006, TSa: Following is actually invalid, but
* well-formed. And as such, it should not throw an exception
* in non-validating mode (but should in validating mode).
*/
final String VALID_TEST2 = "";
sr = getReader(VALID_TEST2, nsAware);
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals("fubar", sr.getLocalName());
assertTokenType(END_ELEMENT, sr.next());
assertTokenType(END_DOCUMENT, sr.next());
}
private void doTestTypicalValid(boolean nsAware)
throws XMLStreamException
{
final String VALID_TEST = "\n"
+"\n"
+"]>\n"
+"";
XMLStreamReader sr = getReader(VALID_TEST, nsAware);
assertTokenType(DTD, sr.next());
// May or may not get SPACE... if we get it, will skip
int type;
while ((type = sr.next()) == SPACE) {
;
}
assertTokenType(START_ELEMENT, type);
}
private void doTestSimpleInvalid(boolean nsAware)
throws XMLStreamException
{
final String INVALID1 = " ";
streamThroughFailing(getReader(INVALID1, nsAware),
"invalid DOCTYPE declaration (missing root element)");
final String INVALID3 = "";
streamThroughFailing(getReader(INVALID3, nsAware),
"invalid DOCTYPE declaration (missing SYSTEM identifier for DTD)");
final String INVALID4 = "";
streamThroughFailing(getReader(INVALID4, nsAware),
"invalid DOCTYPE declaration (missing PUBLIC identifier for DTD)");
final String INVALID5 = "";
streamThroughFailing(getReader(INVALID5, nsAware),
"invalid DOCTYPE declaration (unexpected ampersand character)");
}
/*
////////////////////////////////////////
// Private methods, other
////////////////////////////////////////
*/
private XMLStreamReader getReader(String contents, boolean nsAware)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setCoalescing(f, false); // shouldn't matter
setNamespaceAware(f, nsAware);
setValidating(f, false);
setSupportDTD(f, true);
return constructStreamReader(f, contents);
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/stream/TestEncodingRead.java 0000644 0001750 0001750 00000015113 10444554662 026030 0 ustar twerner twerner package org.codehaus.stax.test.stream;
import java.io.*;
import javax.xml.stream.*;
/**
* Unit test suite that tests handling of text encoding, as specified
* by XML declaration and/or specific byte-order markers.
*/
public class TestEncodingRead
extends BaseStreamTest
{
public TestEncodingRead(String name) {
super(name);
}
final String UTF_1 = String.valueOf((char) 0x41); // 'A'
final String UTF_2 = String.valueOf((char) 0xA0); // nbsp
final String UTF_3 = String.valueOf((char) 0xB61); // some char that needs 3-byte encoding
final String UTF_CONTENT = ""
+UTF_1 + UTF_2 + UTF_3
+UTF_1 + UTF_1 + UTF_2 + UTF_2 + UTF_3 + UTF_3
+UTF_3 + UTF_3 + UTF_2 + UTF_2 + UTF_1 + UTF_1
+UTF_1 + UTF_3 + UTF_2
+UTF_2 + UTF_1 + UTF_3
+UTF_2 + UTF_3 + UTF_1
+UTF_3 + UTF_1 + UTF_2
+UTF_3 + UTF_2 + UTF_1
;
final static byte[] BE_BOM = new byte[] { (byte) 0xFE, (byte) 0xFF };
final static byte[] LE_BOM = new byte[] { (byte) 0xFF, (byte) 0xFE };
final static byte[] UTF8_BOM = new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF };
/**
* Test to check that UTF-8 stream with no leading BOM is succesfully
* handled by parser.
*/
public void testUTF8()
throws Exception
{
doTestEncoding("UTF-8", "UTF-8", null);
doTestEncoding("UTF-8", null, null);
}
/**
* Test to check that UTF-8 stream with leading BOM is succesfully
* handled by parser.
*/
public void testUTF8WithBOM()
throws Exception
{
doTestEncoding("UTF-8", "UTF-8", UTF8_BOM);
doTestEncoding("UTF-8", null, UTF8_BOM);
}
public void testUTF8Surrogates()
throws XMLStreamException, IOException
{
String XML = "XXXX";
int ix = XML.indexOf('X');
byte[] src = XML.getBytes("UTF-8");
// A somewhat random high-order Unicode char:
src[ix] = (byte)0xF1;
src[ix+1] = (byte)0x90;
src[ix+2] = (byte)0x88;
src[ix+3] = (byte)0x88;
InputStream in = new ByteArrayInputStream(src);
XMLInputFactory f = getInputFactory();
XMLStreamReader sr = f.createXMLStreamReader(in);
assertTokenType(START_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
assertTokenType(CHARACTERS, sr.next());
String str = getAndVerifyText(sr);
// Should result in a surrogate pair...
assertEquals(2, str.length());
assertEquals((char) 0xd900, str.charAt(0));
assertEquals((char) 0xde08, str.charAt(1));
assertTokenType(END_ELEMENT, sr.next());
}
public void testUTF16BEWithBOM()
throws XMLStreamException,
UnsupportedEncodingException
{
doTestEncoding("UTF-16BE", "UTF-16", BE_BOM);
doTestEncoding("UTF-16BE", null, BE_BOM);
doTestEncoding2(true);
}
public void testUTF16LEWithBOM()
throws XMLStreamException,
UnsupportedEncodingException
{
doTestEncoding("UTF-16LE", "UTF-16", LE_BOM);
doTestEncoding("UTF-16LE", null, LE_BOM);
doTestEncoding2(false);
}
/*
////////////////////////////////////////
// Private methods, shared test code
////////////////////////////////////////
*/
/**
* @param javaEnc Name of encoding as understood by JDK; used to
* instantiate JDK encoder/decoder to use for test
* @param xmlEnc Name of encoding as included in xml declaration;
* null to indicate nothing should be added
* @param bom Pre-defined bom bytes to prepend to input, if any.
*/
public void doTestEncoding(String javaEnc, String xmlEnc,
byte[] bom)
throws XMLStreamException,
UnsupportedEncodingException
{
String XML = ""+UTF_CONTENT+"";
byte[] b = XML.getBytes(javaEnc);
if (bom != null) {
byte[] orig = b;
b = new byte[b.length + bom.length];
System.arraycopy(bom, 0, b, 0, bom.length);
System.arraycopy(orig, 0, b, bom.length, orig.length);
}
XMLStreamReader sr = getReader(b);
if (xmlEnc != null) {
assertEquals(xmlEnc, sr.getCharacterEncodingScheme());
} else {
/* otherwise... should we get some info? Preferably yes;
* (getEncoding() should return auto-detected encoding)
* but this is not strictly mandated by the specs?
*/
}
assertEquals(START_ELEMENT, sr.next());
assertEquals(CHARACTERS, sr.next());
assertEquals(UTF_CONTENT, getAllText(sr));
assertEquals(END_ELEMENT, sr.getEventType());
assertEquals(END_DOCUMENT, sr.next());
}
private void doTestEncoding2(boolean bigEndian)
throws XMLStreamException
{
/* 20-Jan-2006, TSa: Ok, let's try another variation that may
* causes problem; UTF-16 is vague, and if using JDK provided
* readers, parser has to indicate endianness.
*/
final String XML = "\n"
+"text";
int len = XML.length();
byte[] b = new byte[2 + len + len];
if (bigEndian) {
b[0] = (byte) 0xFE;
b[1] = (byte) 0xFF;
} else {
b[0] = (byte) 0xFF;
b[1] = (byte) 0xFE;
}
int offset = bigEndian ? 3 : 2;
for (int i = 0; i < len; ++i) {
b[offset + i + i] = (byte) XML.charAt(i);
}
XMLStreamReader sr = getReader(b);
// may get white space...
int type = sr.next();
if (type == SPACE) {
type = sr.next();
}
assertTokenType(COMMENT, type);
assertTokenType(START_ELEMENT, sr.next());
assertTokenType(CHARACTERS, sr.next());
assertEquals("text", getAndVerifyText(sr));
assertTokenType(END_ELEMENT, sr.next());
sr.close();
}
/*
////////////////////////////////////////
// Private methods, other
////////////////////////////////////////
*/
private XMLStreamReader getReader(byte[] contents)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setValidating(f, false);
return constructStreamReader(f, contents);
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/stream/BlockingStream.java 0000644 0001750 0001750 00000001623 10444554662 025553 0 ustar twerner twerner package org.codehaus.stax.test.stream;
import java.io.*;
/**
* Test stream used to test whether Reader using this stream would
* 'accidentally' cause blocking. Used by {@link TestStreaming}
* unit test suite.
*/
class BlockingStream
extends FilterInputStream
{
public boolean mBlocked = false;
// dummy ctor to keep JUnit happy
public BlockingStream() { super(null); }
public BlockingStream(InputStream is)
{
super(is);
}
public boolean hasBlocked() {
return mBlocked;
}
public int read() throws IOException
{
int r = super.read();
if (r < 0) {
mBlocked = true;
}
return r;
}
public int read(byte[] b, int off, int len) throws IOException
{
int r = super.read(b, off, len);
if (r < 0) {
mBlocked = true;
}
return r;
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/stream/BaseStreamTest.java 0000644 0001750 0001750 00000011305 10444554662 025533 0 ustar twerner twerner package org.codehaus.stax.test.stream;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.codehaus.stax.test.BaseStaxTest;
/**
* Base class for all StaxTest unit tests that test basic non-validating
* stream (cursor) API functionality.
*
* @author Tatu Saloranta
*/
public class BaseStreamTest
extends BaseStaxTest
{
/**
* Switch that can be turned on to verify to display ALL exact Exceptions
* thrown when Exceptions are expected. This is sometimes necessary
* when debugging, since it's impossible to automatically verify
* that Exception is exactly the right one, since there is no
* strict Exception type hierarchy for StAX problems.
*
* Note: Not made 'final static', so that compiler won't inline
* it. Makes possible to do partial re-compilations.
* Note: Since it's only used as the default value, sub-classes
* can separately turn it off as necessary
*/
//protected static boolean DEF_PRINT_EXP_EXCEPTION = true;
protected static boolean DEF_PRINT_EXP_EXCEPTION = false;
protected boolean PRINT_EXP_EXCEPTION = DEF_PRINT_EXP_EXCEPTION;
protected BaseStreamTest() { super(); }
protected BaseStreamTest(String name) {
super(name);
}
/*
//////////////////////////////////////////////////
// "Special" accessors
//////////////////////////////////////////////////
*/
/*
//////////////////////////////////////////////////
// Higher-level test methods
//////////////////////////////////////////////////
*/
/**
* Method that will iterate through contents of an XML document
* using specified stream reader; will also access some of data
* to make sure reader reads most of lazy-loadable data.
* Method is usually called to try to get an exception for invalid
* content.
*
* @return Dummy value calculated on contents; used to make sure
* no dead code is eliminated
*/
protected int streamThrough(XMLStreamReader sr)
throws XMLStreamException
{
int result = 0;
while (sr.hasNext()) {
int type = sr.next();
result += type;
if (sr.hasText()) {
/* will also do basic verification for text content, to
* see that all text accessor methods return same content
*/
result += getAndVerifyText(sr).hashCode();
}
if (sr.hasName()) {
result += sr.getName().hashCode();
}
}
return result;
}
protected int streamThroughFailing(XMLInputFactory f, String contents,
String msg)
throws XMLStreamException
{
int result = 0;
try {
XMLStreamReader sr = constructStreamReader(f, contents);
result = streamThrough(sr);
} catch (XMLStreamException ex) { // good
if (PRINT_EXP_EXCEPTION) {
System.out.println("Expected failure: '"+ex.getMessage()+"' "
+"(matching message: '"+msg+"')");
}
return 0;
} catch (RuntimeException ex2) { // ok
if (PRINT_EXP_EXCEPTION) {
System.out.println("Expected failure: '"+ex2.getMessage()+"' "
+"(matching message: '"+msg+"')");
}
return 0;
} catch (Throwable t) { // not so good
fail("Expected an XMLStreamException or RuntimeException for "+msg
+", got: "+t);
}
fail("Expected an exception for "+msg);
return result; // never gets here
}
protected int streamThroughFailing(XMLStreamReader sr, String msg)
throws XMLStreamException
{
int result = 0;
try {
result = streamThrough(sr);
} catch (XMLStreamException ex) { // good
if (PRINT_EXP_EXCEPTION) {
System.out.println("Expected failure: '"+ex.getMessage()+"' "
+"(matching message: '"+msg+"')");
}
return 0;
} catch (RuntimeException ex2) { // ok
if (PRINT_EXP_EXCEPTION) {
System.out.println("Expected failure: '"+ex2.getMessage()+"' "
+"(matching message: '"+msg+"')");
}
return 0;
} catch (Throwable t) { // not so good
fail("Expected an XMLStreamException or RuntimeException for "+msg
+", got: "+t);
}
fail("Expected an exception for "+msg);
return result; // never gets here
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/stream/TestAttributeRead.java 0000644 0001750 0001750 00000025577 10444554662 026264 0 ustar twerner twerner package org.codehaus.stax.test.stream;
import javax.xml.stream.*;
/**
* Unit test suite that tests handling of the XML attributes, both
* in namespace aware and non-namespace modes, including ensuring
* that values are properly normalized with regards to white space.
*/
public class TestAttributeRead
extends BaseStreamTest
{
final String VALID_XML1
= "";
final String VALID_XML2
= "";
/**
* Test to make sure that quotes can be used in attribute values
* via entity expansion
*/
final String VALID_ATTRS_WITH_QUOTES
= "\n"
+ " ]>\n"
+ "";
public void testValidNsAttrsByName()
throws XMLStreamException
{
XMLStreamReader sr = getReader(VALID_XML1, true);
assertEquals(START_ELEMENT, sr.next());
assertEquals(1, sr.getNamespaceCount());
assertEquals(2, sr.getAttributeCount());
assertEquals("r&b", sr.getAttributeValue(null, "a"));
assertEquals("\"", sr.getAttributeValue("url", "b"));
// Shoulnd't allow using prefix instead of URI
String val = sr.getAttributeValue("a", "b");
assertNull("Should get null, not '"+val+"'", val);
val = sr.getAttributeValue("", "b");
assertNull("Should get null, not '"+val+"'", val);
assertEquals(END_ELEMENT, sr.next());
assertEquals(END_DOCUMENT, sr.next());
}
public void testValidNsAttrsByIndex()
throws XMLStreamException
{
XMLStreamReader sr = getReader(VALID_XML1, true);
assertEquals(START_ELEMENT, sr.next());
assertEquals(1, sr.getNamespaceCount());
assertEquals(2, sr.getAttributeCount());
/* Note: we can not assume on stream reader returning attributes
* in document order... most will do that, but it's not a
* strict StAX requirement.
*/
String ln1 = sr.getAttributeLocalName(0);
int index1 = 0;
int index2 = 1;
if (ln1.equals("a")) {
;
} else if (ln1.equals("b")) {
index1 = 1;
index2 = 0;
} else {
fail("Unexpected local name for attribute #0; expected either 'a' or 'b'; got '"+ln1+"'.");
}
assertEquals("a", sr.getAttributeLocalName(index1));
assertEquals("b", sr.getAttributeLocalName(index2));
assertEquals("r&b", sr.getAttributeValue(index1));
assertEquals("\"", sr.getAttributeValue(index2));
String prefix = sr.getAttributePrefix(index1);
if (prefix != null) {
fail("Expected null as prefix for attribute 'a', got '"+prefix+"'");
}
assertEquals("a", sr.getAttributePrefix(index2));
String ns = sr.getAttributeNamespace(index1);
assertNull("Unbound attribute should return null for XMLStreamReader.sr.getAttributeNamespace(int): got '"+ns+"'", ns);
assertEquals("url", sr.getAttributeNamespace(index2));
}
public void testValidNsAttrNsInfo()
throws XMLStreamException
{
XMLStreamReader sr = getReader
("",
true);
assertEquals(START_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
assertEquals(1, sr.getNamespaceCount());
assertEquals(1, sr.getAttributeCount());
assertNull(sr.getAttributePrefix(0));
assertNull(sr.getAttributeNamespace(0));
assertEquals("xyz", sr.getAttributeValue(0));
assertEquals(START_ELEMENT, sr.next());
assertEquals("leaf", sr.getLocalName());
assertEquals(0, sr.getNamespaceCount());
assertEquals(1, sr.getAttributeCount());
assertEquals("b", sr.getAttributePrefix(0));
assertEquals("http://foo", sr.getAttributeNamespace(0));
assertEquals("1", sr.getAttributeValue(0));
assertEquals(END_ELEMENT, sr.next());
assertEquals("leaf", sr.getLocalName());
assertEquals(END_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
assertEquals(END_DOCUMENT, sr.next());
}
public void testValidNonNsAttrs()
throws XMLStreamException
{
XMLStreamReader sr = getReader(VALID_XML1, false);
// Does the impl support non-ns mode?
if (sr == null) { // nope!
return;
}
assertEquals(START_ELEMENT, sr.next());
assertEquals(0, sr.getNamespaceCount());
assertEquals(3, sr.getAttributeCount());
assertEquals("r&b", sr.getAttributeValue(null, "a"));
assertEquals("\"", sr.getAttributeValue(null, "a:b"));
assertEquals(END_ELEMENT, sr.next());
assertEquals(END_DOCUMENT, sr.next());
}
public void testValidNonNsAttrsByIndex()
throws XMLStreamException
{
// = "";
XMLStreamReader sr = getReader(VALID_XML2, false);
// Does the impl support non-ns mode?
if (sr == null) { // nope!
return;
}
assertEquals(START_ELEMENT, sr.next());
assertEquals(0, sr.getNamespaceCount());
assertEquals(2, sr.getAttributeCount());
/* Note: we can not assume on stream reader returning attributes
* in document order... most will do that, but it's not a
* strict StAX requirement.
*/
String ln1 = sr.getAttributeLocalName(0);
int index1 = 0;
int index2 = 1;
if (ln1.equals("a:b")) {
;
} else if (ln1.equals("xmlns:a")) {
index1 = 1;
index2 = 0;
} else {
fail("Unexpected local name for attribute #0; expected either 'a:b' or 'xmlns:a'; got '"+ln1+"'.");
}
assertEquals("a:b", sr.getAttributeLocalName(index1));
assertEquals("xmlns:a", sr.getAttributeLocalName(index2));
assertEquals("\"", sr.getAttributeValue(index1));
assertEquals("url", sr.getAttributeValue(index2));
assertNull(sr.getAttributePrefix(index1));
assertNull(sr.getAttributePrefix(index2));
assertNull(sr.getAttributeNamespace(index1));
assertNull(sr.getAttributeNamespace(index2));
}
public void testQuotesViaEntities()
throws XMLStreamException
{
XMLInputFactory ifact = getNewInputFactory();
setNamespaceAware(ifact, false); // shouldn't matter
// These are needed to get entities read and expanded:
setSupportDTD(ifact, true);
setReplaceEntities(ifact, true);
XMLStreamReader sr = constructStreamReader(ifact,
VALID_ATTRS_WITH_QUOTES);
// Shouldn't get exceptions...
try {
streamThrough(sr);
} catch (XMLStreamException ex) {
fail("Failed to parse attributes with quotes expanded from entities: "+ex);
}
}
public void testInvalidAttrNames()
throws XMLStreamException
{
// First NS-aware, then non-NS:
streamThroughFailing(getReader("", true),
"invalid attribute name; can not start with '.'");
streamThroughFailing(getReader("", false),
"invalid attribute name; can not start with '.'");
streamThroughFailing(getReader("", false),
"invalid attribute name can not contain '?'");
streamThroughFailing(getReader("", true),
"invalid attribute name can not contain '?'");
}
public void testInvalidAttrValue()
throws XMLStreamException
{
for (int i = 0; i < 2; ++i) {
boolean ns = (i > 0);
// Invalid, '<' not allowed in attribute value
String XML = "";
streamThroughFailing(getReader(XML, ns),
"unquoted '<' in attribute value");
XML = "";
streamThroughFailing(getReader(XML, ns),
"missing value for attribute");
}
}
/**
* This tests that spaces are actually needed between attributes...
*/
public void testInvalidAttrSpaces()
throws XMLStreamException
{
for (int i = 0; i < 2; ++i) {
boolean ns = (i > 0);
String XML = "";
streamThroughFailing(getReader(XML, ns),
"missing space between attributes");
XML = "";
streamThroughFailing(getReader(XML, ns),
"missing space between attributes");
}
}
public void testInvalidNsAttrDup()
throws XMLStreamException
{
// Invalid; straight duplicate attrs:
String XML = "";
streamThroughFailing(getReader(XML, true),
"duplicate attributes");
// Invalid; sneakier duplicate attrs:
XML = "";
streamThroughFailing(getReader(XML, true),
"duplicate attributes (same URI, different prefix)");
}
public void testInvalidNonNsAttrDup()
throws XMLStreamException
{
// Invalid; duplicate attrs even without namespaces
String XML = "";
streamThroughFailing(getReader(XML, false),
"duplicate attributes");
// Valid when namespaces not enabled:
XML = "";
try {
XMLStreamReader sr = getReader(XML, false);
// Does the impl support non-ns mode?
if (sr == null) { // nope! shouldn't test...
return;
}
streamThrough(sr);
} catch (Exception e) {
fail("Didn't expect an exception when namespace support not enabled: "+e);
}
}
/*
////////////////////////////////////////
// Private methods, other
////////////////////////////////////////
*/
/**
* @return Stream reader constructed if initialization succeeded (all
* setting supported by the impl); null if some settings (namespace
* awareness) not supported.
*/
private XMLStreamReader getReader(String contents, boolean nsAware)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
if (!setNamespaceAware(f, nsAware)) {
return null;
}
setCoalescing(f, true); // shouldn't matter
setValidating(f, false);
return constructStreamReader(f, contents);
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/stream/TestXmlDecl.java 0000644 0001750 0001750 00000016175 10444554662 025047 0 ustar twerner twerner package org.codehaus.stax.test.stream;
import java.io.*;
import javax.xml.stream.*;
/**
* Unit test suite that tests handling of the xml declaration.
*/
public class TestXmlDecl
extends BaseStreamTest
{
public TestXmlDecl(String name) {
super(name);
}
final String VALID_XML1
= "";
final String VALID_XML_UTF8
= "";
/**
* Method that verifies properties that should be active when
* START_DOCUMENT is the current event (ie before iterating), ie.
* right after xml declaration has been read
*/
public void testProperties()
throws XMLStreamException
{
doTestProperties(false);
doTestProperties(true);
}
public void testValidDecl()
throws XMLStreamException, IOException
{
doTestValid(false);
doTestValid(true);
}
public void testValidStandaloneDecls()
throws XMLStreamException, IOException
{
String XML = "";
XMLStreamReader sr = getReader(XML, true);
assertEquals("1.0", sr.getVersion());
assertTrue("XMLStreamReader.standalonSet() should be true", sr.standaloneSet());
assertTrue("XMLStreamReader.isStandalone() should be true", sr.isStandalone());
XML = "";
sr = getReader(XML, true);
assertEquals("1.0", sr.getVersion());
assertTrue("XMLStreamReader.standalonSet() should be true", sr.standaloneSet());
assertFalse("XMLStreamReader.isStandalone() should be false", sr.isStandalone());
// And then all of it:
XML = "";
sr = getReader(XML, true);
assertEquals("1.0", sr.getVersion());
assertTrue("XMLStreamReader.standalonSet() should be true", sr.standaloneSet());
assertTrue("XMLStreamReader.isStandalone() should be true", sr.isStandalone());
assertEquals("US-ASCII", sr.getCharacterEncodingScheme());
}
public void testInvalidDecl()
throws XMLStreamException
{
doTestInvalid(false);
doTestInvalid(true);
}
/*
////////////////////////////////////////
// Private methods, shared test code
////////////////////////////////////////
*/
private void doTestProperties(boolean nsAware)
throws XMLStreamException
{
XMLStreamReader sr = getReader(VALID_XML1, nsAware);
assertEquals(START_DOCUMENT, sr.getEventType());
// Type info
assertEquals(false, sr.isStartElement());
assertEquals(false, sr.isEndElement());
assertEquals(false, sr.isCharacters());
assertEquals(false, sr.isWhiteSpace());
// indirect type info
assertEquals(false, sr.hasName());
assertEquals(false, sr.hasText());
/* Now... how about location and namespace context? Are they really
* guaranteed to exist at this point? Since API doesn't indicate
* otherwise, let's assume this is the case, for now.
*/
assertNotNull(sr.getLocation());
if (nsAware) {
assertNotNull(sr.getNamespaceContext());
}
// And then let's check methods that should throw specific exception
for (int i = 0; i < 8; ++i) {
String method = "";
try {
Object result = null;
switch (i) {
case 0:
method = "getName";
result = sr.getName();
break;
case 1:
method = "getPrefix";
result = sr.getPrefix();
break;
case 2:
method = "getLocalName";
result = sr.getLocalName();
break;
case 3:
method = "getNamespaceURI";
result = sr.getNamespaceURI();
break;
case 4:
method = "getNamespaceCount";
result = new Integer(sr.getNamespaceCount());
break;
case 5:
method = "getAttributeCount";
result = new Integer(sr.getAttributeCount());
break;
case 6:
method = "getPITarget";
result = sr.getPITarget();
break;
case 7:
method = "getPIData";
result = sr.getPIData();
break;
}
fail("Expected IllegalStateException, when calling "
+method+"() for XML declaration (START_DOCUMENT)");
} catch (IllegalStateException iae) {
; // good
}
}
}
private void doTestValid(boolean nsAware)
throws XMLStreamException, IOException
{
XMLStreamReader sr = getReader(VALID_XML1, nsAware);
/* First, let's ensure that version is ok, and whether
* stand-alone pseudo-attr was set:
*/
assertEquals("1.0", sr.getVersion());
assertFalse(sr.standaloneSet());
// Then, encoding passed via factory method:
sr = getUTF8StreamReader(VALID_XML1, nsAware);
assertEquals("UTF-8", sr.getEncoding());
// Then, automatic detection of encoding:
sr = getReader(VALID_XML_UTF8, nsAware);
assertEquals("1.0", sr.getVersion());
assertEquals("UTF-8", sr.getCharacterEncodingScheme());
}
private void doTestInvalid(boolean nsAware)
throws XMLStreamException
{
String XML = "";
streamThroughFailing(getFactory(nsAware), XML,
"invalid XML declaration (missing version)");
XML = "";
streamThroughFailing(getFactory(nsAware), XML,
"invalid XML declaration (mismatch of quotes)");
}
/*
////////////////////////////////////////
// Private methods, other
////////////////////////////////////////
*/
private XMLInputFactory getFactory(boolean nsAware)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setCoalescing(f, false); // shouldn't matter
setNamespaceAware(f, nsAware);
setValidating(f, false);
return f;
}
private XMLStreamReader getReader(String contents, boolean nsAware)
throws XMLStreamException
{
return constructStreamReader(getFactory(nsAware), contents);
}
private XMLStreamReader getUTF8StreamReader(String contents, boolean nsAware)
throws XMLStreamException, UnsupportedEncodingException
{
XMLInputFactory f = getInputFactory();
setCoalescing(f, false); // shouldn't matter
setNamespaceAware(f, nsAware);
setValidating(f, false);
InputStream in = new ByteArrayInputStream(contents.getBytes("UTF-8"));
return f.createXMLStreamReader(in, "UTF-8");
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/stream/TestCDataRead.java 0000644 0001750 0001750 00000013003 10444554662 025252 0 ustar twerner twerner package org.codehaus.stax.test.stream;
import javax.xml.stream.*;
/**
* Unit test suite that tests that the stream reader does in fact
* coalesce adjacent text/CDATA segments when told to do so.
*/
public class TestCDataRead
extends BaseStreamTest
{
final static String CDATA1;
final static String CDATA2;
static {
StringBuffer sb1 = new StringBuffer(8000);
StringBuffer sb2 = new StringBuffer(8000);
sb1.append("...");
sb2.append("\n \n\n ");
/* Let's add enough stuff to probably cause segmentation...
*/
for (int i = 0; i < 200; ++i) {
String txt = "Round #"+i+"; & that's fun: &x"+i+"; <> %xx; &ent <<< %%% ]> ";
sb1.append(txt);
sb1.append(" ");
sb2.append("\n");
sb2.append(txt);
}
CDATA1 = sb1.toString();
CDATA2 = sb2.toString();
}
final static String CDATA3 = " ]] ";
final static String EXP_CDATA = CDATA1 + CDATA2 + CDATA3;
final static String VALID_XML =
""
+""
+""
+""
+""
+"";
public TestCDataRead(String name) {
super(name);
}
public void testCDataCoalescing()
throws XMLStreamException
{
XMLStreamReader sr = getReader(VALID_XML, true);
assertTokenType(START_ELEMENT, sr.next());
/* In coalescing mode, all CDATA are reported as CHARACTERS
*/
assertTokenType(CHARACTERS, sr.next());
String act = getAndVerifyText(sr);
assertEquals(EXP_CDATA, act);
assertTokenType(END_ELEMENT, sr.next());
}
public void testCDataNonCoalescing()
throws XMLStreamException
{
XMLStreamReader sr = getReader(VALID_XML, false);
assertTokenType(START_ELEMENT, sr.next());
int type = sr.next();
/* 07-Dec-2004, TSa: StAX specs actually allow returning
* CHARACTERS too...
*/
if (type != CHARACTERS) {
assertEquals("Unexpected token type ("
+tokenTypeDesc(type)
+") returned; expected CDATA or CHARACTERS",
CDATA, type);
}
StringBuffer sb = new StringBuffer(16000);
do {
sb.append(getAndVerifyText(sr));
type = sr.next();
} while (type == CDATA || type == CHARACTERS);
assertEquals(EXP_CDATA, sb.toString());
assertTokenType(END_ELEMENT, sr.getEventType());
}
public void testInvalidCData()
throws XMLStreamException
{
String XML = "";
String MSG = "unfinished CDATA section";
streamThroughFailing(getReader(XML, false), MSG);
streamThroughFailing(getReader(XML, true), MSG);
XML = " ";
MSG = "malformed CDATA section";
streamThroughFailing(getReader(XML, false), MSG);
streamThroughFailing(getReader(XML, true), MSG);
XML = " ";
streamThroughFailing(getReader(XML, false), MSG);
streamThroughFailing(getReader(XML, true), MSG);
XML = " ";
streamThroughFailing(getReader(XML, false), MSG);
streamThroughFailing(getReader(XML, true), MSG);
}
/**
* This unit test verifies that nested CData sections cause
* an error. It is related to another test, which just checks
* that ]]> (with no quoting) is illegal, but parsers may deal
* with them differently.
*
* Note: this is directly based on XMLTest/SAXTest #735.
*/
public void testInvalidNestedCData()
throws XMLStreamException
{
String XML = "\n\n"
+"\n]]>\n";
for (int i = 0; i < 2; ++i) {
boolean coal = (i > 0);
XMLStreamReader sr = getReader(XML, coal);
assertTokenType(START_ELEMENT, sr.next());
// Ok, now should get an exception...
StringBuffer sb = new StringBuffer();
int type;
try {
while (true) {
type = sr.next();
if (type != CDATA && type != CHARACTERS) {
break;
}
sb.append(getAndVerifyText(sr));
}
} catch (XMLStreamException sex) {
// good
continue;
} catch (RuntimeException sex) {
/* Hmmh. Some implementations may throw a runtime exception,
* if things are lazily parsed (for example, Woodstox)
*/
// acceptable too
continue;
}
fail("Expected an exception for nested CDATA section (coalescing: "+coal+"); instead got text \""+sb.toString()+"\" (next event "+tokenTypeDesc(type)+")");
}
}
/*
////////////////////////////////////////
// Private methods, other
////////////////////////////////////////
*/
private XMLStreamReader getReader(String contents, boolean coalescing)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setCoalescing(f, coalescing);
setReplaceEntities(f, true);
setValidating(f, false);
return constructStreamReader(f, contents);
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/vstream/ 0000755 0001750 0001750 00000000000 10444554662 022170 5 ustar twerner twerner stax-1.2.0.orig/src/org/codehaus/stax/test/vstream/TestEnumAttrRead.java 0000644 0001750 0001750 00000010233 10444554662 026225 0 ustar twerner twerner package org.codehaus.stax.test.vstream;
import javax.xml.stream.*;
/**
* Unit test suite that tests handling of attributes that are declared
* by DTD to be of type NOTATION.
*/
public class TestEnumAttrRead
extends BaseVStreamTest
{
public TestEnumAttrRead(String name) {
super(name);
}
/*
///////////////////////////////////////
// Test cases
///////////////////////////////////////
*/
public void testValidAttrDecl()
throws XMLStreamException
{
// Ok, just a simple declaration...
String XML = "\n"
+"\n"
+"]>\n";
streamThrough(getValidatingReader(XML, true));
}
public void testValidAttrDecl2()
throws XMLStreamException
{
/* Following should be ok, only problematic if DTD parser is
* either trying to match SGML comments, or otherwise unhappy
* about hyphen starting an NMTOKEN.
*/
String XML = "\n"
+"\n"
+"]>\n";
streamThrough(getReader(XML));
}
public void testInvalidAttrDecl()
throws XMLStreamException
{
// Duplicates are not allowed
String XML = "\n"
+"\n"
+"]>\n";
streamThroughFailing(getValidatingReader(XML, true),
"duplicate enumeration in attribute declaration");
}
public void testValidAttrUse()
throws XMLStreamException
{
// Ok, just a simple declaration...
String XML = "\n"
+"\n"
+"]>";
XMLStreamReader sr = getValidatingReader(XML, true);
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals(1, sr.getAttributeCount());
assertEquals("attr2", sr.getAttributeLocalName(0));
assertEquals("enum2", sr.getAttributeValue(0));
}
/**
* Unit test that verifies that values of attributes of type ID
* will get properly normalized.
*/
public void testEnumAttrNormalization()
throws XMLStreamException
{
String XML = "\n"
+"\n"
+"]>"
+""
+""
+""
+"";
;
XMLStreamReader sr = getValidatingReader(XML);
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals(1, sr.getAttributeCount());
assertEquals("enum2", sr.getAttributeValue(0));
assertTokenType(START_ELEMENT, sr.next());
assertEquals(1, sr.getAttributeCount());
assertEquals("enum", sr.getAttributeValue(0));
assertTokenType(END_ELEMENT, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals(1, sr.getAttributeCount());
assertEquals("last", sr.getAttributeValue(0));
assertTokenType(END_ELEMENT, sr.next());
assertTokenType(END_ELEMENT, sr.next());
}
/*
////////////////////////////////////////
// Private methods
////////////////////////////////////////
*/
private XMLStreamReader getReader(String contents)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setCoalescing(f, false); // shouldn't really matter
//setNamespaceAware(f, nsAware);
setSupportDTD(f, true);
// Let's make sure DTD is really parsed?
setValidating(f, true);
return constructStreamReader(f, contents);
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/vstream/TestExternalSubset.java 0000644 0001750 0001750 00000005222 10444554662 026644 0 ustar twerner twerner package org.codehaus.stax.test.vstream;
import javax.xml.stream.*;
import org.codehaus.stax.test.SimpleResolver;
/**
* Unit test suite that verifies that external subsets can be used, and
* also tests some of features only legal in there (include/exclude,
* parameter entities within declarations)
*
* @author Tatu Saloranta
*/
public class TestExternalSubset
extends BaseVStreamTest
{
public void testSimpleValidExternalSubset()
throws XMLStreamException
{
String XML = ""
+"text";
String EXT_ENTITY_VALUE = "just testing";
String EXT_SUBSET =
"\n"
+"";
XMLStreamReader sr = getReader(XML, true,
new SimpleResolver(EXT_SUBSET));
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
assertTokenType(CHARACTERS, sr.next());
assertEquals("text", getAndVerifyText(sr));
assertTokenType(END_ELEMENT, sr.next());
sr.close();
}
public void testEntityInExternalSubset()
throws XMLStreamException
{
String XML = ""
+"&extEnt;";
String EXT_ENTITY_VALUE = "just testing";
String EXT_SUBSET =
"\n"
+"\n";
XMLStreamReader sr = getReader(XML, true,
new SimpleResolver(EXT_SUBSET));
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals("root", sr.getLocalName());
assertTokenType(CHARACTERS, sr.next());
assertEquals(EXT_ENTITY_VALUE, getAndVerifyText(sr));
assertTokenType(END_ELEMENT, sr.next());
sr.close();
}
/*
////////////////////////////////////////
// Private methods, other
////////////////////////////////////////
*/
private XMLStreamReader getReader(String contents, boolean nsAware,
XMLResolver resolver)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setCoalescing(f, false); // shouldn't really matter
setNamespaceAware(f, nsAware);
setSupportDTD(f, true);
setValidating(f, true);
// This shouldn't be required but let's play it safe:
setSupportExternalEntities(f, true);
setResolver(f, resolver);
return constructStreamReader(f, contents);
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/vstream/TestNmTokenAttrRead.java 0000644 0001750 0001750 00000011506 10444554662 026700 0 ustar twerner twerner package org.codehaus.stax.test.vstream;
import javax.xml.stream.*;
/**
* Unit test suite that tests handling of attributes that are declared
* by DTD to be of type NMTOKEN or NMTOKENS; such information is only
* guranteed to be available in validation mode.
*/
public class TestNmTokenAttrRead
extends BaseVStreamTest
{
public TestNmTokenAttrRead(String name) {
super(name);
}
/*
///////////////////////////////////////
// Test cases
///////////////////////////////////////
*/
/**
* Test case that verifies behaviour of valid NMTOKEN/NMTOKENS
* attribute declarations.
*/
public void testValidNmTokenAttrDecl()
throws XMLStreamException
{
// Following should be ok
String XML = "\n"
+"\n"
+"]>\n";
streamThrough(getValidatingReader(XML));
}
/**
* Test case that verifies behaviour of invalid NMTOKEN/NMTOKENS
* attribute declarations.
*/
public void testInvalidNmTokenAttrDecl()
throws XMLStreamException
{
// ??? Are there any such cases?
}
public void testValidNmTokenAttrUse()
throws XMLStreamException
{
String XML = "\n"
+"\n"
+"\n"
+"]>\n ";
streamThrough(getValidatingReader(XML));
}
public void testInvalidNmTokenAttrUse()
throws XMLStreamException
{
// Error: invalid NMTOKEN, ? not valid
String XML = "\n"
+"\n"
+"]>\n";
streamThroughFailing(getValidatingReader(XML),
"invalid char ('?') in NMTOKEN");
// Error: invalid NMTOKENS, / not valid
XML = "\n"
+"\n"
+"]>\n";
streamThroughFailing(getValidatingReader(XML),
"invalid char ('/') in NMTOKENS");
}
/**
* Unit test that verifies that values of attributes of type NMTOKEN and
* NMTOKENS will get properly normalized.
*/
public void testNmTokenAttrNormalization()
throws XMLStreamException
{
String XML = "\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"]>"
+""
+""
+""
+""
+"";
;
XMLStreamReader sr = getValidatingReader(XML);
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals("elem", sr.getLocalName());
assertEquals(1, sr.getAttributeCount());
assertEquals("nmToken", sr.getAttributeValue(0));
assertTokenType(START_ELEMENT, sr.next());
assertEquals(1, sr.getAttributeCount());
assertEquals("name", sr.getAttributeValue(0));
assertTokenType(END_ELEMENT, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals(1, sr.getAttributeCount());
assertEquals("first_name second last", sr.getAttributeValue(0));
assertTokenType(END_ELEMENT, sr.next());
// then the defaults
assertTokenType(START_ELEMENT, sr.next());
assertEquals("elem2", sr.getLocalName());
assertEquals(1, sr.getAttributeCount());
assertEquals("name", sr.getAttributeLocalName(0));
assertEquals("somename", sr.getAttributeValue(0));
assertTokenType(END_ELEMENT, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals("elem3", sr.getLocalName());
assertEquals(1, sr.getAttributeCount());
assertEquals("names", sr.getAttributeLocalName(0));
assertEquals("name1 name2 name3", sr.getAttributeValue(0));
assertTokenType(END_ELEMENT, sr.next());
assertTokenType(END_ELEMENT, sr.next());
}
/*
////////////////////////////////////////
// Private methods
////////////////////////////////////////
*/
}
stax-1.2.0.orig/src/org/codehaus/stax/test/vstream/TestSubsetCombination.java 0000644 0001750 0001750 00000006315 10444554662 027330 0 ustar twerner twerner package org.codehaus.stax.test.vstream;
import javax.xml.stream.*;
import org.codehaus.stax.test.SimpleResolver;
/**
* Unit test suite that tests how implementation handles combining of
* internal and external DTD subsets.
*
* @author Tatu Saloranta
*/
public class TestSubsetCombination
extends BaseVStreamTest
{
/**
* This unit test checks that a DTD definition that is evenly split
* between subsets will be properly combined, and results in a usable
* definition for validation.
*/
public void testValidSubsets()
throws XMLStreamException
{
// Note: need to resolve using a custom resolver
String XML =
"\n"
+"\n"
+"\n"
+"]> Test entities: &ent1;, &ent2;"
+"..."
+"";
String EXT_DTD =
"\n"
+"\n"
+"\n"
;
streamThrough(getReader(XML, true, EXT_DTD));
// Let's also test that non-ns works, just in case it's different
streamThrough(getReader(XML, false, EXT_DTD));
}
/**
* This unit test checks that the internal subset has precedence
* for attribute definitions -- it's ok to declare attributes multiple
* times, but the first one sticks, and internal subset is considered
* to come before external subset
*/
public void testAttributePrecedence()
throws XMLStreamException
{
String XML =
"\n"
+"\n"
+"\n"
+"]>"
;
String EXT_DTD =
"\n"
+"\n"
;
XMLStreamReader sr = getReader(XML, true, EXT_DTD);
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals(1, sr.getAttributeCount());
assertEquals("attr2", sr.getAttributeLocalName(0));
assertEquals("intValue", sr.getAttributeValue(0));
assertFalse(sr.isAttributeSpecified(0));
}
/*
////////////////////////////////////////
// Non-test methods
////////////////////////////////////////
*/
private XMLStreamReader getReader(String contents, boolean nsAware,
String extSubset)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setNamespaceAware(f, nsAware);
setSupportDTD(f, true);
setCoalescing(f, false);
setReplaceEntities(f, true);
setValidating(f, true);
if (extSubset != null) {
setResolver(f, new SimpleResolver(extSubset));
} else {
setResolver(f, null);
}
return constructStreamReader(f, contents);
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/vstream/TestEntityAttrRead.java 0000644 0001750 0001750 00000016051 10444554662 026601 0 ustar twerner twerner package org.codehaus.stax.test.vstream;
import javax.xml.stream.*;
/**
* Unit test suite that tests handling of attributes that are declared
* by DTD to be of type NOTATION.
*/
public class TestEntityAttrRead
extends BaseVStreamTest
{
public TestEntityAttrRead(String name) {
super(name);
}
/*
///////////////////////////////////////
// Test cases
///////////////////////////////////////
*/
public void testValidEntityAttrDecl()
throws XMLStreamException
{
// Following should be ok; notations have been declared ok
String XML = "\n"
+"\n"
+"\n"
+"\n"
+"]>\n";
streamThrough(getValidatingReader(XML));
// Likewise for default values
XML = "\n"
+"\n"
+"\n"
+"\n"
+"]>\n";
streamThrough(getValidatingReader(XML));
}
public void testValidEntitiesAttrDecl()
throws XMLStreamException
{
// Following should be ok; notations have been declared ok
String XML = "\n"
+"\n"
+"\n"
+"\n"
+"]>\n";
streamThrough(getValidatingReader(XML));
// and for default values
XML = "\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"]>\n";
streamThrough(getValidatingReader(XML));
}
public void testInvalidEntityAttrDecl()
throws XMLStreamException
{
// First, let's check that undeclared notation throws an exception
String XML = "\n"
+"\n"
+"\n"
+"\n"
+"]>\n";
streamThroughFailing(getValidatingReader(XML),
"undeclared notation for ENTITY attribute");
// Similarly, undeclared entity via default value
XML = "\n"
+"\n"
+"\n"
+"\n"
+"]>\n";
streamThroughFailing(getValidatingReader(XML),
"undeclared entity for ENTITY default value");
}
public void testInvalidEntitiesAttrDecl()
throws XMLStreamException
{
// First, let's check that undeclared notation throws an exception
String XML = "\n"
+"\n"
+"\n"
+"\n"
+"]>\n";
streamThroughFailing(getValidatingReader(XML),
"undeclared notation for ENTITIES attribute");
// Similarly, undeclared entity via default value
XML = "\n"
+"\n"
+"\n"
+"\n"
+"]>\n";
streamThroughFailing(getValidatingReader(XML),
"undeclared entity for ENTITIES default value");
XML = "\n"
+"\n"
+"\n"
+"\n"
+"]>\n";
streamThroughFailing(getValidatingReader(XML),
"undeclared entity for ENTITIES default value");
}
public void testValidEntityAttrUse()
throws XMLStreamException
{
// Following should be ok; notations have been declared ok
String XML = "\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"]>";
XMLStreamReader sr = getValidatingReader(XML);
// Let's ensure white space normalization too:
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals(1, sr.getAttributeCount());
assertEquals("unpEnt2", sr.getAttributeValue(0));
}
public void testValidEntitiesAttrUse()
throws XMLStreamException
{
// Following should be ok; notations have been declared ok
String XML = "\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"]>";
streamThrough(getValidatingReader(XML));
XMLStreamReader sr = getValidatingReader(XML);
// Let's ensure white space normalization too:
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals(1, sr.getAttributeCount());
assertEquals("unpEnt2 unpEnt3 unpEnt1", sr.getAttributeValue(0));
}
/*
public void testInvalidEntityAttrUse()
throws XMLStreamException
{
}
*/
/*
public void testInvalidEntitiesAttrUse()
throws XMLStreamException
{
}
*/
}
stax-1.2.0.orig/src/org/codehaus/stax/test/vstream/TestAttrTypes.java 0000644 0001750 0001750 00000006672 10444554662 025645 0 ustar twerner twerner package org.codehaus.stax.test.vstream;
import java.util.HashMap;
import javax.xml.stream.*;
/**
* Unit test suite that tests that attribute type information returned
* for all recognized types is as expected
*/
public class TestAttrTypes
extends BaseVStreamTest
{
public TestAttrTypes(String name) {
super(name);
}
/*
///////////////////////////////////////
// Test cases
///////////////////////////////////////
*/
public void testAttrTypes()
throws XMLStreamException
{
// Let's verify we get default value
String XML = "\n"
+"\n"
+"]>"
+"";
XMLStreamReader sr = getValidatingReader(XML, true);
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
int count = sr.getAttributeCount();
assertEquals(7, count);
HashMap seen = new HashMap();
for (int i = 0; i < count; ++i) {
String name = sr.getAttributeLocalName(i);
String value = sr.getAttributeValue(i);
String old = (String) seen.put(name, value);
if (old != null) {
fail("Duplicate attribute '"+name+"': previous value: '"+value+"'");
}
String type = sr.getAttributeType(i);
if (name.equals("attrCData")) {
assertEquals("CDATA", type);
} else if (name.equals("attrId")) {
assertEquals("ID", type);
} else if (name.equals("attrIdref")) {
assertEquals("IDREF", type);
} else if (name.equals("attrIdrefs")) {
assertEquals("IDREFS", type);
} else if (name.equals("attrEnum")) {
/* 25-Apr-2005, TSa: Not quite sure what would be the
* "official" name for the enumerated type?
*/
assertEquals("ENUMERATED", type);
} else if (name.equals("attrName")) {
assertEquals("NMTOKEN", type);
} else if (name.equals("attrNames")) {
assertEquals("NMTOKENS", type);
} else {
fail("Unexpected attribute '"+name+"'");
}
}
}
/*
////////////////////////////////////////
// Private methods
////////////////////////////////////////
*/
private XMLStreamReader getReader(String contents)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setCoalescing(f, false); // shouldn't really matter
//setNamespaceAware(f, nsAware);
setSupportDTD(f, true);
// Let's make sure DTD is really parsed?
setValidating(f, true);
return constructStreamReader(f, contents);
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/vstream/BaseVStreamTest.java 0000644 0001750 0001750 00000002514 10444554662 026051 0 ustar twerner twerner package org.codehaus.stax.test.vstream;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.codehaus.stax.test.stream.BaseStreamTest;
/**
* Base class for all StaxTest unit tests that test validation-dependant
* parts of stream (cursor) API functionality.
*
* @author Tatu Saloranta
*/
public class BaseVStreamTest
extends BaseStreamTest
{
protected BaseVStreamTest() { super(); }
protected BaseVStreamTest(String name) {
super(name);
}
protected XMLStreamReader getValidatingReader(String contents)
throws XMLStreamException
{
return getValidatingReader(contents, true);
}
protected XMLStreamReader getValidatingReader(String contents, boolean nsAware)
throws XMLStreamException
{
XMLInputFactory f = getValidatingFactory(nsAware);
return constructStreamReader(f, contents);
}
protected XMLInputFactory getValidatingFactory(boolean nsAware)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setCoalescing(f, false); // shouldn't really matter
setNamespaceAware(f, nsAware);
setSupportDTD(f, true);
// Let's make sure DTD is really parsed?
setValidating(f, true);
return f;
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/vstream/TestParamEntities.java 0000644 0001750 0001750 00000003206 10444554662 026441 0 ustar twerner twerner package org.codehaus.stax.test.vstream;
import java.io.StringReader;
import java.util.*;
import javax.xml.stream.*;
import org.codehaus.stax.test.SimpleResolver;
/**
* Unit test suite that tests various aspects of parameter entity resolution
* in the external DTD subset.
*
* @author Tatu Saloranta
*/
public class TestParamEntities
extends BaseVStreamTest
{
/**
* Test similar to one in xmltest (valid/not-sa/003.xml, specifically)
*/
public void testExternalParamDeclViaPE()
throws XMLStreamException
{
HashMap m = new HashMap();
m.put("ent1", "\n"
+"\n"
+"");
m.put("ent2", "");
// Following should be ok; notations have been declared ok
String XML = "";
XMLInputFactory f = getValidatingFactory(true);
setResolver(f, new MyResolver(m));
XMLStreamReader sr = f.createXMLStreamReader(new StringReader(XML));
streamThrough(getValidatingReader(XML));
}
final static class MyResolver
implements XMLResolver
{
final Map mEntities;
public MyResolver(Map entities) {
mEntities = entities;
}
public Object resolveEntity(String publicID, String systemID, String baseURI, String namespace)
{
String str = (String) mEntities.get(publicID);
if (str == null) {
str = (String) mEntities.get(systemID);
}
return (str == null) ? null : new StringReader(str);
}
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/vstream/TestIncludes.java 0000644 0001750 0001750 00000010305 10444554662 025440 0 ustar twerner twerner package org.codehaus.stax.test.vstream;
import java.io.StringReader;
import javax.xml.stream.*;
import org.codehaus.stax.test.SimpleResolver;
/**
* Simple unit tests to check and verify that DTD handler properly deals
* with conditional sections.
*
* @author Tatu Saloranta
*/
public class TestIncludes
extends BaseVStreamTest
{
public void testSimpleInclude()
throws XMLStreamException
{
final String XML =
"&myent;";
;
final String EXT_DTD =
"\n"
+""
+"]]>\n"
;
XMLInputFactory f = getValidatingFactory(true);
setResolver(f, new SimpleResolver(EXT_DTD));
XMLStreamReader sr = f.createXMLStreamReader(new StringReader(XML));
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertTokenType(CHARACTERS, sr.next());
assertEquals("value", getAndVerifyText(sr));
assertTokenType(END_ELEMENT, sr.next());
}
public void testSimpleIgnore()
throws XMLStreamException
{
final String XML =
"&myent;";
;
/* Let's add something that'd be invalid in there...
*/
final String EXT_DTD =
"\n"
+" "
+"]]>\n"
+""
;
XMLInputFactory f = getValidatingFactory(true);
setResolver(f, new SimpleResolver(EXT_DTD));
XMLStreamReader sr = f.createXMLStreamReader(new StringReader(XML));
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertTokenType(CHARACTERS, sr.next());
assertEquals("value", getAndVerifyText(sr));
assertTokenType(END_ELEMENT, sr.next());
}
/**
* Conditional sections can NOT be used in the internal subset --
* let's quickly verify this.
*/
public void testFailingInIntSubset()
throws XMLStreamException
{
// first inclusion:
String XML =
""
+"]]>"
+"]>\n"
;
streamThroughFailing(getValidatingReader(XML),
"Condition INCLUDE not allowed in internal DTD subset");
// Then IGNORE:
XML =
""
+"]]>"
+" "
+"]>\n"
;
streamThroughFailing(getValidatingReader(XML),
"Condition INCLUDE not allowed in internal DTD subset");
}
/**
* Ok, and then we better consider parameter entity expanded variations
* of INCLUDE/IGNORE directives (see example under XML 1.0.3 section 3.4
* for a sample)
*/
public void testPEIncludeAndIgnore()
throws XMLStreamException
{
final String XML = "&myent;";
;
final String EXT_DTD =
"\n"
+"\n"
+"\n"
+"]]>\n"
+"\n"
+"]]>\n"
+"\n"
;
XMLInputFactory f = getValidatingFactory(true);
setResolver(f, new SimpleResolver(EXT_DTD));
XMLStreamReader sr = f.createXMLStreamReader(new StringReader(XML));
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertTokenType(CHARACTERS, sr.next());
String text = getAndVerifyText(sr);
if (!text.equals("include")) {
fail("Expected 'myent' to expand to 'include', not '"+text+"'");
}
assertTokenType(END_ELEMENT, sr.next());
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/vstream/TestStructuralValidation.java 0000644 0001750 0001750 00000040211 10444554662 030054 0 ustar twerner twerner package org.codehaus.stax.test.vstream;
import javax.xml.stream.*;
/**
* Unit test suite that tests structural validation using DTD.
*/
public class TestStructuralValidation
extends BaseVStreamTest
{
public TestStructuralValidation(String name) {
super(name);
// Uncomment to see if we get exceptions we should be getting:
//PRINT_EXP_EXCEPTION = true;
}
public void testValidStructure()
throws XMLStreamException
{
for (int i = 0; i < 2; ++i) {
boolean nsAware = (i > 0);
String XML = "\n"
+"\n"
+"\n"
+"]>\n Text ";
streamThrough(getReader(XML, nsAware));
}
}
public void testValidStructure2()
throws XMLStreamException
{
for (int i = 0; i < 2; ++i) {
boolean nsAware = (i > 0);
String XML = "\n"
+"\n"
+"\n"
+"]>\n text";
streamThrough(getReader(XML, nsAware));
// Ok, as leaf is optional...
XML = "\n"
+"\n"
+"]>\n";
streamThrough(getReader(XML, nsAware));
XML = "\n"
+"\n"
+"]>\n text & and more";
streamThrough(getReader(XML, nsAware));
}
}
public void testValidSimpleSeqStructure()
throws XMLStreamException
{
for (int i = 0; i < 2; ++i) {
boolean nsAware = (i > 0);
String XML = "\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"]>\n"
+"\n"
+""
+"";
streamThrough(getReader(XML, nsAware));
}
}
public void testInvalidSimpleSeqStructure()
throws XMLStreamException
{
for (int i = 0; i < 2; ++i) {
boolean nsAware = (i > 0);
String XML = "\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"]>\n"
+"\n"
+""
+"";
streamThroughFailing(getReader(XML, nsAware),
"invalid simple content sequence: missing 'a3' element");
XML = "\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"]>\n"
+"\n"
+""
+"";
streamThroughFailing(getReader(XML, nsAware),
"invalid simple content sequence: missing 'a4' element");
}
}
public void testValidSimpleChoiceStructure()
throws XMLStreamException
{
for (int i = 0; i < 2; ++i) {
boolean nsAware = (i > 0);
String XML = "\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"]>\n"
+"\n"
+""
+"";
streamThrough(getReader(XML, nsAware));
}
}
public void testInvalidSimpleChoiceStructure()
throws XMLStreamException
{
for (int i = 0; i < 2; ++i) {
boolean nsAware = (i > 0);
String XML = "\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"]>\n"
+"\n"
+"";
streamThroughFailing(getReader(XML, nsAware),
"invalid choice content sequence: no children for root");
XML = "\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"]>\n"
+""
+"";
streamThroughFailing(getReader(XML, nsAware),
"invalid choice content sequence: more than one child");
XML = "\n"
+"\n"
+"\n"
+"\n"
+"]>\n"
+""
+"";
streamThroughFailing(getReader(XML, nsAware),
"invalid choice content sequence: c1 not one of legal children for root");
}
}
public void testValidFullChoiceStructure()
throws XMLStreamException
{
for (int i = 0; i < 2; ++i) {
boolean nsAware = (i > 0);
String XML = "\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"]>\n"
+"\n"
+""
+"";
streamThrough(getReader(XML, nsAware));
}
}
public void testValidMixed()
throws XMLStreamException
{
for (int i = 0; i < 2; ++i) {
boolean nsAware = (i > 0);
String XML = "\n"
+"\n"
+"]>Text ";
streamThrough(getReader(XML, nsAware));
}
}
public void testInvalidWrongRoot()
throws XMLStreamException
{
for (int i = 0; i < 2; ++i) {
boolean nsAware = (i > 0);
String XML = " ";
streamThroughFailing(getReader(XML, nsAware), "wrong root element");
}
}
public void testInvalidMixed()
throws XMLStreamException
{
for (int i = 0; i < 2; ++i) {
boolean nsAware = (i > 0);
String XML = "\n"
+"\n"
+"]>Text ";
streamThroughFailing(getReader(XML, nsAware),
"invalid mixed content");
// same, but after a child elem...
XML = "\n"
+"\n"
+"]> x ";
streamThroughFailing(getReader(XML, nsAware),
"invalid mixed content");
}
}
public void testInvalidStructureRoot()
throws XMLStreamException
{
for (int i = 0; i < 2; ++i) {
boolean nsAware = (i > 0);
// First, wrong root element
String XML = "\n"
+"\n"
+"\n"
+"]>\n";
streamThroughFailing(getReader(XML, nsAware),
"wrong root element");
// Then undeclared (root) element
XML = "\n"
+"]>\n ";
streamThroughFailing(getReader(XML, nsAware),
"undeclared element");
// Then one wrong element content for root
XML = "\n"
+"\n"
+"\n"
+"]>\n ";
streamThroughFailing(getReader(XML, nsAware),
"wrong element content (expected branch+, end; got nothing) for root");
}
}
public void testInvalidStructure()
throws XMLStreamException
{
for (int i = 0; i < 2; ++i) {
boolean nsAware = (i > 0);
// And then just wrong ordering of child elements
String XML = "\n"
+"\n"
+"\n"
+"]>\n ";
streamThroughFailing(getReader(XML, nsAware),
"wrong element content (ordering) for root");
XML = "\n"
+"\n"
+"\n"
+"]>\n xyz";
streamThroughFailing(getReader(XML, nsAware),
"wrong element content (missing 'end' element) for root");
XML = "\n"
+"\n"
+"\n"
+"]>\n ";
streamThroughFailing(getReader(XML, nsAware),
"missing children for root");
XML = "\n"
+"\n"
+"\n"
+"\n"
+"]>\n ";
streamThroughFailing(getReader(XML, nsAware),
"wrong child element for branch");
}
}
final static String COMPLEX_DTD =
"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
;
public void testValidStructureComplex()
throws XMLStreamException
{
for (int i = 0; i < 2; ++i) {
boolean nsAware = (i > 0);
// And then just wrong ordering of child elements
String XML = ""
+""
+" "
+" "
+" "
+" "
+""
;
streamThrough(getReader(XML, nsAware));
}
}
public void testInvalidStructureComplex()
throws XMLStreamException
{
for (int i = 0; i < 2; ++i) {
boolean nsAware = (i > 0);
// And then just wrong ordering of child elements
String XML = ""
+""
+" "
+" "
// b is missing:
+" "
+" "
+""
;
streamThroughFailing(getReader(XML, nsAware),
"wrong element structure; missing element ");
}
}
/**
* Unit test that checks that it's illegal to add any content (including
* comment, processing instructions or white space) within an element that has
* content declaration of EMPTY.
*/
public void testInvalidEmpty()
throws XMLStreamException
{
for (int i = 0; i < 2; ++i) {
boolean nsAware = (i > 0);
String XML = "\n"
+"]>";
streamThroughFailing(getReader(XML, nsAware),
"comment within element that has EMPTY content type declaration");
XML = "\n"
+"]>";
streamThroughFailing(getReader(XML, nsAware),
"processing instruction within element that has EMPTY content type declaration");
XML = "\n"
+"]> ";
streamThroughFailing(getReader(XML, nsAware),
"white space within element that has EMPTY content type declaration");
XML = "\n"
+"\n"
+"]>";
streamThroughFailing(getReader(XML, nsAware),
"element within element that has EMPTY content type declaration");
}
}
public void testValidAny()
throws XMLStreamException
{
for (int i = 0; i < 2; ++i) {
boolean nsAware = (i > 0);
String XML = "\n"
+"\n"
+"\n"
+"]> ";
streamThrough(getReader(XML, nsAware));
}
}
public void testInvalidAny()
throws XMLStreamException
{
for (int i = 0; i < 2; ++i) {
boolean nsAware = (i > 0);
String XML = "\n"
+"]>";
streamThroughFailing(getReader(XML, nsAware),
"undeclared element in element with ANY content type");
}
}
/*
////////////////////////////////////////
// Private methods, other
////////////////////////////////////////
*/
private XMLStreamReader getReader(String contents, boolean nsAware)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setCoalescing(f, false); // shouldn't really matter
setNamespaceAware(f, nsAware);
setSupportDTD(f, true);
setValidating(f, true);
return constructStreamReader(f, contents);
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/vstream/TestInvalidDTD.java 0000644 0001750 0001750 00000007042 10444554662 025620 0 ustar twerner twerner package org.codehaus.stax.test.vstream;
import javax.xml.stream.*;
/**
* Simple unit test suite that checks for set of well-formedness problems
* with DTDs
*
* @author Tatu Saloranta
*/
public class TestInvalidDTD
extends BaseVStreamTest
{
public void testInvalidDirectives()
throws XMLStreamException
{
String XML = "\n"
+"]>\n";
streamThroughFailing(getValidatingReader(XML), "invalid directive ''");
XML = "\n"
+"\n"
+"]>\n";
streamThroughFailing(getValidatingReader(XML), "invalid directive ''");
}
public void testInvalidGE()
throws XMLStreamException
{
// Need space between name, content
String XML = "\n"
+"]>\n";
streamThroughFailing(getValidatingReader(XML),
"missing space between general entity name and value");
}
public void testInvalidPE()
throws XMLStreamException
{
// Need space between name, content
String XML = "\n"
+"\n"
+"]>\n";
streamThroughFailing(getValidatingReader(XML), "missing space between parameter entity name and value");
// As well as before and after percent sign
XML = "\n"
+"\n"
+"]>\n";
streamThroughFailing(getValidatingReader(XML), "missing space between parameter entity percent sign and name");
XML = "\n"
+"\n"
+"]>";
streamThroughFailing(getValidatingReader(XML), "missing space between ENTITY and parameter entity percent sign");
// and finally, no NDATA allowed for PEs
XML = "\n"
+"\n"
+"\n"
+"]>\n";
streamThroughFailing(getValidatingReader(XML), "PEs can not be unparsed external (ie. have NDATA reference)");
}
public void testInvalidComment()
throws XMLStreamException
{
String XML = "\n"
+"\n"
+"]>";
streamThroughFailing(getValidatingReader(XML), "invalid directive ''");
}
public void testInvalidPI()
throws XMLStreamException
{
String XML = "\n"
+"\n"
+"]>";
streamThroughFailing(getValidatingReader(XML), "invalid processing instruction in DTD; can not have target 'xml'");
}
/**
* CDATA directive not allowed in DTD subsets.
*/
public void testInvalidCData()
throws XMLStreamException
{
String XML = "\n"
+"\n"
+"]>";
streamThroughFailing(getValidatingReader(XML), "invalid CDATA directive in int. DTD subset");
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/vstream/TestDTDElemRead.java 0000644 0001750 0001750 00000007072 10444554662 025713 0 ustar twerner twerner package org.codehaus.stax.test.vstream;
import javax.xml.stream.*;
/**
* Unit test suite that tests handling of DTD element declarations.
*/
public class TestDTDElemRead
extends BaseVStreamTest
{
public TestDTDElemRead(String name) {
super(name);
}
/*
///////////////////////////////////////
// Element declaration tests:
///////////////////////////////////////
*/
public void testValidElementDecl()
throws XMLStreamException
{
/* Following should be ok; it is not an error to refer to
* undeclared elements... although it is to encounter such
* undeclared elements in content.
*/
String XML = "\n"
+"]>\n";
streamThrough(getVReader(XML));
}
public void testInvalidElementDecl()
throws XMLStreamException
{
/* Then let's make sure that duplicate element declarations
* are caught (as they are errors):
*/
String XML = "\n"
+"\n"
+"\n"
+"]>\n";
try {
streamThrough(getVReader(XML));
fail("Expected an exception for duplicate ELEMENT declaration.");
} catch (XMLStreamException ex) { // good
} catch (RuntimeException ex2) { // ok
} catch (Throwable t) { // not so good
fail("Expected an XMLStreamException or RuntimeException for duplicate ELEMENT declaration, not: "+t);
}
}
/**
* Let's ensure basic simple notation declarations are parsed
* succesfully.
*/
public void testValidNotationDecl()
throws XMLStreamException
{
// Will need a simple content model, too, since we are validating...
String XML = "\n"
+"\n"
+"\n"
+"]>";
streamThrough(getVReader(XML));
}
/**
* This unit test checks that there are no duplicate notation declarations
*/
public void testInvalidDupNotationDecl()
throws XMLStreamException
{
/* Then let's make sure that duplicate element declarations
* are caught (as they are errors):
*/
String XML = "\n"
+"\n"
+"\n"
+"]>";
try {
streamThrough(getVReader(XML));
fail("Expected an exception for duplicate NOTATION declaration.");
} catch (XMLStreamException ex) { // good
} catch (RuntimeException ex2) { // ok
} catch (Throwable t) { // not so good
fail("Expected an XMLStreamException or RuntimeException for duplicate NOTATION declaration, not: "+t);
}
}
/*
////////////////////////////////////////
// Private methods
////////////////////////////////////////
*/
private XMLStreamReader getVReader(String contents)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setCoalescing(f, false); // shouldn't really matter
//setNamespaceAware(f, nsAware);
setSupportDTD(f, true);
// Let's make sure DTD is really parsed?
setValidating(f, true);
return constructStreamReader(f, contents);
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/vstream/TestIdAttrRead.java 0000644 0001750 0001750 00000020457 10444554662 025666 0 ustar twerner twerner package org.codehaus.stax.test.vstream;
import javax.xml.stream.*;
/**
* Unit test suite that tests handling of attributes that are declared
* by DTD to be of type ID, IDREF or IDREFS; such information is only
* guranteed to be available in validation mode.
*/
public class TestIdAttrRead
extends BaseVStreamTest
{
public TestIdAttrRead(String name) {
super(name);
}
/*
///////////////////////////////////////
// Test cases
///////////////////////////////////////
*/
/**
* Test case that verifies behaviour of valid ID/IDREF/IDREF
* attribute declarations.
*/
public void testValidIdAttrDecl()
throws XMLStreamException
{
// Following should be ok
String XML = "\n"
+"\n"
+"\n"
+"]>\n";
streamThrough(getValidatingReader(XML));
}
/**
* Test case that verifies behaviour of invalid ID/IDREF/IDREF
* attribute declarations.
*/
public void testInvalidIdAttrDecl()
throws XMLStreamException
{
/* First, let's check couple of invalid id attr declarations
*/
// Can not have default value for id attr
String XML = "\n"
+"\n"
+"]>\n";
XMLStreamReader sr = getValidatingReader(XML);
streamThroughFailing(sr, "invalid attribute id (default value not allowed)");
// Nor require fixed value
sr = getValidatingReader("\n"
+"\n"
+"]>\n");
streamThroughFailing(sr, "invalid id attribute (fixed value not allowed)");
// Only one attr id per element
sr = getValidatingReader("\n"
+"\n"
+"]>\n");
streamThroughFailing(sr, "more than one attribute id per element");
}
public void testInvalidIdRefAttrDecl()
throws XMLStreamException
{
// IDREF default value needs to be valid id
XMLStreamReader sr = getValidatingReader("\n"
+"\n"
+"]>\n");
streamThroughFailing(sr, "invalid IDREF default value ('#' not allowed)");
sr = getValidatingReader("\n"
+"\n"
+"]>\n");
streamThroughFailing(sr, "invalid (missing) IDREF default value");
// IDREFS default value needs to be non-empty set of valid ids
sr = getValidatingReader("\n"
+"\n"
+"]>\n");
streamThroughFailing(sr, "invalid IDREFS default value ('?' not allowed)");
sr = getValidatingReader("\n"
+"\n"
+"]>\n");
streamThroughFailing(sr, "invalid (missing) IDREFS default value");
}
public void testValidIdAttrUse()
throws XMLStreamException
{
// Following should be ok; all ids are defined
String XML = "\n"
+"\n"
+"\n"
+"]>\n ";
streamThrough(getValidatingReader(XML));
}
public void testInvalidIdAttrUse()
throws XMLStreamException
{
// Error: undefined id 'someId'
String XML = "\n"
+"\n"
+"\n"
+"]>\n";
streamThroughFailing(getValidatingReader(XML),
"undefined id reference for 'someId'");
// Error: empty idref value
XML = "\n"
+"\n"
+"\n"
+"]>\n";
streamThroughFailing(getValidatingReader(XML),
"empty IDREF value");
}
public void testValidIdAttrsUse()
throws XMLStreamException
{
// Following should be ok; all ids are defined
String XML = "\n"
+"\n"
+"\n"
+"]>\n\n"
+"\n"
+"";
streamThrough(getValidatingReader(XML));
}
public void testInvalidIdAttrsUse()
throws XMLStreamException
{
// Error: undefined id 'someId'
String XML = "\n"
+"\n"
+"\n"
+"]>\n";
streamThroughFailing(getValidatingReader(XML),
"undefined id reference for 'someId'");
// Error: empty idrefs value
XML = "\n"
+"\n"
+"\n"
+"]>\n";
streamThroughFailing(getValidatingReader(XML),
"empty IDREFS value");
}
/**
* Unit test that verifies that values of attributes of type ID
* will get properly normalized.
*/
public void testIdAttrNormalization()
throws XMLStreamException
{
String XML = "\n"
+"\n"
+"\n"
+"]>"
+""
+""
+"";
;
XMLStreamReader sr = getValidatingReader(XML);
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals(1, sr.getAttributeCount());
assertEquals("someId", sr.getAttributeValue(0));
assertTokenType(START_ELEMENT, sr.next());
assertEquals(1, sr.getAttributeCount());
assertEquals("otherId", sr.getAttributeValue(0));
assertTokenType(END_ELEMENT, sr.next());
assertTokenType(END_ELEMENT, sr.next());
}
public void testIdRefAttrNormalization()
throws XMLStreamException
{
String XML = "\n"
+"\n"
+"\n"
+"\n"
+"]>"
+""
+""
+""
+"";
;
XMLStreamReader sr = getValidatingReader(XML);
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals(2, sr.getAttributeCount());
assertEquals("id2", sr.getAttributeValue(0));
assertEquals("someId", sr.getAttributeValue(1));
assertTokenType(END_ELEMENT, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals(1, sr.getAttributeCount());
assertEquals("id2 someId", sr.getAttributeValue(0));
assertTokenType(END_ELEMENT, sr.next());
assertTokenType(END_ELEMENT, sr.next());
}
/*
////////////////////////////////////////
// Private methods
////////////////////////////////////////
*/
}
stax-1.2.0.orig/src/org/codehaus/stax/test/vstream/TestNotationAttrRead.java 0000644 0001750 0001750 00000011305 10444554662 027115 0 ustar twerner twerner package org.codehaus.stax.test.vstream;
import javax.xml.stream.*;
/**
* Unit test suite that tests handling of attributes that are declared
* by DTD to be of type NOTATION.
*/
public class TestNotationAttrRead
extends BaseVStreamTest
{
public TestNotationAttrRead(String name) {
super(name);
// To see if we get exceptions we should be getting:
//PRINT_EXP_EXCEPTION = true;
}
/*
///////////////////////////////////////
// Test cases
///////////////////////////////////////
*/
public void testValidAttrDecl()
throws XMLStreamException
{
// Following should be ok; notations have been declared ok
String XML = "\n"
+"\n"
+"\n"
+""
+"]>\n";
streamThrough(getValidatingReader(XML));
// Likewise for default values
XML = "\n"
+"\n"
+"\n"
+""
+"]>\n";
streamThrough(getValidatingReader(XML));
}
public void testInvalidAttrDecl()
throws XMLStreamException
{
// First, let's check that undeclared notation throws an exception
String XML = "\n"
+""
+"]>\n";
XMLStreamReader sr = getValidatingReader(XML);
streamThroughFailing(sr, "undeclared notation");
// And then that only one attribute of type NOTATION is allowed per element
XML = "\n"
+"\n"
+"\n"
+"]>\n";
sr = getValidatingReader(XML);
streamThroughFailing(sr, "more than one notation attribute per element");
// Also, notation ids can not be duplicates
XML = "\n"
+"\n"
+"\n"
+"\n"
+"]>\n";
sr = getValidatingReader(XML);
streamThroughFailing(sr, "duplicate notation values enumerated for attribute");
}
public void testValidAttrUse()
throws XMLStreamException
{
// Following should be ok, everything defined as required...
String XML = "\n"
+"\n"
+"\n"
+"\n"
+"]>\n";
streamThrough(getReader(XML));
}
public void testInvalidAttrUse()
throws XMLStreamException
{
// Shouldn't work, undefined notation...
String XML = "\n"
+"\n"
+"\n"
+"]>\n";
XMLStreamReader sr = getValidatingReader(XML);
streamThroughFailing(sr, "reference to notation that is not enumerated");
// and same using default values
XML = "\n"
+"\n"
+"\n"
+"]>\n";
sr = getValidatingReader(XML);
streamThroughFailing(sr, "reference to notation (via default value) that is not enumerated");
}
/*
////////////////////////////////////////
// Private methods
////////////////////////////////////////
*/
private XMLStreamReader getReader(String contents)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setCoalescing(f, false); // shouldn't really matter
//setNamespaceAware(f, nsAware);
setSupportDTD(f, true);
// Let's make sure DTD is really parsed?
setValidating(f, true);
return constructStreamReader(f, contents);
}
}
stax-1.2.0.orig/src/org/codehaus/stax/test/vstream/TestAttrRead.java 0000644 0001750 0001750 00000021333 10444554662 025403 0 ustar twerner twerner package org.codehaus.stax.test.vstream;
import javax.xml.stream.*;
/**
* Unit test suite that tests basic handling of attributes; aspects
* that do not depend on actual concrete type.
*/
public class TestAttrRead
extends BaseVStreamTest
{
public TestAttrRead(String name) {
super(name);
}
/*
///////////////////////////////////////
// Attribute declaration tests:
///////////////////////////////////////
*/
/**
* Simple tests for generic valid attribute declarations; using
* some constructs that can be warned about, but that are not
* erroneous.
*/
public void testValidAttrDecl()
throws XMLStreamException
{
/* First; declaring attributes for non-declared elements is
* not an error
*/
String XML = "\n"
+"\n"
+"]>\n";
streamThrough(getValidatingReader(XML, true));
/* Then, declaring same attribute more than once is not an
* error; first one is binding (note: should test that this
* indeed happens, via attribute property inspection?)
*/
XML = "\n"
+"\n"
+"\n"
+"\n"
+"]>\n";
streamThrough(getValidatingReader(XML, true));
}
/**
* Unit test that verifies that the attribute type declaration information
* is properly parsed and accessible via stream reader.
*/
public void testAttributeTypes()
throws XMLStreamException
{
String XML = "\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"]>"
+"";
/* Could/should extend to cover all types... but this should be
* enough to at least determined reader does pass through the
* type info (instead of always returning CDATA)
*/
XMLStreamReader sr = getValidatingReader(XML, true);
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals(4, sr.getAttributeCount());
for (int i = 0; i < 4; ++i) {
String ln = sr.getAttributeLocalName(i);
String type = sr.getAttributeType(i);
String expType = ln.toUpperCase();
assertNotNull("Attribute type should never be null; CDATA should be returned if information not known/available");
assertEquals("Incorrect attribute type for attribute '"+ln+"'",
expType, type);
}
assertTokenType(END_ELEMENT, sr.next());
}
public void testValidRequiredAttr()
throws XMLStreamException
{
// this should be valid:
String XML = "\n"
+"\n"
+"]>";
XMLStreamReader sr = getValidatingReader(XML, true);
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals(1, sr.getAttributeCount());
assertEquals("attr", sr.getAttributeLocalName(0));
assertEquals("value", sr.getAttributeValue(0));
}
public void testInvalidRequiredAttr()
throws XMLStreamException
{
// Invalid as it's missing the required attribute
String XML = "\n"
+"\n"
+"]>\n";
streamThroughFailing(getValidatingReader(XML, true),
"Missing required attribute value");
}
public void testOkFixedAttr()
throws XMLStreamException
{
// Ok to omit altogether
String XML = "\n"
+"\n"
+"]>";
// But if so, should get the default value
XMLStreamReader sr = getValidatingReader(XML, true);
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals("Should have 1 attribute; 'elem' had #FIXED default value", 1, sr.getAttributeCount());
assertEquals("attr", sr.getAttributeLocalName(0));
assertEquals("fixed", sr.getAttributeValue(0));
assertTokenType(END_ELEMENT, sr.next());
sr.close();
// Or to use fixed value
XML = "\n"
+"\n"
+"]>";
sr = getValidatingReader(XML, true);
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals(1, sr.getAttributeCount());
assertEquals("attr", sr.getAttributeLocalName(0));
assertEquals("fixed", sr.getAttributeValue(0));
assertTokenType(END_ELEMENT, sr.next());
}
public void testInvalidFixedAttr()
throws XMLStreamException
{
// Not ok to have any other value, either completely different
String XML = "\n"
+"\n"
+"]>\n";
streamThroughFailing(getValidatingReader(XML),
"fixed attribute value not matching declaration");
// Or one with extra white space (CDATA won't get fully normalized)
XML = "\n"
+"\n"
+"]>\n";
streamThroughFailing(getValidatingReader(XML),
"fixed attribute value not matching declaration");
}
/**
* Unit test that verifies that the default attribute values are properly
* used on validating mode.
*/
public void testDefaultAttr()
throws XMLStreamException
{
// Let's verify we get default value
String XML = "\n"
+"\n"
+"]>";
XMLStreamReader sr = getValidatingReader(XML, true);
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals(1, sr.getAttributeCount());
assertEquals("attr", sr.getAttributeLocalName(0));
assertEquals("default", sr.getAttributeValue(0));
}
/**
* Test for proper handling for multiple attribute declarations for
* a single attribute. This is legal, although discouraged (ie. parser
* can issue a non-fatal warning): but if used, the first definition
* should stick. Let's test for both default values and types.
*/
public void testMultipleDeclForSingleAttr()
throws XMLStreamException
{
// Let's verify we get the right default value
String XML = "\n"
+"\n"
+"\n"
+"]>";
XMLStreamReader sr = getValidatingReader(XML, true);
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals(1, sr.getAttributeCount());
assertEquals("attr", sr.getAttributeLocalName(0));
assertEquals("val1", sr.getAttributeValue(0));
// And then let's test that the type is correct as well
XML = "\n"
+"\n"
+"\n"
+"]>";
sr = getValidatingReader(XML, true);
assertTokenType(DTD, sr.next());
assertTokenType(START_ELEMENT, sr.next());
assertEquals(1, sr.getAttributeCount());
assertEquals("attr", sr.getAttributeLocalName(0));
assertEquals("valX", sr.getAttributeValue(0));
assertEquals("NMTOKEN", sr.getAttributeType(0));
}
/*
////////////////////////////////////////
// Private methods
////////////////////////////////////////
*/
}
stax-1.2.0.orig/src/org/codehaus/stax/test/BaseStaxTest.java 0000644 0001750 0001750 00000045141 10444554662 023731 0 ustar twerner twerner package org.codehaus.stax.test;
import java.io.*;
import java.util.HashMap;
import junit.framework.TestCase;
import javax.xml.stream.*;
import javax.xml.stream.events.XMLEvent;
/**
* Base class for all StaxTest unit test classes. Contains shared
* functionality for many common set up tasks, as well as for
* outputting diagnostics.
*
* @author Tatu Saloranta
*/
public class BaseStaxTest
extends TestCase
implements XMLStreamConstants
{
/**
* This is the de facto standard property that enables accurate reporting
* of CDATA events.
*/
final static String PROP_REPORT_CDATA = "http://java.sun.com/xml/stream/properties/report-cdata-event";
final static HashMap mTokenTypes = new HashMap();
static {
mTokenTypes.put(new Integer(START_ELEMENT), "START_ELEMENT");
mTokenTypes.put(new Integer(END_ELEMENT), "END_ELEMENT");
mTokenTypes.put(new Integer(START_DOCUMENT), "START_DOCUMENT");
mTokenTypes.put(new Integer(END_DOCUMENT), "END_DOCUMENT");
mTokenTypes.put(new Integer(CHARACTERS), "CHARACTERS");
mTokenTypes.put(new Integer(CDATA), "CDATA");
mTokenTypes.put(new Integer(COMMENT), "COMMENT");
mTokenTypes.put(new Integer(PROCESSING_INSTRUCTION), "PROCESSING_INSTRUCTION");
mTokenTypes.put(new Integer(DTD), "DTD");
mTokenTypes.put(new Integer(SPACE), "SPACE");
mTokenTypes.put(new Integer(ENTITY_REFERENCE), "ENTITY_REFERENCE");
mTokenTypes.put(new Integer(NAMESPACE), "NAMESPACE_DECLARATION");
mTokenTypes.put(new Integer(NOTATION_DECLARATION), "NOTATION_DECLARATION");
mTokenTypes.put(new Integer(ENTITY_DECLARATION), "ENTITY_DECLARATION");
}
/*
///////////////////////////////////////////////////
// Consts for expected values
///////////////////////////////////////////////////
*/
/**
* Expected return value for streamReader.getNamespaceURI() in
* non-namespace-aware mode
*/
protected final String DEFAULT_URI_NON_NS = null;
protected final String DEFAULT_URI_NS = "";
/*
///////////////////////////////////////////////////
// Other consts
///////////////////////////////////////////////////
*/
/*
///////////////////////////////////////////////////
// Cached instances
///////////////////////////////////////////////////
*/
XMLInputFactory mInputFactory;
XMLOutputFactory mOutputFactory;
XMLEventFactory mEventFactory;
protected BaseStaxTest(String name) {
super(name);
}
protected BaseStaxTest() { super(); }
/*
//////////////////////////////////////////////////
// Factory methods
//////////////////////////////////////////////////
*/
protected XMLInputFactory getInputFactory()
{
if (mInputFactory == null) {
mInputFactory = getNewInputFactory();
}
return mInputFactory;
}
protected static XMLInputFactory getNewInputFactory()
{
return XMLInputFactory.newInstance();
}
protected XMLOutputFactory getOutputFactory()
{
if (mOutputFactory == null) {
mOutputFactory = getNewOutputFactory();
}
return mOutputFactory;
}
protected static XMLOutputFactory getNewOutputFactory()
{
return XMLOutputFactory.newInstance();
}
protected XMLEventFactory getEventFactory()
{
if (mEventFactory == null) {
mEventFactory = XMLEventFactory.newInstance();
}
return mEventFactory;
}
protected static XMLStreamReader constructStreamReader(XMLInputFactory f, String content)
throws XMLStreamException
{
return f.createXMLStreamReader(new StringReader(content));
}
protected static XMLStreamReader constructStreamReader(XMLInputFactory f, byte[] b)
throws XMLStreamException
{
return f.createXMLStreamReader(new ByteArrayInputStream(b));
}
protected static XMLStreamReader constructStreamReaderForFile(XMLInputFactory f, String filename)
throws IOException, XMLStreamException
{
File inf = new File(filename);
XMLStreamReader sr = f.createXMLStreamReader(inf.toURL().toString(),
new FileReader(inf));
assertEquals(START_DOCUMENT, sr.getEventType());
return sr;
}
protected XMLStreamReader constructNsStreamReader(String content)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setNamespaceAware(f, true);
return f.createXMLStreamReader(new StringReader(content));
}
protected XMLStreamReader constructNsStreamReader(String content, boolean coal)
throws XMLStreamException
{
XMLInputFactory f = getInputFactory();
setNamespaceAware(f, true);
setCoalescing(f, coal);
return f.createXMLStreamReader(new StringReader(content));
}
/*
//////////////////////////////////////////////////
// Configuring input factory
//////////////////////////////////////////////////
*/
protected static boolean isCoalescing(XMLInputFactory f)
throws XMLStreamException
{
return ((Boolean) f.getProperty(XMLInputFactory.IS_COALESCING)).booleanValue();
}
protected static void setCoalescing(XMLInputFactory f, boolean state)
throws XMLStreamException
{
Boolean b = state ? Boolean.TRUE : Boolean.FALSE;
f.setProperty(XMLInputFactory.IS_COALESCING, b);
// Let's just double-check it...
assertEquals(state, isCoalescing(f));
}
protected static boolean isValidating(XMLInputFactory f)
throws XMLStreamException
{
return ((Boolean) f.getProperty(XMLInputFactory.IS_VALIDATING)).booleanValue();
}
protected static void setValidating(XMLInputFactory f, boolean state)
throws XMLStreamException
{
try {
Boolean b = state ? Boolean.TRUE : Boolean.FALSE;
f.setProperty(XMLInputFactory.IS_VALIDATING, b);
} catch (IllegalArgumentException iae) {
fail("Could not set DTD validating mode to "+state+": "+iae);
//throw new XMLStreamException(iae.getMessage(), iae);
}
assertEquals(state, isValidating(f));
}
protected static boolean isNamespaceAware(XMLInputFactory f)
throws XMLStreamException
{
return ((Boolean) f.getProperty(XMLInputFactory.IS_NAMESPACE_AWARE)).booleanValue();
}
/**
* @return True if setting succeeded, and property supposedly was
* succesfully set to the value specified; false if there was a problem.
*/
protected static boolean setNamespaceAware(XMLInputFactory f, boolean state)
throws XMLStreamException
{
try {
f.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE,
state ? Boolean.TRUE : Boolean.FALSE);
/* 07-Sep-2005, TSa: Let's not assert, but instead let's see if
* it sticks. Some implementations might choose to silently
* ignore setting, at least for 'false'?
*/
return (isNamespaceAware(f) == state);
} catch (IllegalArgumentException e) {
/* Let's assume, then, that the property (or specific value for it)
* is NOT supported...
*/
return false;
}
}
protected static void setReplaceEntities(XMLInputFactory f, boolean state)
throws XMLStreamException
{
Boolean b = state ? Boolean.TRUE : Boolean.FALSE;
f.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, b);
assertEquals(b, f.getProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES));
}
protected static void setSupportDTD(XMLInputFactory f, boolean state)
throws XMLStreamException
{
Boolean b = state ? Boolean.TRUE : Boolean.FALSE;
f.setProperty(XMLInputFactory.SUPPORT_DTD, b);
assertEquals(b, f.getProperty(XMLInputFactory.SUPPORT_DTD));
}
protected static boolean setSupportExternalEntities(XMLInputFactory f, boolean state)
throws XMLStreamException
{
Boolean b = state ? Boolean.TRUE : Boolean.FALSE;
try {
f.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, b);
Object act = f.getProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES);
return (act instanceof Boolean) && ((Boolean) act).booleanValue() == state;
} catch (IllegalArgumentException e) {
/* Let's assume, then, that the property (or specific value for it)
* is NOT supported...
*/
return false;
}
}
protected static void setResolver(XMLInputFactory f, XMLResolver resolver)
throws XMLStreamException
{
f.setProperty(XMLInputFactory.RESOLVER, resolver);
}
protected static boolean setReportCData(XMLInputFactory f, boolean state)
throws XMLStreamException
{
Boolean b = state ? Boolean.TRUE : Boolean.FALSE;
if (f.isPropertySupported(PROP_REPORT_CDATA)) {
f.setProperty(PROP_REPORT_CDATA, b);
return true;
}
return false;
}
/*
//////////////////////////////////////////////////
// Stream reader accessors
//////////////////////////////////////////////////
*/
/**
* Method that not only gets currently available text from the
* reader, but also checks that its consistenly accessible using
* different StAX methods.
*/
protected static String getAndVerifyText(XMLStreamReader sr)
throws XMLStreamException
{
String text = sr.getText();
/* 05-Apr-2006, TSa: Although getText() is available for DTD
* and ENTITY_REFERENCE, getTextXxx() are not. Thus, can not
* do more checks for those types.
*/
int type = sr.getEventType();
if (type != ENTITY_REFERENCE && type != DTD) {
assertNotNull("getText() should never return null.", text);
int expLen = sr.getTextLength();
/* Hmmh. Can only return empty text for CDATA (since empty
* blocks are legal).
*/
/* !!! 01-Sep-2004, TSa:
* note: theoretically, in coalescing mode, it could be possible
* to have empty CDATA section(s) get converted to CHARACTERS,
* which would be empty... may need to enhance this to check that
* mode is not coalescing? Or something
*/
if (sr.getEventType() == CHARACTERS) {
assertTrue("Stream reader should never return empty Strings.", (expLen > 0));
}
assertEquals("Expected text length of "+expLen+", got "+text.length(),
expLen, text.length());
char[] textChars = sr.getTextCharacters();
int start = sr.getTextStart();
String text2 = new String(textChars, start, expLen);
assertEquals("Expected getText() and getTextCharacters() to return same value for event of type ("+tokenTypeDesc(sr.getEventType())+")", text, text2);
} else { // DTD or ENTITY_REFERENCE
// not sure if null is legal for these either, but...
if (text == null) { // let's prevent an NPE at caller
text = "";
}
}
return text;
}
protected static String getAllText(XMLStreamReader sr)
throws XMLStreamException
{
StringBuffer sb = new StringBuffer();
while (true) {
int tt = sr.getEventType();
if (tt != CHARACTERS && tt != SPACE) {
break;
}
sb.append(getAndVerifyText(sr));
sr.next();
}
return sb.toString();
}
protected static String getAllCData(XMLStreamReader sr)
throws XMLStreamException
{
StringBuffer sb = new StringBuffer();
while (true) {
/* Note: CDATA sections CAN be reported as CHARACTERS, but
* not as SPACE
*/
int tt = sr.getEventType();
if (tt != CHARACTERS && tt != CDATA) {
break;
}
sb.append(getAndVerifyText(sr));
sr.next();
}
return sb.toString();
}
/*
//////////////////////////////////////////////////
// Derived assert/fail methods
//////////////////////////////////////////////////
*/
protected static void assertTokenType(int expType, int actType)
{
if (expType == actType) {
return;
}
fail("Expected token "+tokenTypeDesc(expType)
+"; got "+tokenTypeDesc(actType)+".");
}
protected static void assertTokenType(int expType, int actType,
XMLStreamReader sr)
{
if (expType == actType) {
return;
}
fail("Expected token "+tokenTypeDesc(expType)
+"; got "+tokenTypeDesc(actType, sr)+".");
}
protected static void assertTextualTokenType(int actType)
{
if (actType != CHARACTERS && actType != SPACE
&& actType != CDATA) {
fail("Expected textual token (CHARACTERS, SPACE or CDATA)"
+"; got "+tokenTypeDesc(actType)+".");
}
}
protected static void failStrings(String msg, String exp, String act)
{
// !!! TODO: Indicate position where Strings differ
fail(msg+": expected "+quotedPrintable(exp)+", got "
+quotedPrintable(act));
}
/**
* Specific method makes sense, since it's not 100% clear whether
* it's legal to use both null and "" when no prefix was found
*/
protected static void assertNoPrefix(XMLStreamReader sr)
throws XMLStreamException
{
String prefix = sr.getPrefix();
if (prefix != null && prefix.length() > 0) {
fail("Excepted no (or empty) prefix: got '"+prefix+"'");
}
}
/**
* Similar to {@link #assertNoPrefix}, but here we do know that unbound
* namespace URI should be indicated as null, not empty String.
*/
protected static void assertNoNsURI(XMLStreamReader sr)
throws XMLStreamException
{
String uri = sr.getNamespaceURI();
if (uri != null) {
if (uri.length() == 0) { // most likely
fail("Excepted no (null) namespace URI: got empty string; non-conformant");
}
fail("Excepted no (null) namespace URI: got '"+uri+"'");
}
}
protected static void assertNoPrefixOrNs(XMLStreamReader sr)
throws XMLStreamException
{
assertNoPrefix(sr);
assertNoNsURI(sr);
}
/**
* Helper assertion that assert that the String is either null or
* empty ("").
*/
protected static void assertNullOrEmpty(String str)
{
if (str != null && str.length() > 0) {
fail("Expected String to be empty or null; was '"+str+"' (length "
+str.length()+")");
}
}
/*
//////////////////////////////////////////////////
// Debug/output helpers
//////////////////////////////////////////////////
*/
protected static String tokenTypeDesc(int tt)
{
String desc = (String) mTokenTypes.get(new Integer(tt));
if (desc == null) {
return "["+tt+"]";
}
return desc;
}
protected static String tokenTypeDesc(XMLEvent evt)
{
return tokenTypeDesc(evt.getEventType());
}
final static int MAX_DESC_TEXT_CHARS = 8;
protected static String tokenTypeDesc(int tt, XMLStreamReader sr)
{
String desc = tokenTypeDesc(tt);
// Let's show first 8 chars or so...
if (tt == CHARACTERS || tt == SPACE || tt == CDATA) {
String str = sr.getText();
if (str.length() > MAX_DESC_TEXT_CHARS) {
desc = "\""+str.substring(0, MAX_DESC_TEXT_CHARS) + "\"[...]";
} else {
desc = "\"" + desc + "\"";
}
desc = " ("+desc+")";
}
return desc;
}
protected static String valueDesc(String value)
{
if (value == null) {
return "[NULL]";
}
return "\"" + value + "\"";
}
protected static String printable(char ch)
{
if (ch == '\n') {
return "\\n";
}
if (ch == '\r') {
return "\\r";
}
if (ch == '\t') {
return "\\t";
}
if (ch == ' ') {
return "_";
}
if (ch > 127 || ch < 32) {
StringBuffer sb = new StringBuffer(6);
sb.append("\\u");
String hex = Integer.toHexString((int)ch);
for (int i = 0, len = 4 - hex.length(); i < len; i++) {
sb.append('0');
}
sb.append(hex);
return sb.toString();
}
return null;
}
protected static String printable(String str)
{
if (str == null || str.length() == 0) {
return str;
}
int len = str.length();
StringBuffer sb = new StringBuffer(len + 64);
for (int i = 0; i < len; ++i) {
char c = str.charAt(i);
String res = printable(c);
if (res == null) {
sb.append(c);
} else {
sb.append(res);
}
}
return sb.toString();
}
protected static String quotedPrintable(String str)
{
if (str == null || str.length() == 0) {
return "[0]''";
}
return "[len: "+str.length()+"] '"+printable(str)+"'";
}
protected void reportNADueToProperty(String method, String prop)
{
String clsName = getClass().getName();
/* 27-Sep-2005, TSa: Should probably use some other mechanism for
* reporting this. Does JUnit have something applicable?
*/
System.err.println("Skipping "+clsName+"#"+method+": property '"
+prop+"' (or one of its values) not supported.");
}
protected void reportNADueToNS(String method)
{
reportNADueToProperty(method, "IS_NAMESPACE_AWARE");
}
protected void reportNADueToExtEnt(String method)
{
reportNADueToProperty(method, "IS_SUPPORTING_EXTERNAL_ENTITIES");
}
protected void reportNADueToEntityExpansion(String method, int type)
{
String clsName = getClass().getName();
String msg = (type > 0) ? " (next event: "+tokenTypeDesc(type)+")" : "";
System.err.println("Skipping "+clsName+"#"+method+": entity expansion does not seem to be functioning properly"+msg+".");
}
}
stax-1.2.0.orig/src/javax/ 0000755 0001750 0001750 00000000000 10444554662 015300 5 ustar twerner twerner stax-1.2.0.orig/src/javax/xml/ 0000755 0001750 0001750 00000000000 10444554664 016102 5 ustar twerner twerner stax-1.2.0.orig/src/javax/xml/XMLConstants.java 0000644 0001750 0001750 00000005507 10444554664 021311 0 ustar twerner twerner // $Id: XMLConstants.java,v 1.1 2004/10/13 16:38:07 aslom Exp $
package javax.xml;
/**
* Utility class to contain basic XML values as constants.
*
* @author JAXP Java Community Process
* @author JAXP Reference Implementation
* @version 1.0.proposed
* @see
* Extensible Markup Language (XML) 1.0 (Second Edition)
* @see
* Namespaces in XML
* @see
* Namespaces in XML Errata
**/
public class XMLConstants {
/**
* Constructor to prevent instantiation.
*/
private XMLConstants() { }
/**
* Prefix to use to represent the default XML Namespace.
*
*
Defined by the XML specification to be "".
*
* @see
* Namespaces in XML
*/
public static final String DEFAULT_NS_PREFIX = "";
/**
* The official XML Namespace prefix.
*
* Defined by the XML specification to be "xml
".
*
* @see
* Namespaces in XML
*/
public static final String XML_NS_PREFIX = "xml";
/**
* The official XML Namespace name URI.
*
* Defined by the XML specification to be
* "http://www.w3.org/XML/1998/namespace
".
*
* @see
* Namespaces in XML
*/
public static final String XML_NS_URI =
"http://www.w3.org/XML/1998/namespace";
/**
* The official XML attribute used for specifying XML Namespace
* declarations.
*
* It is not valid to use as a prefix.
* Defined by the XML specification to be
* "xmlns
".
*
* @see
* Namespaces in XML
*/
public static final String XMLNS_ATTRIBUTE = "xmlns";
/**
* The official XML attribute used for specifying XML Namespace
* declarations, {@link #XMLNS_ATTRIBUTE "xmlns"}, Namespace name
* URI.
*
* Defined by the XML specification to be
* "http://www.w3.org/2000/xmlns/
".
*
* @see
* Namespaces in XML
* @see
* Namespaces in XML Errata
*/
public static final String XMLNS_ATTRIBUTE_NS_URI =
"http://www.w3.org/2000/xmlns/";
}
stax-1.2.0.orig/src/javax/xml/stream/ 0000755 0001750 0001750 00000000000 10444554664 017375 5 ustar twerner twerner stax-1.2.0.orig/src/javax/xml/stream/XMLReporter.java 0000644 0001750 0001750 00000001632 10444554664 022425 0 ustar twerner twerner package javax.xml.stream;
/**
* This interface is used to report non-fatal errors.
* Only warnings should be echoed through this interface.
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
*/
public interface XMLReporter {
/**
* Report the desired message in an application specific format.
* Only warnings and non-fatal errors should be reported through
* this interface.
* Fatal errors should be thrown as XMLStreamException.
*
* @param message the error message
* @param errorType an implementation defined error type
* @param relatedInformation information related to the error, if available
* @param location the location of the error, if available
* @throws XMLStreamException
*/
public void report(String message, String errorType, Object relatedInformation, Location location)
throws XMLStreamException;
}
stax-1.2.0.orig/src/javax/xml/stream/XMLStreamException.java 0000644 0001750 0001750 00000004657 10444554664 023747 0 ustar twerner twerner package javax.xml.stream;
/**
* The base exception for unexpected processing errors. This Exception
* class is used to report well-formedness errors as well as unexpected
* processing conditions.
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
*/
public class XMLStreamException extends Exception {
protected Throwable nested;
protected Location location;
/**
* Default constructor
*/
public XMLStreamException(){
super();
}
/**
* Construct an exception with the assocated message.
*
* @param msg the message to report
*/
public XMLStreamException(String msg) {
super(msg);
}
/**
* Construct an exception with the assocated exception
*
* @param th a nested exception
*/
public XMLStreamException(Throwable th) {
nested = th;
}
/**
* Construct an exception with the assocated message and exception
*
* @param th a nested exception
* @param msg the message to report
*/
public XMLStreamException(String msg, Throwable th) {
super(msg);
nested = th;
}
/**
* Construct an exception with the assocated message, exception and location.
*
* @param th a nested exception
* @param msg the message to report
* @param location the location of the error
*/
public XMLStreamException(String msg, Location location, Throwable th) {
super("ParseError at [row,col]:["+location.getLineNumber()+","+
location.getColumnNumber()+"]\n"+
"Message: "+msg);
nested = th;
this.location = location;
}
/**
* Construct an exception with the assocated message, exception and location.
*
* @param msg the message to report
* @param location the location of the error
*/
public XMLStreamException(String msg,
Location location) {
super("ParseError at [row,col]:["+location.getLineNumber()+","+
location.getColumnNumber()+"]\n"+
"Message: "+msg);
this.location = location;
}
/**
* Gets the nested exception.
*
* @return Nested exception
*/
public Throwable getNestedException() {
return nested;
}
/**
* Gets the location of the exception
*
* @return the location of the exception, may be null if none is available
*/
public Location getLocation() {
return location;
}
}
stax-1.2.0.orig/src/javax/xml/stream/EventFilter.java 0000644 0001750 0001750 00000001160 10444554664 022465 0 ustar twerner twerner package javax.xml.stream;
import javax.xml.stream.events.XMLEvent;
/**
* This interface declares a simple filter interface that one can
* create to filter XMLEventReaders
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
*/
public interface EventFilter {
/**
* Tests whether this event is part of this stream. This method
* will return true if this filter accepts this event and false
* otherwise.
*
* @param event the event to test
* @return true if this filter accepts this event, false otherwise
*/
public boolean accept(XMLEvent event);
}
stax-1.2.0.orig/src/javax/xml/stream/XMLOutputFactory.java 0000644 0001750 0001750 00000020516 10444554664 023455 0 ustar twerner twerner package javax.xml.stream;
import javax.xml.transform.Result;
/**
* Defines an abstract implementation of a factory for
* getting XMLEventWriters and XMLStreamWriters.
*
* The following table defines the standard properties of this specification.
* Each property varies in the level of support required by each implementation.
* The level of support required is described in the 'Required' column.
*
*
*
*
*
* Configuration parameters
* |
*
*
*
*
* Property Name |
* Behavior |
* Return type |
* Default Value |
* Required |
*
* javax.xml.stream.isRepairingNamespaces | defaults prefixes on the output side | Boolean | False | Yes |
*
*
*
* The following paragraphs describe the namespace and prefix repair algorithm:
*
* The property can be set with the following code line:
* setProperty("javax.xml.stream.isRepairingNamespaces",new Boolean(true|false));
*
* This property specifies that the writer default namespace prefix declarations.
* The default value is false.
*
* If a writer isRepairingNamespaces it will create a namespace declaration
* on the current StartElement for
* any attribute that does not
* currently have a namespace declaration in scope. If the StartElement
* has a uri but no prefix specified a prefix will be assigned, if the prefix
* has not been declared in a parent of the current StartElement it will be declared
* on the current StartElement. If the defaultNamespace is bound and in scope
* and the default namespace matches the URI of the attribute or StartElement
* QName no prefix will be assigned.
*
* If an element or attribute name has a prefix, but is not
* bound to any namespace URI, then the prefix will be removed
* during serialization.
*
* If element and/or attribute names in the same start or
* empty-element tag are bound to different namespace URIs and
* are using the same prefix then the element or the first
* occurring attribute retains the original prefix and the
* following attributes have their prefixes replaced with a
* new prefix that is bound to the namespace URIs of those
* attributes.
*
* If an element or attribute name uses a prefix that is
* bound to a different URI than that inherited from the
* namespace context of the parent of that element and there
* is no namespace declaration in the context of the current
* element then such a namespace declaration is added.
*
* If an element or attribute name is bound to a prefix and
* there is a namespace declaration that binds that prefix
* to a different URI then that namespace declaration is
* either removed if the correct mapping is inherited from
* the parent context of that element, or changed to the
* namespace URI of the element or attribute using that prefix.
*
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see XMLInputFactory
* @see XMLEventWriter
* @see XMLStreamWriter
*/
public abstract class XMLOutputFactory {
/**
* Property used to set prefix defaulting on the output side
*/
public static final String IS_REPAIRING_NAMESPACES=
"javax.xml.stream.isRepairingNamespaces";
protected XMLOutputFactory(){}
/**
* Create a new instance of the factory using the default factory location
* mechanism (check env. variable, jaxp.properties, jar services manifest,
* in this order)
*
* @throws FactoryConfigurationError if an instance of this factory cannot be loaded
*/
public static XMLOutputFactory newInstance()
throws FactoryConfigurationError
{
return (XMLOutputFactory) FactoryFinder.find("javax.xml.stream.XMLOutputFactory",
"com.bea.xml.stream.XMLOutputFactoryBase");
}
/**
* Create a new instance of the factory
*
* @param factoryId Name of the factory to find; not the class name but the
* property name to use
* @param classLoader classLoader to use
* @return the factory implementation
* @throws FactoryConfigurationError if an instance of this factory cannot be loaded
*/
public static XMLOutputFactory newInstance(String factoryId,
ClassLoader classLoader)
throws FactoryConfigurationError
{
return (XMLOutputFactory) FactoryFinder.find(
factoryId,
"com.bea.xml.stream.XMLOutputFactoryBase",
classLoader);
}
/**
* Create a new XMLStreamWriter that writes to a writer
* @param stream the writer to write to
* @throws XMLStreamException
*/
public abstract XMLStreamWriter createXMLStreamWriter(java.io.Writer stream) throws XMLStreamException;
/**
* Create a new XMLStreamWriter that writes to a stream
* @param stream the stream to write to
* @throws XMLStreamException
*/
public abstract XMLStreamWriter createXMLStreamWriter(java.io.OutputStream stream) throws XMLStreamException;
/**
* Create a new XMLStreamWriter that writes to a stream
* @param stream the stream to write to
* @param encoding the encoding to use
* @throws XMLStreamException
*/
public abstract XMLStreamWriter createXMLStreamWriter(java.io.OutputStream stream,
String encoding) throws XMLStreamException;
/**
* Create a new XMLStreamWriter that writes to a JAXP result. This method is optional.
* @param result the result to write to
* @throws UnsupportedOperationException if this method is not
* supported by this XMLOutputFactory
* @throws XMLStreamException
*/
public abstract XMLStreamWriter createXMLStreamWriter(Result result) throws XMLStreamException;
/**
* Create a new XMLEventWriter that writes to a JAXP result. This method is optional.
* @param result the result to write to
* @throws UnsupportedOperationException if this method is not
* supported by this XMLOutputFactory
* @throws XMLStreamException
*/
public abstract XMLEventWriter createXMLEventWriter(Result result) throws XMLStreamException;
/**
* Create a new XMLEventWriter that writes to a stream
* @param stream the stream to write to
* @throws XMLStreamException
*/
public abstract XMLEventWriter createXMLEventWriter(java.io.OutputStream stream) throws XMLStreamException;
/**
* Create a new XMLEventWriter that writes to a stream
* @param stream the stream to write to
* @param encoding the encoding to use
* @throws XMLStreamException
*/
public abstract XMLEventWriter createXMLEventWriter(java.io.OutputStream stream,
String encoding) throws XMLStreamException;
/**
* Create a new XMLEventWriter that writes to a writer
* @param stream the stream to write to
* @throws XMLStreamException
*/
public abstract XMLEventWriter createXMLEventWriter(java.io.Writer stream) throws XMLStreamException;
/**
* Allows the user to set specific features/properties on the underlying implementation.
* @param name The name of the property
* @param value The value of the property
* @throws java.lang.IllegalArgumentException if the property is not supported
*/
public abstract void setProperty(java.lang.String name,
Object value)
throws IllegalArgumentException;
/**
* Get a feature/property on the underlying implementation
* @param name The name of the property
* @return The value of the property
* @throws java.lang.IllegalArgumentException if the property is not supported
*/
public abstract Object getProperty(java.lang.String name)
throws IllegalArgumentException;
/**
* Query the set of properties that this factory supports.
*
* @param name The name of the property (may not be null)
* @return true if the property is supported and false otherwise
*/
public abstract boolean isPropertySupported(String name);
}
stax-1.2.0.orig/src/javax/xml/stream/XMLStreamWriter.java 0000644 0001750 0001750 00000032221 10444554664 023251 0 ustar twerner twerner package javax.xml.stream;
import javax.xml.namespace.NamespaceContext;
/**
* The XMLStreamWriter interface specifies how to write XML. The XMLStreamWriter does
* not perform well formedness checking on its input. However
* the writeCharacters method is required to escape & , < and >
* For attribute values the writeAttribute method will escape the
* above characters plus " to ensure that all character content
* and attribute values are well formed.
*
* Each NAMESPACE
* and ATTRIBUTE must be individually written.
*
* If javax.xml.stream.isRepairingNamespaces is set to false it is a fatal error if an element
* is written with namespace URI that has not been bound to a prefix.
*
* If javax.xml.stream.isRepairingNamespaces is set to true the XMLStreamWriter implementation
* must write a prefix for each unbound URI that it encounters in the
* current scope.
*
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see XMLOutputFactory
* @see XMLStreamReader
*/
public interface XMLStreamWriter {
/**
* Writes a start tag to the output. All writeStartElement methods
* open a new scope in the internal namespace context. Writing the
* corresponding EndElement causes the scope to be closed.
* @param localName local name of the tag, may not be null
* @throws XMLStreamException
*/
public void writeStartElement(String localName)
throws XMLStreamException;
/**
* Writes a start tag to the output
* @param namespaceURI the namespaceURI of the prefix to use, may not be null
* @param localName local name of the tag, may not be null
* @throws XMLStreamException if the namespace URI has not been bound to a prefix and
* javax.xml.stream.isPrefixDefaulting has not been set to true
*/
public void writeStartElement(String namespaceURI, String localName)
throws XMLStreamException;
/**
* Writes a start tag to the output
* @param localName local name of the tag, may not be null
* @param prefix the prefix of the tag, may not be null
* @param namespaceURI the uri to bind the prefix to, may not be null
* @throws XMLStreamException
*/
public void writeStartElement(String prefix,
String localName,
String namespaceURI)
throws XMLStreamException;
/**
* Writes an empty element tag to the output
* @param namespaceURI the uri to bind the tag to, may not be null
* @param localName local name of the tag, may not be null
* @throws XMLStreamException if the namespace URI has not been bound to a prefix and
* javax.xml.stream.isPrefixDefaulting has not been set to true
*/
public void writeEmptyElement(String namespaceURI, String localName)
throws XMLStreamException;
/**
* Writes an empty element tag to the output
* @param prefix the prefix of the tag, may not be null
* @param localName local name of the tag, may not be null
* @param namespaceURI the uri to bind the tag to, may not be null
* @throws XMLStreamException
*/
public void writeEmptyElement(String prefix, String localName, String namespaceURI)
throws XMLStreamException;
/**
* Writes an empty element tag to the output
* @param localName local name of the tag, may not be null
* @throws XMLStreamException
*/
public void writeEmptyElement(String localName)
throws XMLStreamException;
/**
* Writes string data to the output without checking for well formedness.
* The data is opaque to the XMLStreamWriter, i.e. the characters are written
* blindly to the underlying output. If the method cannot be supported
* in the currrent writing context the implementation may throw a
* UnsupportedOperationException. For example note that any
* namespace declarations, end tags, etc. will be ignored and could
* interfere with proper maintanence of the writers internal state.
*
* @param data the data to write
*/
// public void writeRaw(String data) throws XMLStreamException;
/**
* Writes an end tag to the output relying on the internal
* state of the writer to determine the prefix and local name
* of the event.
* @throws XMLStreamException
*/
public void writeEndElement()
throws XMLStreamException;
/**
* Closes any start tags and writes corresponding end tags.
* @throws XMLStreamException
*/
public void writeEndDocument()
throws XMLStreamException;
/**
* Close this writer and free any resources associated with the
* writer. This must not close the underlying output stream.
* @throws XMLStreamException
*/
public void close()
throws XMLStreamException;
/**
* Write any cached data to the underlying output mechanism.
* @throws XMLStreamException
*/
public void flush()
throws XMLStreamException;
/**
* Writes an attribute to the output stream without
* a prefix.
* @param localName the local name of the attribute
* @param value the value of the attribute
* @throws IllegalStateException if the current state does not allow Attribute writing
* @throws XMLStreamException
*/
public void writeAttribute(String localName, String value)
throws XMLStreamException;
/**
* Writes an attribute to the output stream
* @param prefix the prefix for this attribute
* @param namespaceURI the uri of the prefix for this attribute
* @param localName the local name of the attribute
* @param value the value of the attribute
* @throws IllegalStateException if the current state does not allow Attribute writing
* @throws XMLStreamException if the namespace URI has not been bound to a prefix and
* javax.xml.stream.isPrefixDefaulting has not been set to true
*/
public void writeAttribute(String prefix,
String namespaceURI,
String localName,
String value)
throws XMLStreamException;
/**
* Writes an attribute to the output stream
* @param namespaceURI the uri of the prefix for this attribute
* @param localName the local name of the attribute
* @param value the value of the attribute
* @throws IllegalStateException if the current state does not allow Attribute writing
* @throws XMLStreamException if the namespace URI has not been bound to a prefix and
* javax.xml.stream.isPrefixDefaulting has not been set to true
*/
public void writeAttribute(String namespaceURI,
String localName,
String value)
throws XMLStreamException;
/**
* Writes a namespace to the output stream
* If the prefix argument to this method is the empty string,
* "xmlns", or null this method will delegate to writeDefaultNamespace
*
* @param prefix the prefix to bind this namespace to
* @param namespaceURI the uri to bind the prefix to
* @throws IllegalStateException if the current state does not allow Namespace writing
* @throws XMLStreamException
*/
public void writeNamespace(String prefix, String namespaceURI)
throws XMLStreamException;
/**
* Writes the default namespace to the stream
* @param namespaceURI the uri to bind the default namespace to
* @throws IllegalStateException if the current state does not allow Namespace writing
* @throws XMLStreamException
*/
public void writeDefaultNamespace(String namespaceURI)
throws XMLStreamException;
/**
* Writes an xml comment with the data enclosed
* @param data the data contained in the comment, may be null
* @throws XMLStreamException
*/
public void writeComment(String data)
throws XMLStreamException;
/**
* Writes a processing instruction
* @param target the target of the processing instruction, may not be null
* @throws XMLStreamException
*/
public void writeProcessingInstruction(String target)
throws XMLStreamException;
/**
* Writes a processing instruction
* @param target the target of the processing instruction, may not be null
* @param data the data contained in the processing instruction, may not be null
* @throws XMLStreamException
*/
public void writeProcessingInstruction(String target,
String data)
throws XMLStreamException;
/**
* Writes a CData section
* @param data the data contained in the CData Section, may not be null
* @throws XMLStreamException
*/
public void writeCData(String data)
throws XMLStreamException;
/**
* Write a DTD section. This string represents the entire doctypedecl production
* from the XML 1.0 specification.
*
* @param dtd the DTD to be written
* @throws XMLStreamException
*/
public void writeDTD(String dtd)
throws XMLStreamException;
/**
* Writes an entity reference
* @param name the name of the entity
* @throws XMLStreamException
*/
public void writeEntityRef(String name)
throws XMLStreamException;
/**
* Write the XML Declaration. Defaults the XML version to 1.0, and the encoding to utf-8
* @throws XMLStreamException
*/
public void writeStartDocument()
throws XMLStreamException;
/**
* Write the XML Declaration. Defaults the XML version to 1.0
* @param version version of the xml document
* @throws XMLStreamException
*/
public void writeStartDocument(String version)
throws XMLStreamException;
/**
* Write the XML Declaration. Note that the encoding parameter does
* not set the actual encoding of the underlying output. That must
* be set when the instance of the XMLStreamWriter is created using the
* XMLOutputFactory
* @param encoding encoding of the xml declaration
* @param version version of the xml document
* @throws XMLStreamException
*/
public void writeStartDocument(String encoding,
String version)
throws XMLStreamException;
/**
* Write text to the output
* @param text the value to write
* @throws XMLStreamException
*/
public void writeCharacters(String text)
throws XMLStreamException;
/**
* Write text to the output
* @param text the value to write
* @param start the starting position in the array
* @param len the number of characters to write
* @throws XMLStreamException
*/
public void writeCharacters(char[] text, int start, int len)
throws XMLStreamException;
/**
* Gets the prefix the uri is bound to
* @return the prefix or null
* @throws XMLStreamException
*/
public String getPrefix(String uri)
throws XMLStreamException;
/**
* Sets the prefix the uri is bound to. This prefix is bound
* in the scope of the current START_ELEMENT / END_ELEMENT pair.
* If this method is called before a START_ELEMENT has been written
* the prefix is bound in the root scope.
* @param prefix the prefix to bind to the uri, may not be null
* @param uri the uri to bind to the prefix, may be null
* @throws XMLStreamException
*/
public void setPrefix(String prefix, String uri)
throws XMLStreamException;
/**
* Binds a URI to the default namespace
* This URI is bound
* in the scope of the current START_ELEMENT / END_ELEMENT pair.
* If this method is called before a START_ELEMENT has been written
* the uri is bound in the root scope.
* @param uri the uri to bind to the default namespace, may be null
* @throws XMLStreamException
*/
public void setDefaultNamespace(String uri)
throws XMLStreamException;
/**
* Sets the current namespace context for prefix and uri bindings.
* This context becomes the root namespace context for writing and
* will replace the current root namespace context. Subsequent calls
* to setPrefix and setDefaultNamespace will bind namespaces using
* the context passed to the method as the root context for resolving
* namespaces. This method may only be called once at the start of
* the document. It does not cause the namespaces to be declared.
* If a namespace URI to prefix mapping is found in the namespace
* context it is treated as declared and the prefix may be used
* by the StreamWriter.
* @param context the namespace context to use for this writer, may not be null
* @throws XMLStreamException
*/
public void setNamespaceContext(NamespaceContext context)
throws XMLStreamException;
/**
* Returns the current namespace context.
* @return the current NamespaceContext
*/
public NamespaceContext getNamespaceContext();
/**
* Get the value of a feature/property from the underlying implementation
* @param name The name of the property, may not be null
* @return The value of the property
* @throws IllegalArgumentException if the property is not supported
* @throws NullPointerException if the name is null
*/
public Object getProperty(java.lang.String name) throws IllegalArgumentException;
}
stax-1.2.0.orig/src/javax/xml/stream/FactoryFinder.java 0000644 0001750 0001750 00000015622 10444554664 023005 0 ustar twerner twerner package javax.xml.stream;
import java.io.InputStream;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import java.io.BufferedReader;
import java.io.InputStreamReader;
class FactoryFinder {
/** Temp debug code - this will be removed after we test everything
*/
private static boolean debug = false;
static {
// Use try/catch block to support applets
try {
debug = System.getProperty("xml.stream.debug") != null;
} catch (Exception x) {
}
}
private static void debugPrintln(String msg) {
if (debug) {
System.err.println("STREAM: " + msg);
}
}
private static ClassLoader findClassLoader()
throws FactoryConfigurationError
{
ClassLoader classLoader;
try {
// Construct the name of the concrete class to instantiate
Class clazz = Class.forName(FactoryFinder.class.getName()
+ "$ClassLoaderFinderConcrete");
ClassLoaderFinder clf = (ClassLoaderFinder) clazz.newInstance();
classLoader = clf.getContextClassLoader();
} catch (LinkageError le) {
// Assume that we are running JDK 1.1, use the current ClassLoader
classLoader = FactoryFinder.class.getClassLoader();
} catch (ClassNotFoundException x) {
// This case should not normally happen. MS IE can throw this
// instead of a LinkageError the second time Class.forName() is
// called so assume that we are running JDK 1.1 and use the
// current ClassLoader
classLoader = FactoryFinder.class.getClassLoader();
} catch (Exception x) {
// Something abnormal happened so throw an error
throw new FactoryConfigurationError(x.toString(), x);
}
return classLoader;
}
/**
* Create an instance of a class using the specified ClassLoader
*/
private static Object newInstance(String className,
ClassLoader classLoader)
throws FactoryConfigurationError
{
try {
Class spiClass;
if (classLoader == null) {
spiClass = Class.forName(className);
} else {
spiClass = classLoader.loadClass(className);
}
return spiClass.newInstance();
} catch (ClassNotFoundException x) {
throw new FactoryConfigurationError(
"Provider " + className + " not found", x);
} catch (Exception x) {
throw new FactoryConfigurationError(
"Provider " + className + " could not be instantiated: " + x,
x);
}
}
static Object find(String factoryId)
throws FactoryConfigurationError
{
return find(factoryId,null);
}
static Object find(String factoryId,
String fallbackClassName)
throws FactoryConfigurationError
{
ClassLoader classLoader = findClassLoader();
return find(factoryId,fallbackClassName,classLoader);
}
/**
* Finds the implementation Class object in the specified order. Main
* entry point.
* @return Class object of factory, never null
*
* @param factoryId Name of the factory to find, same as
* a property name
* @param fallbackClassName Implementation class name, if nothing else
* is found. Use null to mean no fallback.
*
* Package private so this code can be shared.
*/
static Object find(String factoryId,
String fallbackClassName,
ClassLoader classLoader)
throws FactoryConfigurationError
{
// Use the system property first
try {
String systemProp =
System.getProperty( factoryId );
if( systemProp!=null) {
debugPrintln("found system property" + systemProp);
return newInstance(systemProp, classLoader);
}
} catch (SecurityException se) {
}
// try to read from $java.home/lib/xml.properties
try {
String javah=System.getProperty( "java.home" );
String configFile = javah + File.separator +
"lib" + File.separator + "jaxp.properties";
File f=new File( configFile );
if( f.exists()) {
Properties props=new Properties();
props.load( new FileInputStream(f));
String factoryClassName = props.getProperty(factoryId);
if (factoryClassName != null && factoryClassName.length() > 0) {
debugPrintln("found java.home property " + factoryClassName);
return newInstance(factoryClassName, classLoader);
}
}
} catch(Exception ex ) {
if( debug ) ex.printStackTrace();
}
String serviceId = "META-INF/services/" + factoryId;
// try to find services in CLASSPATH
try {
InputStream is=null;
if (classLoader == null) {
is=ClassLoader.getSystemResourceAsStream( serviceId );
} else {
is=classLoader.getResourceAsStream( serviceId );
}
if( is!=null ) {
debugPrintln("found " + serviceId);
BufferedReader rd =
new BufferedReader(new InputStreamReader(is, "UTF-8"));
String factoryClassName = rd.readLine();
rd.close();
if (factoryClassName != null &&
! "".equals(factoryClassName)) {
debugPrintln("loaded from services: " + factoryClassName);
return newInstance(factoryClassName, classLoader);
}
}
} catch( Exception ex ) {
if( debug ) ex.printStackTrace();
}
if (fallbackClassName == null) {
throw new FactoryConfigurationError(
"Provider for " + factoryId + " cannot be found", null);
}
debugPrintln("loaded from fallback value: " + fallbackClassName);
return newInstance(fallbackClassName, classLoader);
}
/*
* The following nested classes allow getContextClassLoader() to be
* called only on JDK 1.2 and yet run in older JDK 1.1 JVMs
*/
private static abstract class ClassLoaderFinder {
abstract ClassLoader getContextClassLoader();
}
static class ClassLoaderFinderConcrete extends ClassLoaderFinder {
ClassLoader getContextClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
}
}
stax-1.2.0.orig/src/javax/xml/stream/events/ 0000755 0001750 0001750 00000000000 10444554664 020701 5 ustar twerner twerner stax-1.2.0.orig/src/javax/xml/stream/events/Characters.java 0000644 0001750 0001750 00000002714 10444554662 023625 0 ustar twerner twerner package javax.xml.stream.events;
/**
* This describes the interface to Characters events.
* All text events get reported as Characters events.
* Content, CData and whitespace are all reported as
* Characters events. IgnorableWhitespace, in most cases,
* will be set to false unless an element declaration of element
* content is present for the current element.
*
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
*/
public interface Characters extends XMLEvent {
/**
* Get the character data of this event
*/
public String getData();
/**
* Returns true if this set of Characters
* is all whitespace. Whitespace inside a document
* is reported as CHARACTERS. This method allows
* checking of CHARACTERS events to see if they
* are composed of only whitespace characters
*/
public boolean isWhiteSpace();
/**
* Returns true if this is a CData section. If this
* event is CData its event type will be CDATA
*
* If javax.xml.stream.isCoalescing is set to true CDATA Sections
* that are surrounded by non CDATA characters will be reported
* as a single Characters event. This method will return false
* in this case.
*/
public boolean isCData();
/**
* Return true if this is ignorableWhiteSpace. If
* this event is ignorableWhiteSpace its event type will
* be SPACE.
*/
public boolean isIgnorableWhiteSpace();
}
stax-1.2.0.orig/src/javax/xml/stream/events/StartDocument.java 0000644 0001750 0001750 00000002202 10444554664 024334 0 ustar twerner twerner package javax.xml.stream.events;
/**
* An interface for the start document event
*
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
*/
public interface StartDocument extends XMLEvent {
/**
* Returns the system ID of the XML data
* @return the system ID, defaults to ""
*/
public String getSystemId();
/**
* Returns the encoding style of the XML data
* @return the character encoding, defaults to "UTF-8"
*/
public String getCharacterEncodingScheme();
/**
* Returns true if CharacterEncodingScheme was set in
* the encoding declaration of the document
*/
public boolean encodingSet();
/**
* Returns if this XML is standalone
* @return the standalone state of XML, defaults to "no"
*/
public boolean isStandalone();
/**
* Returns true if the standalone attribute was set in
* the encoding declaration of the document.
*/
public boolean standaloneSet();
/**
* Returns the version of XML of this XML stream
* @return the version of XML, defaults to "1.0"
*/
public String getVersion();
}
stax-1.2.0.orig/src/javax/xml/stream/events/EndDocument.java 0000644 0001750 0001750 00000000456 10444554664 023756 0 ustar twerner twerner package javax.xml.stream.events;
/**
* A marker interface for the end of the document
*
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
*/
public interface EndDocument extends XMLEvent {
/**
* No methods are defined in this interface.
*/
}
stax-1.2.0.orig/src/javax/xml/stream/events/StartElement.java 0000644 0001750 0001750 00000005710 10444554664 024156 0 ustar twerner twerner package javax.xml.stream.events;
import javax.xml.namespace.QName;
import javax.xml.namespace.NamespaceContext;
import java.util.Map;
import java.util.Iterator;
/**
* The StartElement interface provides access to information about
* start elements. A StartElement is reported for each Start Tag
* in the document.
*
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
*/
public interface StartElement extends XMLEvent {
/**
* Get the name of this event
* @return the qualified name of this event
*/
public QName getName();
/**
* Returns an Iterator of non-namespace declared attributes declared on
* this START_ELEMENT,
* returns an empty iterator if there are no attributes. The
* iterator must contain only implementations of the javax.xml.stream.Attribute
* interface. Attributes are fundamentally unordered and may not be reported
* in any order.
*
* @return a readonly Iterator over Attribute interfaces, or an
* empty iterator
*/
public Iterator getAttributes();
/**
* Returns an Iterator of namespaces declared on this element.
* This Iterator does not contain previously declared namespaces
* unless they appear on the current START_ELEMENT.
* Therefore this list may contain redeclared namespaces and duplicate namespace
* declarations. Use the getNamespaceContext() method to get the
* current context of namespace declarations.
*
* The iterator must contain only implementations of the
* javax.xml.stream.Namespace interface.
*
*
A Namespace isA Attribute. One
* can iterate over a list of namespaces as a list of attributes.
* However this method returns only the list of namespaces
* declared on this START_ELEMENT and does not
* include the attributes declared on this START_ELEMENT.
*
* Returns an empty iterator if there are no namespaces.
*
* @return a readonly Iterator over Namespace interfaces, or an
* empty iterator
*
*/
public Iterator getNamespaces();
/**
* Returns the attribute referred to by this name
* @param name the qname of the desired name
* @return the attribute corresponding to the name value or null
*/
public Attribute getAttributeByName(QName name);
/**
* Gets a read-only namespace context. If no context is
* available this method will return an empty namespace context.
* The NamespaceContext contains information about all namespaces
* in scope for this StartElement.
*
* @return the current namespace context
*/
public NamespaceContext getNamespaceContext();
/**
* Gets the value that the prefix is bound to in the
* context of this element. Returns null if
* the prefix is not bound in this context
* @param prefix the prefix to lookup
* @return the uri bound to the prefix or null
*/
public String getNamespaceURI(String prefix);
}
stax-1.2.0.orig/src/javax/xml/stream/events/Attribute.java 0000644 0001750 0001750 00000002150 10444554664 023505 0 ustar twerner twerner package javax.xml.stream.events;
import javax.xml.namespace.QName;
/**
* An interface that contains information about an attribute. Attributes are reported
* as a set of events accessible from a StartElement. Other applications may report
* Attributes as first-order events, for example as the results of an XPath expression.
*
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see StartElement
*/
public interface Attribute extends XMLEvent {
/**
* Returns the QName for this attribute
*/
QName getName();
/**
* Gets the normalized value of this attribute
*/
public String getValue();
/**
* Gets the type of this attribute, default is
* the String "CDATA"
* @return the type as a String, default is "CDATA"
*/
public String getDTDType();
/**
* A flag indicating whether this attribute was actually
* specified in the start-tag of its element, or was defaulted from the schema.
* @return returns true if this was specified in the start element
*/
public boolean isSpecified();
}
stax-1.2.0.orig/src/javax/xml/stream/events/XMLEvent.java 0000644 0001750 0001750 00000010251 10444554664 023205 0 ustar twerner twerner package javax.xml.stream.events;
import java.io.Writer;
import javax.xml.namespace.QName;
/**
* This is the base event interface for handling markup events.
* Events are value objects that are used to communicate the
* XML 1.0 InfoSet to the Application. Events may be cached
* and referenced after the parse has completed.
*
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see javax.xml.stream.XMLEventReader
* @see Characters
* @see ProcessingInstruction
* @see StartElement
* @see EndElement
* @see StartDocument
* @see EndDocument
* @see EntityReference
* @see EntityDeclaration
* @see NotationDeclaration
*/
public interface XMLEvent extends javax.xml.stream.XMLStreamConstants {
/**
* Returns an integer code for this event.
* @see #START_ELEMENT
* @see #END_ELEMENT
* @see #CHARACTERS
* @see #ATTRIBUTE
* @see #NAMESPACE
* @see #PROCESSING_INSTRUCTION
* @see #COMMENT
* @see #START_DOCUMENT
* @see #END_DOCUMENT
* @see #DTD
*/
public int getEventType();
/**
* Return the location of this event. The Location
* returned from this method is non-volatile and
* will retain its information.
* @see javax.xml.stream.Location
*/
javax.xml.stream.Location getLocation();
/**
* A utility function to check if this event is a StartElement.
* @see StartElement
*/
public boolean isStartElement();
/**
* A utility function to check if this event is an Attribute.
* @see Attribute
*/
public boolean isAttribute();
/**
* A utility function to check if this event is a Namespace.
* @see Namespace
*/
public boolean isNamespace();
/**
* A utility function to check if this event is a EndElement.
* @see EndElement
*/
public boolean isEndElement();
/**
* A utility function to check if this event is an EntityReference.
* @see EntityReference
*/
public boolean isEntityReference();
/**
* A utility function to check if this event is a ProcessingInstruction.
* @see ProcessingInstruction
*/
public boolean isProcessingInstruction();
/**
* A utility function to check if this event is Characters.
* @see Characters
*/
public boolean isCharacters();
/**
* A utility function to check if this event is a StartDocument.
* @see StartDocument
*/
public boolean isStartDocument();
/**
* A utility function to check if this event is an EndDocument.
* @see EndDocument
*/
public boolean isEndDocument();
/**
* Returns this event as a start element event, may result in
* a class cast exception if this event is not a start element.
*/
public StartElement asStartElement();
/**
* Returns this event as an end element event, may result in
* a class cast exception if this event is not a end element.
*/
public EndElement asEndElement();
/**
* Returns this event as Characters, may result in
* a class cast exception if this event is not Characters.
*/
public Characters asCharacters();
/**
* This method is provided for implementations to provide
* optional type information about the associated event.
* It is optional and will return null if no information
* is available.
*/
public QName getSchemaType();
/**
* This method will write the XMLEvent as per the XML 1.0 specification as Unicode characters.
* No indentation or whitespace should be outputted.
*
* Any user defined event type SHALL have this method
* called when being written to on an output stream.
* Built in Event types MUST implement this method,
* but implementations MAY choose not call these methods
* for optimizations reasons when writing out built in
* Events to an output stream.
* The output generated MUST be equivalent in terms of the
* infoset expressed.
*
* @param writer The writer that will output the data
* @throws XMLStreamException if there is a fatal error writing the event
*/
public void writeAsEncodedUnicode(Writer writer)
throws javax.xml.stream.XMLStreamException;
}
stax-1.2.0.orig/src/javax/xml/stream/events/EndElement.java 0000644 0001750 0001750 00000001416 10444554662 023564 0 ustar twerner twerner package javax.xml.stream.events;
import java.util.Iterator;
import javax.xml.namespace.QName;
/**
* An interface for the end element event. An EndElement is reported
* for each End Tag in the document.
*
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see XMLEvent
*/
public interface EndElement extends XMLEvent {
/**
* Get the name of this event
* @return the qualified name of this event
*/
public QName getName();
/**
* Returns an Iterator of namespaces that have gone out
* of scope. Returns an empty iterator if no namespaces have gone
* out of scope.
* @return an Iterator over Namespace interfaces, or an
* empty iterator
*/
public Iterator getNamespaces();
}
stax-1.2.0.orig/src/javax/xml/stream/events/DTD.java 0000644 0001750 0001750 00000002544 10444554664 022164 0 ustar twerner twerner package javax.xml.stream.events;
import java.util.List;
/**
* This is the top level interface for events dealing with DTDs
*
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
*/
public interface DTD extends XMLEvent {
/**
* Returns the entire Document Type Declaration as a string, including
* the internal DTD subset.
* This may be null if there is not an internal subset.
* If it is not null it must return the entire
* Document Type Declaration which matches the doctypedecl
* production in the XML 1.0 specification
*/
String getDocumentTypeDeclaration();
/**
* Returns an implementation defined representation of the DTD.
* This method may return null if no representation is available.
*/
Object getProcessedDTD();
/**
* Return a List containing the notations declared in the DTD.
* This list must contain NotationDeclaration events.
* @see NotationDeclaration
* @return an unordered list of NotationDeclaration events
*/
List getNotations();
/**
* Return a List containing the general entities,
* both external and internal, declared in the DTD.
* This list must contain EntityDeclaration events.
* @see EntityDeclaration
* @return an unordered list of EntityDeclaration events
*/
List getEntities();
}
stax-1.2.0.orig/src/javax/xml/stream/events/NotationDeclaration.java 0000644 0001750 0001750 00000001513 10444554662 025503 0 ustar twerner twerner package javax.xml.stream.events;
/**
* An interface for handling Notation Declarations
*
* Receive notification of a notation declaration event.
* It is up to the application to record the notation for later reference,
* At least one of publicId and systemId must be non-null.
* There is no guarantee that the notation declaration
* will be reported before any unparsed entities that use it.
*
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
*/
public interface NotationDeclaration extends XMLEvent {
/**
* The notation name.
*/
String getName();
/**
* The notation's public identifier, or null if none was given.
*/
String getPublicId();
/**
* The notation's system identifier, or null if none was given.
*/
String getSystemId();
}
stax-1.2.0.orig/src/javax/xml/stream/events/Comment.java 0000644 0001750 0001750 00000000545 10444554664 023152 0 ustar twerner twerner package javax.xml.stream.events;
/**
* An interface for comment events
*
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
*/
public interface Comment extends XMLEvent {
/**
* Return the string data of the comment, returns empty string if it
* does not exist
*/
public String getText();
}
stax-1.2.0.orig/src/javax/xml/stream/events/EntityReference.java 0000644 0001750 0001750 00000002165 10444554664 024643 0 ustar twerner twerner package javax.xml.stream.events;
/**
* An interface for handling Entity events.
*
* This event reports entities that have not been resolved
* and reports their replacement text unprocessed (if
* available). This event will be reported if javax.xml.stream.isReplacingEntityReferences
* is set to false. If javax.xml.stream.isReplacingEntityReferences is set to true
* entity references will be resolved transparently.
*
* Entities are handled in two possible ways:
*
* (1) If javax.xml.stream.isReplacingEntityReferences is set to true
* all entity references are resolved and reported as markup transparently.
* (2) If javax.xml.stream.isReplacingEntityReferences is set to false
* Entity references are reported as an EntityReference Event.
*
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
*/
public interface EntityReference extends XMLEvent {
/**
* Return the declaration of this entity.
*/
EntityDeclaration getDeclaration();
/**
* The name of the entity
* @return the entity's name, may not be null
*/
String getName();
}
stax-1.2.0.orig/src/javax/xml/stream/events/package.html 0000644 0001750 0001750 00000000747 10444554664 023172 0 ustar twerner twerner
Describes a set of events for processing XML
Related Documentation
Provides various utilities for processing XML
Package Specification
This package describes a set of utility APIs for the Streaming API
for XML
Related Documentation
stax-1.2.0.orig/src/javax/xml/stream/events/ProcessingInstruction.java 0000644 0001750 0001750 00000001111 10444554664 026114 0 ustar twerner twerner package javax.xml.stream.events;
/**
* An interface that describes the data found in processing instructions
*
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
*/
public interface ProcessingInstruction extends XMLEvent {
/**
* The target section of the processing instruction
*
* @return the String value of the PI or null
*/
public String getTarget();
/**
* The data section of the processing instruction
*
* @return the String value of the PI's data or null
*/
public String getData();
}
stax-1.2.0.orig/src/javax/xml/stream/events/Namespace.java 0000644 0001750 0001750 00000001335 10444554664 023442 0 ustar twerner twerner package javax.xml.stream.events;
import javax.xml.namespace.QName;
/**
* An interface that contains information about a namespace.
* Namespaces are accessed from a StartElement.
*
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see StartElement
*/
public interface Namespace extends Attribute {
/**
* Gets the prefix, returns "" if this is a default
* namespace declaration.
*/
public String getPrefix();
/**
* Gets the uri bound to the prefix of this namespace
*/
public String getNamespaceURI();
/**
* returns true if this attribute declares the default namespace
*/
public boolean isDefaultNamespaceDeclaration();
}
stax-1.2.0.orig/src/javax/xml/stream/events/EntityDeclaration.java 0000644 0001750 0001750 00000002313 10444554664 025165 0 ustar twerner twerner package javax.xml.stream.events;
/**
* An interface for handling Entity Declarations
*
* This interface is used to record and report unparsed entity declarations.
*
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
*/
public interface EntityDeclaration extends XMLEvent {
/**
* The entity's public identifier, or null if none was given
* @return the public ID for this declaration or null
*/
String getPublicId();
/**
* The entity's system identifier.
* @return the system ID for this declaration or null
*/
String getSystemId();
/**
* The entity's name
* @return the name, may not be null
*/
String getName();
/**
* The name of the associated notation.
* @return the notation name
*/
String getNotationName();
/**
* The replacement text of the entity.
* This method will only return non-null
* if this is an internal entity.
* @return null or the replacment text
*/
String getReplacementText();
/**
* Get the base URI for this reference
* or null if this information is not available
* @return the base URI or null
*/
String getBaseURI();
}
stax-1.2.0.orig/src/javax/xml/stream/XMLStreamReader.java 0000644 0001750 0001750 00000066253 10444554664 023213 0 ustar twerner twerner package javax.xml.stream;
import java.io.Reader;
import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
/**
* The XMLStreamReader interface allows forward, read-only access to XML.
* It is designed to be the lowest level and most efficient way to
* read XML data.
*
*
The XMLStreamReader is designed to iterate over XML using
* next() and hasNext(). The data can be accessed using methods such as getEventType(),
* getNamespaceURI(), getLocalName() and getText();
*
*
Parsing events are defined as the XML Declaration, a DTD,
* start tag, character data, white space, end tag, comment,
* or processing instruction. An attribute or namespace event may be encountered
* at the root level of a document as the result of a query operation.
*
*
For XML 1.0 compliance an XML processor must pass the
* identifiers of declared unparsed entities, notation declarations and their
* associated identifiers to the application. This information is
* provided through the property API on this interface.
* The following two properties allow access to this information:
* javax.xml.stream.notations and javax.xml.stream.entities.
* When the current event is a DTD the following call will return a
* list of Notations
* List l = (List) getProperty("javax.xml.stream.notations");
* The following call will return a list of entity declarations:
* List l = (List) getProperty("javax.xml.stream.entities");
* These properties can only be accessed during a DTD event and
* are defined to return null if the information is not available.
*
*
The following table describes which methods are valid in what state.
* If a method is called in an invalid state the method will throw a
* java.lang.IllegalStateException.
*
*
*
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see javax.xml.stream.events.XMLEvent
* @see XMLInputFactory
* @see XMLStreamWriter
*/
public interface XMLStreamReader extends XMLStreamConstants {
/**
* Get the value of a feature/property from the underlying implementation
* @param name The name of the property, may not be null
* @return The value of the property
* @throws IllegalArgumentException if name is null
*/
public Object getProperty(java.lang.String name) throws java.lang.IllegalArgumentException;
/**
* Get next parsing event - a processor may return all contiguous
* character data in a single chunk, or it may split it into several chunks.
* If the property javax.xml.stream.isCoalescing is set to true
* element content must be coalesced and only one CHARACTERS event
* must be returned for contiguous element content or
* CDATA Sections.
*
* By default entity references must be
* expanded and reported transparently to the application.
* An exception will be thrown if an entity reference cannot be expanded.
* If element content is empty (i.e. content is "") then no CHARACTERS event will be reported.
*
*
*
* @throws XMLStreamException if the current event is not a START_ELEMENT
* or if a non text element is encountered
*/
public String getElementText() throws XMLStreamException;
/**
* Skips any white space (isWhiteSpace() returns true), COMMENT,
* or PROCESSING_INSTRUCTION,
* until a START_ELEMENT or END_ELEMENT is reached.
* If other than white space characters, COMMENT, PROCESSING_INSTRUCTION, START_ELEMENT, END_ELEMENT
* are encountered, an exception is thrown. This method should
* be used when processing element-only content seperated by white space.
*
*
Precondition: none
*
Postcondition: the current event is START_ELEMENT or END_ELEMENT
* and cursor may have moved over any whitespace event.
*
*
Essentially it does the following (implementations are free to optimized
* but must do equivalent processing):
*
*
* @return the event type of the element read (START_ELEMENT or END_ELEMENT)
* @throws XMLStreamException if the current event is not white space, PROCESSING_INSTRUCTION,
* START_ELEMENT or END_ELEMENT
* @throws NoSuchElementException if this is called when hasNext() returns false
*/
public int nextTag() throws XMLStreamException;
/**
* Returns true if there are more parsing events and false
* if there are no more events. This method will return
* false if the current state of the XMLStreamReader is
* END_DOCUMENT
* @return true if there are more events, false otherwise
* @throws XMLStreamException if there is a fatal error detecting the next state
*/
public boolean hasNext() throws XMLStreamException;
/**
* Frees any resources associated with this Reader. This method does not close the
* underlying input source.
* @throws XMLStreamException if there are errors freeing associated resources
*/
public void close() throws XMLStreamException;
/**
* Return the uri for the given prefix.
* The uri returned depends on the current state of the processor.
*
*
* The sub stream is read from it MUST be read before the parent stream is
* moved on, if not any call on the sub stream will cause an XMLStreamException to be
* thrown. The parent stream will always return the same result from next()
* whatever is done to the sub stream.
* @return an XMLStreamReader which points to the next element
*/
// public XMLStreamReader subReader() throws XMLStreamException;
/**
* Allows the implementation to reset and reuse any underlying tables
*/
// public void recycle() throws XMLStreamException;
/**
* Returns an integer code that indicates the type
* of the event the cursor is pointing to.
*/
public int getEventType();
/**
* Returns the current value of the parse event as a string,
* this returns the string value of a CHARACTERS event,
* returns the value of a COMMENT, the replacement value
* for an ENTITY_REFERENCE, the string value of a CDATA section,
* the string value for a SPACE event,
* or the String value of the internal subset of the DTD.
* If an ENTITY_REFERENCE has been resolved, any character data
* will be reported as CHARACTERS events.
* @return the current text or null
* @throws java.lang.IllegalStateException if this state is not
* a valid text state.
*/
public String getText();
/**
* Returns an array which contains the characters from this event.
* This array should be treated as read-only and transient. I.e. the array will
* contain the text characters until the XMLStreamReader moves on to the next event.
* Attempts to hold onto the character array beyond that time or modify the
* contents of the array are breaches of the contract for this interface.
* @return the current text or an empty array
* @throws java.lang.IllegalStateException if this state is not
* a valid text state.
*/
public char[] getTextCharacters();
/**
* Gets the the text associated with a CHARACTERS, SPACE or CDATA event.
* Text starting a "sourceStart" is copied into "target" starting at "targetStart".
* Up to "length" characters are copied. The number of characters actually copied is returned.
*
* The "sourceStart" argument must be greater or equal to 0 and less than or equal to
* the number of characters associated with the event. Usually, one requests text starting at a "sourceStart" of 0.
* If the number of characters actually copied is less than the "length", then there is no more text.
* Otherwise, subsequent calls need to be made until all text has been retrieved. For example:
*
*
* int length = 1024;
* char[] myBuffer = new char[ length ];
*
* for ( int sourceStart = 0 ; ; sourceStart += length )
* {
* int nCopied = stream.getTextCharacters( sourceStart, myBuffer, 0, length );
*
* if (nCopied < length)
* break;
* }
*
* XMLStreamException may be thrown if there are any XML errors in the underlying source.
* The "targetStart" argument must be greater than or equal to 0 and less than the length of "target",
* Length must be greater than 0 and "targetStart + length" must be less than or equal to length of "target".
*
* @param sourceStart the index of the first character in the source array to copy
* @param target the destination array
* @param targetStart the start offset in the target array
* @param length the number of characters to copy
* @return the number of characters actually copied
* @throws XMLStreamException if the underlying XML source is not well-formed
* @throws IndexOutOfBoundsException if targetStart < 0 or > than the length of target
* @throws IndexOutOfBoundsException if length < 0 or targetStart + length > length of target
* @throws UnsupportedOperationException if this method is not supported
* @throws NullPointerException is if target is null
*/
public int getTextCharacters(int sourceStart, char[] target, int targetStart, int length)
throws XMLStreamException;
/**
* Gets the text associated with a CHARACTERS, SPACE or CDATA event. Allows the underlying
* implementation to return the text as a stream of characters. The reference to the
* Reader returned by this method is only valid until next() is called.
*
* All characters must have been checked for well-formedness.
*
*
This method is optional and will throw UnsupportedOperationException if it is not supported.
* @throws UnsupportedOperationException if this method is not supported
* @throws IllegalStateException if this is not a valid text state
*/
//public Reader getTextStream();
/**
* Returns the offset into the text character array where the first
* character (of this text event) is stored.
* @throws java.lang.IllegalStateException if this state is not
* a valid text state.
*/
public int getTextStart();
/**
* Returns the length of the sequence of characters for this
* Text event within the text character array.
* @throws java.lang.IllegalStateException if this state is not
* a valid text state.
*/
public int getTextLength();
/**
* Return input encoding if known or null if unknown.
* @return the encoding of this instance or null
*/
public String getEncoding();
/**
* Return true if the current event has text, false otherwise
* The following events have text:
* CHARACTERS,DTD ,ENTITY_REFERENCE, COMMENT, SPACE
*/
public boolean hasText();
/**
* Return the current location of the processor.
* If the Location is unknown the processor should return
* an implementation of Location that returns -1 for the
* location and null for the publicId and systemId.
* The location information is only valid until next() is
* called.
*/
public Location getLocation();
/**
* Returns a QName for the current START_ELEMENT or END_ELEMENT event
* @return the QName for the current START_ELEMENT or END_ELEMENT event
* @throws IllegalStateException if this is not a START_ELEMENT or
* END_ELEMENT
*/
public QName getName();
/**
* Returns the (local) name of the current event.
* For START_ELEMENT or END_ELEMENT returns the (local) name of the current element.
* For ENTITY_REFERENCE it returns entity name.
* The current event must be START_ELEMENT or END_ELEMENT,
* or ENTITY_REFERENCE
* @return the localName
* @throws IllegalStateException if this not a START_ELEMENT,
* END_ELEMENT or ENTITY_REFERENCE
*/
public String getLocalName();
/**
* returns true if the current event has a name (is a START_ELEMENT or END_ELEMENT)
* returns false otherwise
*/
public boolean hasName();
/**
* If the current event is a START_ELEMENT or END_ELEMENT this method
* returns the URI of the current element (URI mapping to the prefix
* element/attribute has, if any; or if no prefix, null for attribute,
* and the default namespace URI for the element).
*
* @return the URI bound to this elements prefix, the default namespace, or null
* @throws IllegalStateException if this is not a START_ELEMENT, END_ELEMENT
* or ATTRIBUTE
*/
public String getNamespaceURI();
/**
* Returns the prefix of the current event or null if the event does not
* have a prefix
* @return the prefix or null
* @throws IllegalStateException if this is not a START_ELEMENT or END_ELEMENT
*/
public String getPrefix();
/**
* Get the xml version declared on the xml declaration
* Returns null if none was declared
* @return the XML version or null
*/
public String getVersion();
/**
* Get the standalone declaration from the xml declaration, if one found
* ({@link #standaloneSet} returns true if one was specified).
*
* @return true if this is standalone, or false otherwise
*/
public boolean isStandalone();
/**
* Checks if standalone was set in the document
* @return true if standalone was set in the document, or false otherwise
*/
public boolean standaloneSet();
/**
* Returns the character encoding declared on the xml declaration
* Returns null if none was declared
* @return the encoding declared in the document or null
*/
public String getCharacterEncodingScheme();
/**
* Get the target of a processing instruction
* @return the target
* @throws IllegalStateException if the current event is not a
* {@link XMLStreamConstants#PROCESSING_INSTRUCTION}
*/
public String getPITarget();
/**
* Get the data section of a processing instruction
* @return the data (if processing instruction has any), or null
* if the processing instruction only has target.
* @throws IllegalStateException if the current event is not a
* {@link XMLStreamConstants#PROCESSING_INSTRUCTION}
*/
public String getPIData();
}
stax-1.2.0.orig/src/javax/xml/stream/util/ 0000755 0001750 0001750 00000000000 10444554664 020352 5 ustar twerner twerner stax-1.2.0.orig/src/javax/xml/stream/util/EventReaderDelegate.java 0000644 0001750 0001750 00000004400 10444554664 025052 0 ustar twerner twerner package javax.xml.stream.util;
import javax.xml.namespace.QName;
import javax.xml.namespace.NamespaceContext;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.events.XMLEvent;
import javax.xml.stream.Location;
import javax.xml.stream.XMLStreamException;
/**
* This is the base class for deriving an XMLEventReader
* filter.
*
* This class is designed to sit between an XMLEventReader and an
* application's XMLEventReader. By default each method
* does nothing but call the corresponding method on the
* parent interface.
*
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see javax.xml.stream.XMLEventReader
* @see StreamReaderDelegate
*/
public class EventReaderDelegate implements XMLEventReader {
private XMLEventReader reader;
/**
* Construct an empty filter with no parent.
*/
public EventReaderDelegate(){}
/**
* Construct an filter with the specified parent.
* @param reader the parent
*/
public EventReaderDelegate(XMLEventReader reader) {
this.reader = reader;
}
/**
* Set the parent of this instance.
* @param reader the new parent
*/
public void setParent(XMLEventReader reader) {
this.reader = reader;
}
/**
* Get the parent of this instance.
* @return the parent or null if none is set
*/
public XMLEventReader getParent() {
return reader;
}
public XMLEvent nextEvent()
throws XMLStreamException
{
return reader.nextEvent();
}
public Object next() {
return reader.next();
}
public boolean hasNext()
{
return reader.hasNext();
}
public XMLEvent peek()
throws XMLStreamException
{
return reader.peek();
}
public void close()
throws XMLStreamException
{
reader.close();
}
public String getElementText()
throws XMLStreamException
{
return reader.getElementText();
}
public XMLEvent nextTag()
throws XMLStreamException
{
return reader.nextTag();
}
public Object getProperty(java.lang.String name)
throws java.lang.IllegalArgumentException
{
return reader.getProperty(name);
}
public void remove() {
reader.remove();
}
}
stax-1.2.0.orig/src/javax/xml/stream/util/StreamReaderDelegate.java 0000644 0001750 0001750 00000013313 10444554664 025227 0 ustar twerner twerner package javax.xml.stream.util;
import java.io.Reader;
import javax.xml.namespace.QName;
import javax.xml.namespace.NamespaceContext;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.Location;
import javax.xml.stream.XMLStreamException;
/**
* This is the base class for deriving an XMLStreamReader filter
*
* This class is designed to sit between an XMLStreamReader and an
* application's XMLStreamReader. By default each method
* does nothing but call the corresponding method on the
* parent interface.
*
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see javax.xml.stream.XMLStreamReader
* @see EventReaderDelegate
*/
public class StreamReaderDelegate implements XMLStreamReader {
private XMLStreamReader reader;
/**
* Construct an empty filter with no parent.
*/
public StreamReaderDelegate(){}
/**
* Construct an filter with the specified parent.
* @param reader the parent
*/
public StreamReaderDelegate(XMLStreamReader reader) {
this.reader = reader;
}
/**
* Set the parent of this instance.
* @param reader the new parent
*/
public void setParent(XMLStreamReader reader) {
this.reader = reader;
}
/**
* Get the parent of this instance.
* @return the parent or null if none is set
*/
public XMLStreamReader getParent() {
return reader;
}
public int next()
throws XMLStreamException
{
return reader.next();
}
public int nextTag()
throws XMLStreamException
{
return reader.nextTag();
}
public String getElementText()
throws XMLStreamException
{
return reader.getElementText();
}
public void require(int type, String namespaceURI, String localName)
throws XMLStreamException
{
reader.require(type,namespaceURI,localName);
}
public boolean hasNext()
throws XMLStreamException
{
return reader.hasNext();
}
public void close()
throws XMLStreamException
{
reader.close();
}
public String getNamespaceURI(String prefix)
{
return reader.getNamespaceURI(prefix);
}
public NamespaceContext getNamespaceContext() {
return reader.getNamespaceContext();
}
public boolean isStartElement() {
return reader.isStartElement();
}
public boolean isEndElement() {
return reader.isEndElement();
}
public boolean isCharacters() {
return reader.isCharacters();
}
public boolean isWhiteSpace() {
return reader.isWhiteSpace();
}
public String getAttributeValue(String namespaceUri,
String localName)
{
return reader.getAttributeValue(namespaceUri,localName);
}
public int getAttributeCount() {
return reader.getAttributeCount();
}
public QName getAttributeName(int index) {
return reader.getAttributeName(index);
}
public String getAttributePrefix(int index) {
return reader.getAttributePrefix(index);
}
public String getAttributeNamespace(int index) {
return reader.getAttributeNamespace(index);
}
public String getAttributeLocalName(int index) {
return reader.getAttributeLocalName(index);
}
public String getAttributeType(int index) {
return reader.getAttributeType(index);
}
public String getAttributeValue(int index) {
return reader.getAttributeValue(index);
}
public boolean isAttributeSpecified(int index) {
return reader.isAttributeSpecified(index);
}
public int getNamespaceCount() {
return reader.getNamespaceCount();
}
public String getNamespacePrefix(int index) {
return reader.getNamespacePrefix(index);
}
public String getNamespaceURI(int index) {
return reader.getNamespaceURI(index);
}
public int getEventType() {
return reader.getEventType();
}
public String getText() {
return reader.getText();
}
public int getTextCharacters(int sourceStart,
char[] target,
int targetStart,
int length)
throws XMLStreamException {
return reader.getTextCharacters(sourceStart,
target,
targetStart,
length);
}
public char[] getTextCharacters() {
return reader.getTextCharacters();
}
public int getTextStart() {
return reader.getTextStart();
}
public int getTextLength() {
return reader.getTextLength();
}
public String getEncoding() {
return reader.getEncoding();
}
public boolean hasText() {
return reader.hasText();
}
public Location getLocation() {
return reader.getLocation();
}
public QName getName() {
return reader.getName();
}
public String getLocalName() {
return reader.getLocalName();
}
public boolean hasName() {
return reader.hasName();
}
public String getNamespaceURI() {
return reader.getNamespaceURI();
}
public String getPrefix() {
return reader.getPrefix();
}
public String getVersion() {
return reader.getVersion();
}
public boolean isStandalone() {
return reader.isStandalone();
}
public boolean standaloneSet() {
return reader.standaloneSet();
}
public String getCharacterEncodingScheme() {
return reader.getCharacterEncodingScheme();
}
public String getPITarget() {
return reader.getPITarget();
}
public String getPIData() {
return reader.getPIData();
}
public Object getProperty(String name) {
return reader.getProperty(name);
}
}
stax-1.2.0.orig/src/javax/xml/stream/util/XMLEventAllocator.java 0000644 0001750 0001750 00000003763 10444554664 024531 0 ustar twerner twerner package javax.xml.stream.util;
import javax.xml.stream.events.XMLEvent;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamException;
/**
* This interface defines a class that allows a user to register
* a way to allocate events given an XMLStreamReader. An implementation
* is not required to use the XMLEventFactory implementation but this
* is recommended. The XMLEventAllocator can be set on an XMLInputFactory
* using the property "javax.xml.stream.allocator"
*
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see javax.xml.stream.XMLInputFactory
* @see javax.xml.stream.XMLEventFactory
*/
public interface XMLEventAllocator {
/**
* This method creates an instance of the XMLEventAllocator. This
* allows the XMLInputFactory to allocate a new instance per reader.
*/
public XMLEventAllocator newInstance();
/**
* This method allocates an event given the current
* state of the XMLStreamReader. If this XMLEventAllocator
* does not have a one-to-one mapping between reader states
* and events this method will return null. This method
* must not modify the state of the XMLStreamReader.
* @param reader The XMLStreamReader to allocate from
* @return the event corresponding to the current reader state
*/
public XMLEvent allocate(XMLStreamReader reader)
throws XMLStreamException;
/**
* This method allocates an event or set of events
* given the current
* state of the XMLStreamReader and adds the event
* or set of events to the
* consumer that was passed in. This method can be used
* to expand or contract reader states into event states.
* This method may modify the state of the XMLStreamReader.
* @param reader The XMLStreamReader to allocate from
* @param consumer The XMLEventConsumer to add to.
*/
public void allocate(XMLStreamReader reader, XMLEventConsumer consumer)
throws XMLStreamException;
}
stax-1.2.0.orig/src/javax/xml/stream/util/XMLEventConsumer.java 0000644 0001750 0001750 00000002013 10444554664 024367 0 ustar twerner twerner package javax.xml.stream.util;
import javax.xml.stream.events.XMLEvent;
import javax.xml.stream.XMLStreamException;
/**
* This interface defines an event consumer interface. The contract of the
* of a consumer is to accept the event. This interface can be used to
* mark an object as able to receive events. Add may be called several
* times in immediate succession so a consumer must be able to cache
* events it hasn't processed yet.
*
* @version 1.0
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
*/
public interface XMLEventConsumer {
/**
* This method adds an event to the consumer. Calling this method
* invalidates the event parameter. The client application should
* discard all references to this event upon calling add.
* The behavior of an application that continues to use such references
* is undefined.
*
* @param event the event to add, may not be null
*/
public void add(XMLEvent event)
throws XMLStreamException;
}
stax-1.2.0.orig/src/javax/xml/stream/util/package.html 0000644 0001750 0001750 00000001130 10444554664 022626 0 ustar twerner twerner