stax-1.2.0.orig/0000755000175000017500000000000011224142554013366 5ustar twernertwernerstax-1.2.0.orig/src/0000755000175000017500000000000010444554664014171 5ustar twernertwernerstax-1.2.0.orig/src/test/0000755000175000017500000000000010444554662015146 5ustar twernertwernerstax-1.2.0.orig/src/test/XmlEscapingTest.java0000644000175000017500000000770510444554662021074 0ustar twernertwerner/* * 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/0000755000175000017500000000000010444554662016250 5ustar twernertwernerstax-1.2.0.orig/src/test/files/test.xml0000644000175000017500000000117310444554662017753 0ustar twernertwerner ]> foo bar foo &>< &foo; &bar; &foo;&bar;&foo; ]]> stax-1.2.0.orig/src/samples/0000755000175000017500000000000010444554662015633 5ustar twernertwernerstax-1.2.0.orig/src/samples/TestSerializer2.java0000644000175000017500000000373510444554662021541 0ustar twernertwernerpackage 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.java0000644000175000017500000002024210444554662021714 0ustar twernertwernerpackage 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(" 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.java0000644000175000017500000000210110444554662017700 0ustar twernertwernerpackage 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.java0000644000175000017500000000253510444554662021454 0ustar twernertwernerpackage 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.java0000644000175000017500000000375210444554662021555 0ustar twernertwernerpackage 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.java0000644000175000017500000003032610444554662020102 0ustar twernertwerner// 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(""); 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(""); 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.java0000644000175000017500000000361310444554662022570 0ustar twernertwernerpackage 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/0000755000175000017500000000000010444554662014756 5ustar twernertwernerstax-1.2.0.orig/src/org/codehaus/0000755000175000017500000000000010444554662016551 5ustar twernertwernerstax-1.2.0.orig/src/org/codehaus/stax/0000755000175000017500000000000010444554662017530 5ustar twernertwernerstax-1.2.0.orig/src/org/codehaus/stax/test/0000755000175000017500000000000010444554662020507 5ustar twernertwernerstax-1.2.0.orig/src/org/codehaus/stax/test/evt/0000755000175000017500000000000010444554662021305 5ustar twernertwernerstax-1.2.0.orig/src/org/codehaus/stax/test/evt/TestEventWriter.java0000644000175000017500000001461610444554662025276 0ustar twernertwernerpackage 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.java0000644000175000017500000001147210444554662024671 0ustar twernertwernerpackage 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.java0000644000175000017500000000376610444554662025705 0ustar twernertwernerpackage 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.java0000644000175000017500000004724610444554662025231 0ustar twernertwernerpackage 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.java0000644000175000017500000001271710444554662025126 0ustar twernertwernerpackage 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.java0000644000175000017500000002154510444554662025430 0ustar twernertwernerpackage 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.java0000644000175000017500000002274210444554662024717 0ustar twernertwernerpackage 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/0000755000175000017500000000000010444554662022171 5ustar twernertwernerstax-1.2.0.orig/src/org/codehaus/stax/test/wstream/TestSimpleWriter.java0000644000175000017500000005003010444554662026320 0ustar twernertwernerpackage 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.java0000644000175000017500000000163510444554662025750 0ustar twernertwernerpackage 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.java0000644000175000017500000002162210444554662027014 0ustar twernertwernerpackage 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.java0000644000175000017500000000714210444554662026647 0ustar twernertwernerpackage 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.java0000644000175000017500000000153310444554662024327 0ustar twernertwernerpackage 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/0000755000175000017500000000000010444554662022002 5ustar twernertwernerstax-1.2.0.orig/src/org/codehaus/stax/test/stream/TestStreaming.java0000644000175000017500000000506310444554662025442 0ustar twernertwernerpackage 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.java0000644000175000017500000005620710444554662025576 0ustar twernertwernerpackage 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.java0000644000175000017500000000605210444554662024727 0ustar twernertwernerpackage 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.java0000644000175000017500000003072310444554662025266 0ustar twernertwernerpackage 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" +"" +""; /* 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.java0000644000175000017500000002360010444554662026726 0ustar twernertwernerpackage 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.java0000644000175000017500000002040210444554662025701 0ustar twernertwernerpackage 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.java0000644000175000017500000002563210444554662026111 0ustar twernertwernerpackage 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.java0000644000175000017500000001235610444554662026430 0ustar twernertwernerpackage 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.java0000644000175000017500000002475010444554662025413 0ustar twernertwernerpackage 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.java0000644000175000017500000001643110444554662024405 0ustar twernertwernerpackage 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.java0000644000175000017500000000406610444554662026374 0ustar twernertwernerpackage 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.java0000644000175000017500000002343310444554662026231 0ustar twernertwernerpackage 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.java0000644000175000017500000005233510444554662025565 0ustar twernertwernerpackage 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.java0000644000175000017500000002014310444554662025704 0ustar twernertwernerpackage 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.java0000644000175000017500000001511310444554662026030 0ustar twernertwernerpackage 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.java0000644000175000017500000000162310444554662025553 0ustar twernertwernerpackage 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.java0000644000175000017500000001130510444554662025533 0ustar twernertwernerpackage 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.java0000644000175000017500000002557710444554662026264 0ustar twernertwernerpackage 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.java0000644000175000017500000001617510444554662025047 0ustar twernertwernerpackage 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.java0000644000175000017500000001300310444554662025252 0ustar twernertwernerpackage 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/0000755000175000017500000000000010444554662022170 5ustar twernertwernerstax-1.2.0.orig/src/org/codehaus/stax/test/vstream/TestEnumAttrRead.java0000644000175000017500000001023310444554662026225 0ustar twernertwernerpackage 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.java0000644000175000017500000000522210444554662026644 0ustar twernertwernerpackage 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.java0000644000175000017500000001150610444554662026700 0ustar twernertwernerpackage 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.java0000644000175000017500000000631510444554662027330 0ustar twernertwernerpackage 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.java0000644000175000017500000001605110444554662026601 0ustar twernertwernerpackage 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.java0000644000175000017500000000667210444554662025645 0ustar twernertwernerpackage 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.java0000644000175000017500000000251410444554662026051 0ustar twernertwernerpackage 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.java0000644000175000017500000000320610444554662026441 0ustar twernertwernerpackage 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.java0000644000175000017500000001030510444554662025440 0ustar twernertwernerpackage 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.java0000644000175000017500000004021110444554662030054 0ustar twernertwernerpackage 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.java0000644000175000017500000000704210444554662025620 0ustar twernertwernerpackage 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.java0000644000175000017500000000707210444554662025713 0ustar twernertwernerpackage 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.java0000644000175000017500000002045710444554662025666 0ustar twernertwernerpackage 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.java0000644000175000017500000001130510444554662027115 0ustar twernertwernerpackage 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.java0000644000175000017500000002133310444554662025403 0ustar twernertwernerpackage 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.java0000644000175000017500000004514110444554662023731 0ustar twernertwernerpackage 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/0000755000175000017500000000000010444554662015300 5ustar twernertwernerstax-1.2.0.orig/src/javax/xml/0000755000175000017500000000000010444554664016102 5ustar twernertwernerstax-1.2.0.orig/src/javax/xml/XMLConstants.java0000644000175000017500000000550710444554664021311 0ustar twernertwerner// $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/0000755000175000017500000000000010444554664017375 5ustar twernertwernerstax-1.2.0.orig/src/javax/xml/stream/XMLReporter.java0000644000175000017500000000163210444554664022425 0ustar twernertwernerpackage 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.java0000644000175000017500000000465710444554664023747 0ustar twernertwernerpackage 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.java0000644000175000017500000000116010444554664022465 0ustar twernertwernerpackage 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.java0000644000175000017500000002051610444554664023455 0ustar twernertwernerpackage 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 NameBehaviorReturn typeDefault ValueRequired
javax.xml.stream.isRepairingNamespacesdefaults prefixes on the output sideBooleanFalseYes
* *

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.java0000644000175000017500000003222110444554664023251 0ustar twernertwernerpackage 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.java0000644000175000017500000001562210444554664023005 0ustar twernertwernerpackage 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/0000755000175000017500000000000010444554664020701 5ustar twernertwernerstax-1.2.0.orig/src/javax/xml/stream/events/Characters.java0000644000175000017500000000271410444554662023625 0ustar twernertwernerpackage 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.java0000644000175000017500000000220210444554664024334 0ustar twernertwernerpackage 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.java0000644000175000017500000000045610444554664023756 0ustar twernertwernerpackage 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.java0000644000175000017500000000571010444554664024156 0ustar twernertwernerpackage 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.java0000644000175000017500000000215010444554664023505 0ustar twernertwernerpackage 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.java0000644000175000017500000001025110444554664023205 0ustar twernertwernerpackage 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.java0000644000175000017500000000141610444554662023564 0ustar twernertwernerpackage 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.java0000644000175000017500000000254410444554664022164 0ustar twernertwernerpackage 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.java0000644000175000017500000000151310444554662025503 0ustar twernertwernerpackage 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.java0000644000175000017500000000054510444554664023152 0ustar twernertwernerpackage 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.java0000644000175000017500000000216510444554664024643 0ustar twernertwernerpackage 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.html0000644000175000017500000000074710444554664023172 0ustar twernertwerner Describes a set of events for processing XML

Related Documentation

stax-1.2.0.orig/src/javax/xml/stream/events/ProcessingInstruction.java0000644000175000017500000000111110444554664026114 0ustar twernertwernerpackage 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.java0000644000175000017500000000133510444554664023442 0ustar twernertwernerpackage 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.java0000644000175000017500000000231310444554664025165 0ustar twernertwernerpackage 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.java0000644000175000017500000006625310444554664023213 0ustar twernertwernerpackage 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(); * *

The next() method causes the reader to read the next parse event. * The next() method returns an integer which identifies the type of event just read. *

The event type can be determined using getEventType(). *

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. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Valid methods for each state *
Event TypeValid Methods
All States getProperty(), hasNext(), require(), close(), * getNamespaceURI(), isStartElement(), * isEndElement(), isCharacters(), isWhiteSpace(), * getNamespaceContext(), getEventType(),getLocation(), * hasText(), hasName() *
START_ELEMENT next(), getName(), getLocalName(), hasName(), getPrefix(), * getAttributeXXX(), isAttributeSpecified(), * getNamespaceXXX(), * getElementText(), nextTag() *
ATTRIBUTE next(), nextTag() * getAttributeXXX(), isAttributeSpecified(), *
NAMESPACE next(), nextTag() * getNamespaceXXX() *
END_ELEMENT next(), getName(), getLocalName(), hasName(), getPrefix(), * getNamespaceXXX(), nextTag() *
CHARACTERS next(), getTextXXX(), nextTag()
CDATA next(), getTextXXX(), nextTag()
COMMENT next(), getTextXXX(), nextTag()
SPACE next(), getTextXXX(), nextTag()
START_DOCUMENT next(), getEncoding(), getVersion(), isStandalone(), standaloneSet(), * getCharacterEncodingScheme(), nextTag()
END_DOCUMENT close()
PROCESSING_INSTRUCTION next(), getPITarget(), getPIData(), nextTag()
ENTITY_REFERENCE next(), getLocalName(), getText(), nextTag()
DTD next(), getText(), nextTag()
* * @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. * *

Given the following XML:
* <foo><!--description-->content text<![CDATA[<greeting>Hello</greeting>]]>other content</foo>
* The behavior of calling next() when being on foo will be:
* 1- the comment (COMMENT)
* 2- then the characters section (CHARACTERS)
* 3- then the CDATA section (another CHARACTERS)
* 4- then the next characters section (another CHARACTERS)
* 5- then the END_ELEMENT
* *

NOTE: empty element (such as <tag/>) will be reported * with two separate events: START_ELEMENT, END_ELEMENT - This preserves * parsing equivalency of empty element to <tag></tag>. * * This method will throw an IllegalStateException if it is called after hasNext() returns false. * @see javax.xml.stream.events.XMLEvent * @return the integer code corresponding to the current parse event * @throws NoSuchElementException if this is called when hasNext() returns false * @throws XMLStreamException if there is an error processing the underlying XML source */ public int next() throws XMLStreamException; /** * Test if the current event is of the given type and if the namespace and name match the current * namespace and name of the current event. If the namespaceURI is null it is not checked for equality, * if the localName is null it is not checked for equality. * @param type the event type * @param namespaceURI the uri of the event, may be null * @param localName the localName of the event, may be null * @throws XMLStreamException if the required values are not matched. */ public void require(int type, String namespaceURI, String localName) throws XMLStreamException; /** * Reads the content of a text-only element, an exception is thrown if this is * not a text-only element. * Regardless of value of javax.xml.stream.isCoalescing this method always returns coalesced content. *
Precondition: the current event is START_ELEMENT. *
Postcondition: the current event is the corresponding END_ELEMENT. * *
The method does the following (implementations are free to optimized * but must do equivalent processing): *

   * if(getEventType() != XMLStreamConstants.START_ELEMENT) {
   * throw new XMLStreamException(
   * "parser must be on START_ELEMENT to read next text", getLocation());
   * }
   * int eventType = next();
   * StringBuffer content = new StringBuffer();
   * while(eventType != XMLStreamConstants.END_ELEMENT ) {
   * if(eventType == XMLStreamConstants.CHARACTERS
   * || eventType == XMLStreamConstants.CDATA
   * || eventType == XMLStreamConstants.SPACE
   * || eventType == XMLStreamConstants.ENTITY_REFERENCE) {
   * buf.append(getText());
   * } else if(eventType == XMLStreamConstants.PROCESSING_INSTRUCTION
   * || eventType == XMLStreamConstants.COMMENT) {
   * // skipping
   * } else if(eventType == XMLStreamConstants.END_DOCUMENT) {
   * throw new XMLStreamException(
   * "unexpected end of document when reading element text content", this);
   * } else if(eventType == XMLStreamConstants.START_ELEMENT) {
   * throw new XMLStreamException(
   * "element text content may not contain START_ELEMENT", getLocation());
   * } else {
   * throw new XMLStreamException(
   * "Unexpected event type "+eventType, getLocation());
   * }
   * eventType = next();
   * }
   * return buf.toString();
   * 
* * @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): *
   * int eventType = next();
   * while((eventType == XMLStreamConstants.CHARACTERS && isWhiteSpace()) // skip whitespace
   * || (eventType == XMLStreamConstants.CDATA && isWhiteSpace()) 
   * // skip whitespace
   * || eventType == XMLStreamConstants.SPACE
   * || eventType == XMLStreamConstants.PROCESSING_INSTRUCTION
   * || eventType == XMLStreamConstants.COMMENT
   * ) {
   * eventType = next();
   * }
   * if (eventType != XMLStreamConstants.START_ELEMENT && eventType != XMLStreamConstants.END_ELEMENT) {
   * throw new String XMLStreamException("expected start or end tag", getLocation());
   * }
   * return eventType;
   * 
* * @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. * *

NOTE:The 'xml' prefix is bound as defined in * Namespaces in XML * specification to "http://www.w3.org/XML/1998/namespace". * *

NOTE: The 'xmlns' prefix must be resolved to following namespace * http://www.w3.org/2000/xmlns/ * @param prefix The prefix to lookup, may not be null * @return the uri bound to the given prefix or null if it is not bound * @throws IllegalArgumentException if the prefix is null */ public String getNamespaceURI(String prefix); /** * Returns true if the cursor points to a start tag (otherwise false) * @return true if the cursor points to a start tag, false otherwise */ public boolean isStartElement(); /** * Returns true if the cursor points to an end tag (otherwise false) * @return true if the cursor points to an end tag, false otherwise */ public boolean isEndElement(); /** * Returns true if the cursor points to a character data event * @return true if the cursor points to character data, false otherwise */ public boolean isCharacters(); /** * Returns true if the cursor points to a character data event * that consists of all whitespace * @return true if the cursor points to all whitespace, false otherwise */ public boolean isWhiteSpace(); /** * Returns the normalized attribute value of the * attribute with the namespace and localName * If the namespaceURI is null the namespace * is not checked for equality * @param namespaceURI the namespace of the attribute * @param localName the local name of the attribute, cannot be null * @return returns the value of the attribute , returns null if not found * @throws IllegalStateException if this is not a START_ELEMENT or ATTRIBUTE */ public String getAttributeValue(String namespaceURI, String localName); /** * Returns the count of attributes on this START_ELEMENT, * this method is only valid on a START_ELEMENT or ATTRIBUTE. This * count excludes namespace definitions. Attribute indices are * zero-based. * @return returns the number of attributes * @throws IllegalStateException if this is not a START_ELEMENT or ATTRIBUTE */ public int getAttributeCount(); /** Returns the qname of the attribute at the provided index * * @param index the position of the attribute * @return the QName of the attribute * @throws IllegalStateException if this is not a START_ELEMENT or ATTRIBUTE */ public QName getAttributeName(int index); /** * Returns the namespace of the attribute at the provided * index * @param index the position of the attribute * @return the namespace URI (can be null) * @throws IllegalStateException if this is not a START_ELEMENT or ATTRIBUTE */ public String getAttributeNamespace(int index); /** * Returns the localName of the attribute at the provided * index * @param index the position of the attribute * @return the localName of the attribute * @throws IllegalStateException if this is not a START_ELEMENT or ATTRIBUTE */ public String getAttributeLocalName(int index); /** * Returns the prefix of this attribute at the * provided index * @param index the position of the attribute * @return the prefix of the attribute * @throws IllegalStateException if this is not a START_ELEMENT or ATTRIBUTE */ public String getAttributePrefix(int index); /** * Returns the XML type of the attribute at the provided * index * @param index the position of the attribute * @return the XML type of the attribute * @throws IllegalStateException if this is not a START_ELEMENT or ATTRIBUTE */ public String getAttributeType(int index); /** * Returns the value of the attribute at the * index * @param index the position of the attribute * @return the attribute value * @throws IllegalStateException if this is not a START_ELEMENT or ATTRIBUTE */ public String getAttributeValue(int index); /** * Returns a boolean which indicates if this * attribute was created by default * @param index the position of the attribute * @return true if this is a default attribute * @throws IllegalStateException if this is not a START_ELEMENT or ATTRIBUTE */ public boolean isAttributeSpecified(int index); /** * Returns the count of namespaces declared on this START_ELEMENT or END_ELEMENT. * This method is only valid on a START_ELEMENT, END_ELEMENT or NAMESPACE. * On an END_ELEMENT the count is of the namespaces that are about to go * out of scope. This is the equivalent of the information reported * by SAX callback for an end element event. * @return returns the number of namespace declarations on this specific element * @throws IllegalStateException if this is not a START_ELEMEN or, END_ELEMENT */ public int getNamespaceCount(); /** * Returns the prefix for the namespace declared at the * index. Returns null if this is the default namespace * declaration * * @param index the position of the namespace declaration * @return returns the namespace prefix * @throws IllegalStateException if this is not a START_ELEMENT, * END_ELEMENT or NAMESPACE */ public String getNamespacePrefix(int index); /** * Returns the uri for the namespace declared at the * index. * * @param index the position of the namespace declaration * @return returns the namespace uri * @throws IllegalStateException if this is not a START_ELEMENT, * END_ELEMENT or NAMESPACE */ public String getNamespaceURI(int index); /** * Returns a read only namespace context for the current * position. The context is transient and only valid until * a call to next() changes the state of the reader. * @return return a namespace context */ public NamespaceContext getNamespaceContext(); /** * Returns a reader that points to the current start element * and all of its contents. Throws an XMLStreamException if the * cursor does not point to a START_ELEMENT.

* 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/0000755000175000017500000000000010444554664020352 5ustar twernertwernerstax-1.2.0.orig/src/javax/xml/stream/util/EventReaderDelegate.java0000644000175000017500000000440010444554664025052 0ustar twernertwernerpackage 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.java0000644000175000017500000001331310444554664025227 0ustar twernertwernerpackage 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.java0000644000175000017500000000376310444554664024531 0ustar twernertwernerpackage 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.java0000644000175000017500000000201310444554664024367 0ustar twernertwernerpackage 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.html0000644000175000017500000000113010444554664022626 0ustar twernertwerner 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/XMLEventFactory.java0000644000175000017500000003177410444554664023246 0ustar twernertwernerpackage javax.xml.stream; import javax.xml.stream.events.*; import javax.xml.namespace.NamespaceContext; import javax.xml.namespace.QName; import java.util.Iterator; /** * This interface defines a utility class for creating instances of * XMLEvents * @version 1.0 * @author Copyright (c) 2003 by BEA Systems. All Rights Reserved. * @see javax.xml.stream.events.StartElement * @see javax.xml.stream.events.EndElement * @see javax.xml.stream.events.ProcessingInstruction * @see javax.xml.stream.events.Comment * @see javax.xml.stream.events.Characters * @see javax.xml.stream.events.StartDocument * @see javax.xml.stream.events.EndDocument * @see javax.xml.stream.events.DTD */ public abstract class XMLEventFactory { protected XMLEventFactory(){} /** * Create a new instance of the factory * @throws FactoryConfigurationError if an instance of this factory cannot be loaded */ public static XMLEventFactory newInstance() throws FactoryConfigurationError { return (XMLEventFactory) FactoryFinder.find( "javax.xml.stream.XMLEventFactory", "com.bea.xml.stream.EventFactory"); } /** * Create a new instance of the factory * * @param factoryId Name of the factory to find, same as * a property name * @param classLoader classLoader to use * @return the factory implementation * @throws FactoryConfigurationError if an instance of this factory cannot be loaded */ public static XMLEventFactory newInstance(String factoryId, ClassLoader classLoader) throws FactoryConfigurationError { return (XMLEventFactory) FactoryFinder.find( factoryId, "com.bea.xml.stream.EventFactory", classLoader); } /** * This method allows setting of the Location on each event that * is created by this factory. The values are copied by value into * the events created by this factory. To reset the location * information set the location to null. * @param location the location to set on each event created */ public abstract void setLocation(Location location); /** * Create a new Attribute * @param prefix the prefix of this attribute, may not be null * @param namespaceURI the attribute value is set to this value, may not be null * @param localName the local name of the XML name of the attribute, localName cannot be null * @param value the attribute value to set, may not be null * @return the Attribute with specified values */ public abstract Attribute createAttribute(String prefix, String namespaceURI, String localName, String value); /** * Create a new Attribute * @param localName the local name of the XML name of the attribute, localName cannot be null * @param value the attribute value to set, may not be null * @return the Attribute with specified values */ public abstract Attribute createAttribute(String localName, String value); /** * Create a new Attribute * @param name the qualified name of the attribute, may not be null * @param value the attribute value to set, may not be null * @return the Attribute with specified values */ public abstract Attribute createAttribute(QName name, String value); /** * Create a new default Namespace * @param namespaceURI the default namespace uri * @return the Namespace with the specified value */ public abstract Namespace createNamespace(String namespaceURI); /** * Create a new Namespace * @param prefix the prefix of this namespace, may not be null * @param namespaceUri the attribute value is set to this value, may not be null * @return the Namespace with the specified values */ public abstract Namespace createNamespace(String prefix, String namespaceUri); /** * Create a new StartElement. Namespaces can be added to this StartElement * by passing in an Iterator that walks over a set of Namespace interfaces. * Attributes can be added to this StartElement by passing an iterator * that walks over a set of Attribute interfaces. * * @param name the qualified name of the attribute, may not be null * @param attributes an optional unordered set of objects that * implement Attribute to add to the new StartElement, may be null * @param namespaces an optional unordered set of objects that * implement Namespace to add to the new StartElement, may be null * @return an instance of the requested StartElement */ public abstract StartElement createStartElement(QName name, Iterator attributes, Iterator namespaces); /** * Create a new StartElement. This defaults the NamespaceContext to * an empty NamespaceContext. Querying this event for its namespaces or * attributes will result in an empty iterator being returned. * * @param namespaceUri the uri of the QName of the new StartElement * @param localName the local name of the QName of the new StartElement * @param prefix the prefix of the QName of the new StartElement * @return an instance of the requested StartElement */ public abstract StartElement createStartElement(String prefix, String namespaceUri, String localName); /** * Create a new StartElement. Namespaces can be added to this StartElement * by passing in an Iterator that walks over a set of Namespace interfaces. * Attributes can be added to this StartElement by passing an iterator * that walks over a set of Attribute interfaces. * * @param namespaceUri the uri of the QName of the new StartElement * @param localName the local name of the QName of the new StartElement * @param prefix the prefix of the QName of the new StartElement * @param attributes an unordered set of objects that implement * Attribute to add to the new StartElement * @param namespaces an unordered set of objects that implement * Namespace to add to the new StartElement * @return an instance of the requested StartElement */ public abstract StartElement createStartElement(String prefix, String namespaceUri, String localName, Iterator attributes, Iterator namespaces ); /** * Create a new StartElement. Namespaces can be added to this StartElement * by passing in an Iterator that walks over a set of Namespace interfaces. * Attributes can be added to this StartElement by passing an iterator * that walks over a set of Attribute interfaces. * * @param namespaceUri the uri of the QName of the new StartElement * @param localName the local name of the QName of the new StartElement * @param prefix the prefix of the QName of the new StartElement * @param attributes an unordered set of objects that implement * Attribute to add to the new StartElement, may be null * @param namespaces an unordered set of objects that implement * Namespace to add to the new StartElement, may be null * @param context the namespace context of this element * @return an instance of the requested StartElement */ public abstract StartElement createStartElement(String prefix, String namespaceUri, String localName, Iterator attributes, Iterator namespaces, NamespaceContext context ); /** * Create a new EndElement * @param name the qualified name of the EndElement * @param namespaces an optional unordered set of objects that * implement Namespace that have gone out of scope, may be null * @return an instance of the requested EndElement */ public abstract EndElement createEndElement(QName name, Iterator namespaces); /** * Create a new EndElement * @param namespaceUri the uri of the QName of the new EndElement * @param localName the local name of the QName of the new StartElement * @param prefix the prefix of the QName of the new StartElement * @return an instance of the requested EndElement */ public abstract EndElement createEndElement(String prefix, String namespaceUri, String localName); /** * Create a new EndElement * @param namespaceUri the uri of the QName of the new EndElement * @param localName the local name of the QName of the new StartElement * @param prefix the prefix of the QName of the new StartElement * @param namespaces an unordered set of objects that implement * Namespace that have gone out of scope, may be null * @return an instance of the requested EndElement */ public abstract EndElement createEndElement(String prefix, String namespaceUri, String localName, Iterator namespaces); /** * Create a Characters event, this method does not check if the content * is all whitespace. To create a space event use #createSpace(String) * @param content the string to create * @return a Characters event */ public abstract Characters createCharacters(String content); /** * Create a Characters event with the CData flag set to true * @param content the string to create * @return a Characters event */ public abstract Characters createCData(String content); /** * Create a Characters event with the isSpace flag set to true * @param content the content of the space to create * @return a Characters event */ public abstract Characters createSpace(String content); /** * Create an ignorable space * @param content the space to create * @return a Characters event */ public abstract Characters createIgnorableSpace(String content); /** * Creates a new instance of a StartDocument event * @return a StartDocument event */ public abstract StartDocument createStartDocument(); /** * Creates a new instance of a StartDocument event * * @param encoding the encoding style * @param version the XML version * @param standalone the status of standalone may be set to "true" or "false" * @return a StartDocument event */ public abstract StartDocument createStartDocument(String encoding, String version, boolean standalone); /** * Creates a new instance of a StartDocument event * * @param encoding the encoding style * @param version the XML version * @return a StartDocument event */ public abstract StartDocument createStartDocument(String encoding, String version); /** * Creates a new instance of a StartDocument event * * @param encoding the encoding style * @return a StartDocument event */ public abstract StartDocument createStartDocument(String encoding); /** * Creates a new instance of an EndDocument event * @return an EndDocument event */ public abstract EndDocument createEndDocument(); /** Creates a new instance of a EntityReference event * * @param name The name of the reference * @param declaration the declaration for the event * @return an EntityReference event */ public abstract EntityReference createEntityReference(String name, EntityDeclaration declaration); /** * Create a comment * @param text The text of the comment * a Comment event */ public abstract Comment createComment(String text); /** * Create a processing instruction * @param target The target of the processing instruction * @param data The text of the processing instruction * @return a ProcessingInstruction event */ public abstract ProcessingInstruction createProcessingInstruction(String target, String data); /** * Create a document type definition event * This string contains the entire document type declaration that matches * the doctypedecl in the XML 1.0 specification * @param dtd the text of the document type definition * @return a DTD event */ public abstract DTD createDTD(String dtd); } stax-1.2.0.orig/src/javax/xml/stream/Location.java0000644000175000017500000000260110444554664022007 0ustar twernertwernerpackage javax.xml.stream; /** * Provides information on the location of an event. * * All the information provided by a Location is optional. For example * an application may only report line numbers. * * @version 1.0 * @author Copyright (c) 2003 by BEA Systems. All Rights Reserved. */ public interface Location { /** * Return the line number where the current event ends, * returns -1 if none is available. * @return the current line number */ int getLineNumber(); /** * Return the column number where the current event ends, * returns -1 if none is available. * @return the current column number */ int getColumnNumber(); /** * Return the byte or character offset into the input source this location * is pointing to. If the input source is a file or a byte stream then * this is the byte offset into that stream, but if the input source is * a character media then the offset is the character offset. * Returns -1 if there is no offset available. * @return the current offset */ int getCharacterOffset(); /** * Returns the public ID of the XML * @return the public ID, or null if not available */ public String getPublicId(); /** * Returns the system ID of the XML * @return the system ID, or null if not available */ public String getSystemId(); } stax-1.2.0.orig/src/javax/xml/stream/FactoryConfigurationError.java0000644000175000017500000000365010444554664025415 0ustar twernertwernerpackage javax.xml.stream; /** * An error class for reporting factory configuration errors. * * @version 1.0 * @author Copyright (c) 2003 by BEA Systems. All Rights Reserved. */ public class FactoryConfigurationError extends Error { Exception nested; /** * Default constructor */ public FactoryConfigurationError(){} /** * Construct an exception with a nested inner exception * * @param e the exception to nest */ public FactoryConfigurationError(java.lang.Exception e){ nested = e; } /** * Construct an exception with a nested inner exception * and a message * * @param e the exception to nest * @param msg the message to report */ public FactoryConfigurationError(java.lang.Exception e, java.lang.String msg){ super(msg); nested = e; } /** * Construct an exception with a nested inner exception * and a message * * @param msg the message to report * @param e the exception to nest */ public FactoryConfigurationError(java.lang.String msg, java.lang.Exception e){ super(msg); nested = e; } /** * Construct an exception with associated message * * @param e the exception to nest * @param msg the message to report */ public FactoryConfigurationError(java.lang.String msg){ super(msg); } /** * Return the nested exception (if any) * * @return the nested exception or null */ public Exception getException() { return nested; } /** * Report the message associated with this error * * @return the string value of the message */ public String getMessage() { String msg = super.getMessage(); if(msg != null) return msg; if(nested != null){ msg = nested.getMessage(); if(msg == null) msg = nested.getClass().toString(); } return msg; } } stax-1.2.0.orig/src/javax/xml/stream/XMLResolver.java0000644000175000017500000000263410444554664022427 0ustar twernertwernerpackage javax.xml.stream; /** * This interface is used to resolve resources during an XML parse. If an application wishes to * perform custom entity resolution it must register an instance of this interface with * the XMLInputFactory using the setXMLResolver method. * * @version 1.0 * @author Copyright (c) 2003 by BEA Systems. All Rights Reserved. */ public interface XMLResolver { /** * Retrieves a resource. This resource can be of the following three return types: * (1) java.io.InputStream (2) javax.xml.stream.XMLStreamReader (3) java.xml.stream.XMLEventReader. * If this method returns null the processor will attempt to resolve the entity using its * default mechanism. * * @param publicID The public identifier of the external entity being referenced, or null if none was supplied. * @param systemID The system identifier of the external entity being referenced. * @param baseURI Absolute base URI associated with systemId. * @param namespace The namespace of the entity to resolve. * @return The resource requested or null. * @throws XMLStreamException if there was a failure attempting to resolve the resource. */ public Object resolveEntity(String publicID, String systemID, String baseURI, String namespace) throws XMLStreamException; } stax-1.2.0.orig/src/javax/xml/stream/XMLStreamConstants.java0000644000175000017500000000520410444554664023752 0ustar twernertwernerpackage javax.xml.stream; /** * This interface declares the constants used in this API. * Numbers in the range 0 to 256 are reserved for the specification, * user defined events must use event codes outside that range. */ public interface XMLStreamConstants { /** * Indicates an event is a start element * @see javax.xml.stream.events.StartElement */ public static final int START_ELEMENT=1; /** * Indicates an event is an end element * @see javax.xml.stream.events.EndElement */ public static final int END_ELEMENT=2; /** * Indicates an event is a processing instruction * @see javax.xml.stream.events.ProcessingInstruction */ public static final int PROCESSING_INSTRUCTION=3; /** * Indicates an event is characters * @see javax.xml.stream.events.Characters */ public static final int CHARACTERS=4; /** * Indicates an event is a comment * @see javax.xml.stream.events.Comment */ public static final int COMMENT=5; /** * The characters are white space * (see [XML], 2.10 "White Space Handling"). * Events are only reported as SPACE if they are ignorable white * space. Otherwise they are reported as CHARACTERS. * @see javax.xml.stream.events.Characters */ public static final int SPACE=6; /** * Indicates an event is a start document * @see javax.xml.stream.events.StartDocument */ public static final int START_DOCUMENT=7; /** * Indicates an event is an end document * @see javax.xml.stream.events.EndDocument */ public static final int END_DOCUMENT=8; /** * Indicates an event is an entity reference * @see javax.xml.stream.events.EntityReference */ public static final int ENTITY_REFERENCE=9; /** * Indicates an event is an attribute * @see javax.xml.stream.events.Attribute */ public static final int ATTRIBUTE=10; /** * Indicates an event is a DTD * @see javax.xml.stream.events.DTD */ public static final int DTD=11; /** * Indicates an event is a CDATA section * @see javax.xml.stream.events.Characters */ public static final int CDATA=12; /** * Indicates the event is a namespace declaration * * @see javax.xml.stream.events.Namespace */ public static final int NAMESPACE=13; /** * Indicates a Notation * @see javax.xml.stream.events.NotationDeclaration */ public static final int NOTATION_DECLARATION=14; /** * Indicates a Entity Declaration * @see javax.xml.stream.events.NotationDeclaration */ public static final int ENTITY_DECLARATION=15; } stax-1.2.0.orig/src/javax/xml/stream/package.html0000644000175000017500000000113410444554664021655 0ustar twernertwerner Provides an API for processing XML as a stream

Package Specification

This package describes a set of APIs for processing XML in an iterative fashion.

Related Documentation

stax-1.2.0.orig/src/javax/xml/stream/XMLInputFactory.java0000644000175000017500000003351610444554664023260 0ustar twernertwernerpackage javax.xml.stream; import javax.xml.transform.Source; import javax.xml.stream.util.XMLEventAllocator; /** * Defines an abstract implementation of a factory for getting streams. * * 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 NameBehaviorReturn typeDefault ValueRequired
javax.xml.stream.isValidatingTurns on/off implementation specific DTD validationBooleanFalseNo
javax.xml.stream.isNamespaceAwareTurns on/off namespace processing for XML 1.0 supportBooleanTrueTrue (required) / False (optional)
javax.xml.stream.isCoalescingRequires the processor to coalesce adjacent character dataBooleanFalseYes
javax.xml.stream.isReplacingEntityReferencesreplace internal entity references with their replacement text and report them as charactersBooleanTrueYes
javax.xml.stream.isSupportingExternalEntitiesResolve external parsed entitiesBooleanUnspecifiedYes
javax.xml.stream.supportDTDUse this property to request processors that do not support DTDsBooleanTrueYes
javax.xml.stream.reportersets/gets the impl of the XMLReporter javax.xml.stream.XMLReporterNullYes
javax.xml.stream.resolversets/gets the impl of the XMLResolver interfacejavax.xml.stream.XMLResolverNullYes
javax.xml.stream.allocatorsets/gets the impl of the XMLEventAllocator interfacejavax.xml.stream.util.XMLEventAllocatorNullYes
* * * @version 1.0 * @author Copyright (c) 2003 by BEA Systems. All Rights Reserved. * @see XMLOutputFactory * @see XMLEventReader * @see XMLStreamReader * @see EventFilter * @see XMLReporter * @see XMLResolver * @see javax.xml.stream.util.XMLEventAllocator */ public abstract class XMLInputFactory { /** * The property used to turn on/off namespace support, * this is to support XML 1.0 documents, * only the true setting must be supported */ public static final String IS_NAMESPACE_AWARE= "javax.xml.stream.isNamespaceAware"; /** * The property used to turn on/off implementation specific validation */ public static final String IS_VALIDATING= "javax.xml.stream.isValidating"; /** * The property that requires the parser to coalesce adjacent character data sections */ public static final String IS_COALESCING= "javax.xml.stream.isCoalescing"; /** * Requires the parser to replace internal * entity references with their replacement * text and report them as characters */ public static final String IS_REPLACING_ENTITY_REFERENCES= "javax.xml.stream.isReplacingEntityReferences"; /** * The property that requires the parser to resolve external parsed entities */ public static final String IS_SUPPORTING_EXTERNAL_ENTITIES= "javax.xml.stream.isSupportingExternalEntities"; /** * The property that requires the parser to support DTDs */ public static final String SUPPORT_DTD= "javax.xml.stream.supportDTD"; /** * The property used to * set/get the implementation of the XMLReporter interface */ public static final String REPORTER= "javax.xml.stream.reporter"; /** * The property used to set/get the implementation of the XMLResolver */ public static final String RESOLVER= "javax.xml.stream.resolver"; /** * The property used to set/get the implementation of the allocator */ public static final String ALLOCATOR= "javax.xml.stream.allocator"; protected XMLInputFactory(){} /** * Create a new instance of the factory. * This static method creates a new factory instance. * This method uses the following ordered lookup procedure to determine * the XMLInputFactory implementation class to load: * Use the javax.xml.stream.XMLInputFactory system property. * Use the properties file "lib/stax.properties" in the JRE directory. * This configuration file is in standard java.util.Properties format and contains * the fully qualified name of the implementation class with the key being the system property defined above. * Use the Services API (as detailed in the JAR specification), if available, to determine the classname. * The Services API will look for a classname in the file META-INF/services/javax.xml.stream.XMLInputFactory * in jars available to the runtime. * Platform default XMLInputFactory instance. * Once an application has obtained a reference to a XMLInputFactory * it can use the factory to configure and obtain stream instances. * * @throws FactoryConfigurationError if an instance of this factory cannot be loaded */ public static XMLInputFactory newInstance() throws FactoryConfigurationError { return (XMLInputFactory) FactoryFinder.find( "javax.xml.stream.XMLInputFactory", "com.bea.xml.stream.MXParserFactory"); } /** * Create a new instance of the factory * * @param factoryId Name of the factory to find, same as * a property name * @param classLoader classLoader to use * @return the factory implementation * @throws FactoryConfigurationError if an instance of this factory cannot be loaded */ public static XMLInputFactory newInstance(String factoryId, ClassLoader classLoader) throws FactoryConfigurationError { return (XMLInputFactory) FactoryFinder.find( factoryId, "com.bea.xml.stream.MXParserFactory", classLoader); } /** * Create a new XMLStreamReader from a reader * @param reader the XML data to read from * @throws XMLStreamException */ public abstract XMLStreamReader createXMLStreamReader(java.io.Reader reader) throws XMLStreamException; /** * Create a new XMLStreamReader from a JAXP source. This method is optional. * @param source the source to read from * @throws UnsupportedOperationException if this method is not * supported by this XMLInputFactory * @throws XMLStreamException */ public abstract XMLStreamReader createXMLStreamReader(Source source) throws XMLStreamException; /** * Create a new XMLStreamReader from a java.io.InputStream * @param stream the InputStream to read from * @throws XMLStreamException */ public abstract XMLStreamReader createXMLStreamReader(java.io.InputStream stream) throws XMLStreamException; /** * Create a new XMLStreamReader from a java.io.InputStream * @param stream the InputStream to read from * @param encoding the character encoding of the stream * @throws XMLStreamException */ public abstract XMLStreamReader createXMLStreamReader(java.io.InputStream stream, String encoding) throws XMLStreamException; /** * Create a new XMLStreamReader from a java.io.InputStream * @param systemId the system ID of the stream * @param stream the InputStream to read from */ public abstract XMLStreamReader createXMLStreamReader(String systemId, java.io.InputStream stream) throws XMLStreamException; /** * Create a new XMLStreamReader from a java.io.InputStream * @param systemId the system ID of the stream * @param reader the InputStream to read from */ public abstract XMLStreamReader createXMLStreamReader(String systemId, java.io.Reader reader) throws XMLStreamException; /** * Create a new XMLEventReader from a reader * @param reader the XML data to read from * @throws XMLStreamException */ public abstract XMLEventReader createXMLEventReader(java.io.Reader reader) throws XMLStreamException; /** * Create a new XMLEventReader from a reader * @param systemId the system ID of the input * @param reader the XML data to read from * @throws XMLStreamException */ public abstract XMLEventReader createXMLEventReader(String systemId, java.io.Reader reader) throws XMLStreamException; /** * Create a new XMLEventReader from an XMLStreamReader. After being used * to construct the XMLEventReader instance returned from this method * the XMLStreamReader must not be used. * @param reader the XMLStreamReader to read from (may not be modified) * @return a new XMLEventReader * @throws XMLStreamException */ public abstract XMLEventReader createXMLEventReader(XMLStreamReader reader) throws XMLStreamException; /** * Create a new XMLEventReader from a JAXP source. * Support of this method is optional. * @param source the source to read from * @throws UnsupportedOperationException if this method is not * supported by this XMLInputFactory */ public abstract XMLEventReader createXMLEventReader(Source source) throws XMLStreamException; /** * Create a new XMLEventReader from a java.io.InputStream * @param stream the InputStream to read from * @throws XMLStreamException */ public abstract XMLEventReader createXMLEventReader(java.io.InputStream stream) throws XMLStreamException; /** * Create a new XMLEventReader from a java.io.InputStream * @param stream the InputStream to read from * @param encoding the character encoding of the stream * @throws XMLStreamException */ public abstract XMLEventReader createXMLEventReader(java.io.InputStream stream, String encoding) throws XMLStreamException; /** * Create a new XMLEventReader from a java.io.InputStream * @param systemId the system ID of the stream * @param stream the InputStream to read from * @throws XMLStreamException */ public abstract XMLEventReader createXMLEventReader(String systemId, java.io.InputStream stream) throws XMLStreamException; /** * Create a filtered reader that wraps the filter around the reader * @param reader the reader to filter * @param filter the filter to apply to the reader * @throws XMLStreamException */ public abstract XMLStreamReader createFilteredReader(XMLStreamReader reader, StreamFilter filter) throws XMLStreamException; /** * Create a filtered event reader that wraps the filter around the event reader * @param reader the event reader to wrap * @param filter the filter to apply to the event reader * @throws XMLStreamException */ public abstract XMLEventReader createFilteredReader(XMLEventReader reader, EventFilter filter) throws XMLStreamException; /** * The resolver that will be set on any XMLStreamReader or XMLEventReader created * by this factory instance. */ public abstract XMLResolver getXMLResolver(); /** * The resolver that will be set on any XMLStreamReader or XMLEventReader created * by this factory instance. * @param resolver the resolver to use to resolve references */ public abstract void setXMLResolver(XMLResolver resolver); /** * The reporter that will be set on any XMLStreamReader or XMLEventReader created * by this factory instance. */ public abstract XMLReporter getXMLReporter(); /** * The reporter that will be set on any XMLStreamReader or XMLEventReader created * by this factory instance. * @param reporter the resolver to use to report non fatal errors */ public abstract void setXMLReporter(XMLReporter reporter); /** * Allows the user to set specific feature/property on the underlying implementation. The underlying implementation * is not required to support every setting of every property in the specification and may use IllegalArgumentException * to signal that an unsupported property may not be set with the specified value. * @param name The name of the property (may not be null) * @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 java.lang.IllegalArgumentException; /** * 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 */ public abstract Object getProperty(java.lang.String name) throws java.lang.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); /** * Set a user defined event allocator for events * @param allocator the user defined allocator */ public abstract void setEventAllocator(XMLEventAllocator allocator); /** * Gets the allocator used by streams created with this factory */ public abstract XMLEventAllocator getEventAllocator(); } stax-1.2.0.orig/src/javax/xml/stream/StreamFilter.java0000644000175000017500000000126310444554664022643 0ustar twernertwernerpackage javax.xml.stream; /** * This interface declares a simple filter interface that one can * create to filter XMLStreamReaders * @version 1.0 * @author Copyright (c) 2003 by BEA Systems. All Rights Reserved. */ public interface StreamFilter { /** * Tests whether the current state is part of this stream. This method * will return true if this filter accepts this event and false otherwise. * * The method should not change the state of the reader when accepting * a state. * * @param reader the event to test * @return true if this filter accepts this event, false otherwise */ public boolean accept(XMLStreamReader reader); } stax-1.2.0.orig/src/javax/xml/stream/XMLEventWriter.java0000644000175000017500000002070510444554664023103 0ustar twernertwernerpackage javax.xml.stream; import javax.xml.stream.events.*; import javax.xml.stream.util.XMLEventConsumer; import javax.xml.namespace.NamespaceContext; /** * * This is the top level interface for writing XML documents. * * Instances of this interface are not required to validate the * form of the XML. * * @version 1.0 * @author Copyright (c) 2003 by BEA Systems. All Rights Reserved. * @see XMLEventReader * @see javax.xml.stream.events.XMLEvent * @see javax.xml.stream.events.Characters * @see javax.xml.stream.events.ProcessingInstruction * @see javax.xml.stream.events.StartElement * @see javax.xml.stream.events.EndElement */ public interface XMLEventWriter extends XMLEventConsumer { /** * Writes any cached events to the underlying output mechanism * @throws XMLStreamException */ public void flush() throws XMLStreamException; /** * Frees any resources associated with this stream * @throws XMLStreamException */ public void close() throws XMLStreamException; /** * Add an event to the output stream * Adding a START_ELEMENT will open a new namespace scope that * will be closed when the corresponding END_ELEMENT is written. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Required and optional fields for events added to the writer *
Event TypeRequired FieldsOptional FieldsRequired Behavior
START_ELEMENT QName name namespaces , attributes A START_ELEMENT will be written by writing the name, * namespaces, and attributes of the event in XML 1.0 valid * syntax for START_ELEMENTs. * The name is written by looking up the prefix for * the namespace uri. The writer can be configured to * respect prefixes of QNames. If the writer is respecting * prefixes it must use the prefix set on the QName. The * default behavior is to lookup the value for the prefix * on the EventWriter's internal namespace context. * Each attribute (if any) * is written using the behavior specified in the attribute * section of this table. Each namespace (if any) is written * using the behavior specified in the namespace section of this * table. *
END_ELEMENT Qname name None A well formed END_ELEMENT tag is written. * The name is written by looking up the prefix for * the namespace uri. The writer can be configured to * respect prefixes of QNames. If the writer is respecting * prefixes it must use the prefix set on the QName. The * default behavior is to lookup the value for the prefix * on the EventWriter's internal namespace context. * If the END_ELEMENT name does not match the START_ELEMENT * name an XMLStreamException is thrown. *
ATTRIBUTE QName name , String value QName type An attribute is written using the same algorithm * to find the lexical form as used in START_ELEMENT. * The default is to use double quotes to wrap attribute * values and to escape any double quotes found in the * value. The type value is ignored. *
NAMESPACE String prefix, String namespaceURI, * boolean isDefaultNamespaceDeclaration * None A namespace declaration is written. If the * namespace is a default namespace declaration * (isDefault is true) then xmlns="$namespaceURI" * is written and the prefix is optional. If * isDefault is false, the prefix must be declared * and the writer must prepend xmlns to the prefix * and write out a standard prefix declaration. *
PROCESSING_INSTRUCTION None String target, String data The data does not need to be present and may be * null. Target is required and many not be null. * The writer * will write data section * directly after the target, * enclosed in appropriate XML 1.0 syntax *
COMMENT None String comment If the comment is present (not null) it is written, otherwise an * an empty comment is written *
START_DOCUMENT None String encoding , boolean standalone, String version A START_DOCUMENT event is not required to be written to the * stream. If present the attributes are written inside * the appropriate XML declaration syntax *
END_DOCUMENT None None Nothing is written to the output
DTD String DocumentTypeDefinition None The DocumentTypeDefinition is written to the output
* @param event the event to be added * @throws XMLStreamException */ public void add(XMLEvent event) throws XMLStreamException; /** * Adds an entire stream to an output stream, * calls next() on the inputStream argument until hasNext() returns false * This should be treated as a convenience method that will * perform the following loop over all the events in an * event reader and call add on each event. * * @param reader the event stream to add to the output * @throws XMLStreamException */ public void add(XMLEventReader reader) throws XMLStreamException; /** * Gets the prefix the uri is bound to * @param uri the uri to look up * @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 * @param uri the uri to bind to the prefix * @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 * @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. * @param context the namespace context to use for this writer * @throws XMLStreamException */ public void setNamespaceContext(NamespaceContext context) throws XMLStreamException; /** * Returns the current namespace context. * @return the current namespace context */ public NamespaceContext getNamespaceContext(); } stax-1.2.0.orig/src/javax/xml/stream/XMLEventReader.java0000644000175000017500000000542610444554664023034 0ustar twernertwernerpackage javax.xml.stream; import javax.xml.stream.events.XMLEvent; import java.util.Iterator; /** * * This is the top level interface for parsing XML Events. It provides * the ability to peek at the next event and returns configuration * information through the property interface. * * @version 1.0 * @author Copyright (c) 2003 by BEA Systems. All Rights Reserved. * @see XMLInputFactory * @see XMLEventWriter */ public interface XMLEventReader extends Iterator { /** * Get the next XMLEvent * @see XMLEvent * @throws XMLStreamException if there is an error with the underlying XML. * @throws NoSuchElementException iteration has no more elements. */ public XMLEvent nextEvent() throws XMLStreamException; /** * Check if there are more events. * Returns true if there are more events and false otherwise. * @return true if the event reader has more events, false otherwise */ public boolean hasNext(); /** * Check the next XMLEvent without reading it from the stream. * Returns null if the stream is at EOF or has no more XMLEvents. * A call to peek() will be equal to the next return of next(). * @see XMLEvent * @throws XMLStreamException */ public XMLEvent peek() throws XMLStreamException; /** * Reads the content of a text-only element. Precondition: * the current event is START_ELEMENT. Postcondition: * The current event is the corresponding END_ELEMENT. * @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 insignificant space events until a START_ELEMENT or * END_ELEMENT is reached. If anything other than space characters are * encountered, an exception is thrown. This method should * be used when processing element-only content because * the parser is not able to recognize ignorable whitespace if * the DTD is missing or not interpreted. * @throws XMLStreamException if anything other than space characters are encountered */ public XMLEvent nextTag() throws XMLStreamException; /** * Get the value of a feature/property from the underlying implementation * @param name The name of the property * @return The value of the property * @throws IllegalArgumentException if the property is not supported */ public Object getProperty(java.lang.String name) throws java.lang.IllegalArgumentException; /** * 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; } stax-1.2.0.orig/src/javax/xml/package.html0000644000175000017500000000076010444554664020366 0ustar twernertwerner Specifies constants for use in XML APIs

Package Specification

Related Documentation

stax-1.2.0.orig/src/javax/xml/namespace/0000755000175000017500000000000010444554664020036 5ustar twernertwernerstax-1.2.0.orig/src/com/0000755000175000017500000000000010444554664014747 5ustar twernertwernerstax-1.2.0.orig/src/com/bea/0000755000175000017500000000000010444554664015476 5ustar twernertwernerstax-1.2.0.orig/src/com/bea/xml/0000755000175000017500000000000010444554664016276 5ustar twernertwernerstax-1.2.0.orig/src/com/bea/xml/stream/0000755000175000017500000000000010444554664017571 5ustar twernertwernerstax-1.2.0.orig/src/com/bea/xml/stream/XMLWriterBase.java0000644000175000017500000005514510444554664023076 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream; import com.bea.xml.stream.util.NamespaceContextImpl; import com.bea.xml.stream.util.Stack; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.util.HashSet; import java.util.Iterator; import javax.xml.namespace.NamespaceContext; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; /** *

The base output class.

*/ public class XMLWriterBase extends ReaderToWriter implements XMLStreamWriter { protected static final String DEFAULTNS=""; private Writer writer; private boolean startElementOpened=false; private boolean isEmpty=false; private ConfigurationContextBase config; private CharsetEncoder encoder; // these two stacks are used to implement the // writeEndElement() method private Stack localNameStack = new Stack(); private Stack prefixStack = new Stack(); private Stack uriStack = new Stack(); protected NamespaceContextImpl context = new NamespaceContextImpl(); private HashSet needToWrite; private boolean isPrefixDefaulting; private int defaultPrefixCount=0; public XMLWriterBase() {} public XMLWriterBase(Writer writer) { this.writer = writer; setWriter(writer); } public void setWriter(Writer writer) { this.writer = writer; setStreamWriter(this); if (writer instanceof OutputStreamWriter) { String charsetName = ((OutputStreamWriter) writer).getEncoding(); this.encoder = Charset.forName(charsetName).newEncoder(); } else { this.encoder = null; } } public void setConfigurationContext(ConfigurationContextBase c) { config = c; isPrefixDefaulting = config.isPrefixDefaulting(); } protected void write(String s) throws XMLStreamException { try { writer.write(s); } catch (IOException e) { throw new XMLStreamException(e); } } protected void write (char c) throws XMLStreamException { try { writer.write(c); } catch (IOException e) { throw new XMLStreamException(e); } } protected void write (char[] c) throws XMLStreamException { try { writer.write(c); } catch (IOException e) { throw new XMLStreamException(e); } } protected void write (char[] c, int start, int len) throws XMLStreamException { try { writer.write(c,start,len); } catch (IOException e) { throw new XMLStreamException(e); } } protected void writeCharactersInternal(char characters[], int start, int length, boolean isAttributeValue) throws XMLStreamException { if(length == 0) return; // We expect the common case to be that people do not have these // characters in their XML so we make a pass through the char // array and check. If they're all good, we can call the // underlying Writer once with the entire char array. If we find // a bad character then we punt it to the slow routine. int i = 0; loop: for(; i': break loop; } if (c < 32) { /* All non-space white space needs to be encoded in attribute * values; in normal text tabs and LFs can be left as is, * but everything else (including CRs) needs to be quoted */ if (isAttributeValue || (c != '\t' && c != '\n')) { break loop; } } else if (c > 127) { // Above ascii range? if (encoder != null && !encoder.canEncode(c)) { break loop; } } } if (i < length) { // slow path slowWriteCharacters(characters,start,length, isAttributeValue); } else { // fast path write(characters,start,length); } } private void slowWriteCharacters(char chars[], int start, int length, boolean isAttributeValue) throws XMLStreamException { loop: for (int i=0; i < length; i++) { final char c = chars[i+start]; switch (c) { case '&': write("&"); continue loop; case '<': write("<"); continue loop; case '>': write(">"); continue loop; case '\"': if (isAttributeValue) { write("""); continue loop; } break; default: if (c < 32) { if (isAttributeValue || (c != '\t' && c != '\n')) { write("&#"); write(Integer.toString(c)); write(';'); continue loop; } } else if (c > 127 && encoder != null && !encoder.canEncode(c)) { write("&#"); write(Integer.toString(c)); write(';'); continue loop; } } write(c); } } protected void closeStartElement() throws XMLStreamException { if (startElementOpened) { closeStartTag(); startElementOpened = false; } } protected boolean isOpen() { return startElementOpened; } protected void closeStartTag() throws XMLStreamException { flushNamespace(); clearNeedsWritingNs(); if (isEmpty) { write ("/>"); isEmpty = false; } else write(">"); } private void openStartElement() throws XMLStreamException { if (startElementOpened) closeStartTag(); else startElementOpened = true; } protected String writeName(String prefix,String namespaceURI, String localName) throws XMLStreamException { if (!("".equals(namespaceURI))) prefix = getPrefixInternal(namespaceURI); if (!("".equals(prefix))) { write(prefix); write(":"); } write(localName); return prefix; } private String getPrefixInternal(String namespaceURI) { String prefix = context.getPrefix(namespaceURI); if (prefix == null) { return ""; } return prefix; } protected String getURIInternal(String prefix) { String uri = context.getNamespaceURI(prefix); if (uri == null) { return ""; } return uri; } protected void openStartTag() throws XMLStreamException { write("<"); } private boolean needToWrite(String uri) { if (needToWrite == null) { needToWrite = new HashSet(); } boolean needs = needToWrite.contains(uri); needToWrite.add(uri); return needs; } private void prepareNamespace(String uri) throws XMLStreamException { if (!isPrefixDefaulting) return; if ("".equals(uri)) return; String prefix = getPrefix(uri); // if the prefix is bound then we can ignore and return if (prefix != null) return; defaultPrefixCount++; prefix = "ns"+defaultPrefixCount; setPrefix(prefix,uri); } private void removeNamespace(String uri) { if (!isPrefixDefaulting || needToWrite == null) return; needToWrite.remove(uri); } private void flushNamespace() throws XMLStreamException { if (!isPrefixDefaulting || needToWrite == null) return; Iterator i = needToWrite.iterator(); while (i.hasNext()) { String uri = (String) i.next(); String prefix = context.getPrefix(uri); if (prefix == null) { throw new XMLStreamException("Unable to default prefix with uri:"+ uri); } writeNamespace(prefix,uri); } needToWrite.clear(); } protected void writeStartElementInternal(String namespaceURI, String localName) throws XMLStreamException { if (namespaceURI == null) throw new IllegalArgumentException("The namespace URI may not be null"); if (localName == null) throw new IllegalArgumentException("The local name may not be null"); openStartElement(); openStartTag(); prepareNamespace(namespaceURI); prefixStack.push(writeName("",namespaceURI, localName)); localNameStack.push(localName); uriStack.push(namespaceURI); } public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { context.openScope(); writeStartElementInternal(namespaceURI,localName); } public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { if (namespaceURI == null) throw new IllegalArgumentException("The namespace URI may not be null"); if (localName == null) throw new IllegalArgumentException("The local name may not be null"); if (prefix == null) throw new IllegalArgumentException("The prefix may not be null"); context.openScope(); prepareNamespace(namespaceURI); context.bindNamespace(prefix,namespaceURI); writeStartElementInternal(namespaceURI,localName); } public void writeStartElement(String localName) throws XMLStreamException { context.openScope(); writeStartElement("",localName); } public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { openStartElement(); prepareNamespace(namespaceURI); isEmpty = true; write("<"); writeName("",namespaceURI,localName); } public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { openStartElement(); prepareNamespace(namespaceURI); isEmpty = true; write("<"); write(prefix); write(":"); write(localName); } public void writeEmptyElement(String localName) throws XMLStreamException { writeEmptyElement("",localName); } protected void openEndTag() throws XMLStreamException { write(""); } public void writeEndElement() throws XMLStreamException { /* 07-Mar-2006, TSa: Empty elements do not need special handling, * since this call only 'closes' them as a side effect: real * effect is for the open non-empty start element (non-empty * just meaning it was written using full writeStartElement() * as opposed to writeEmptyElement()). */ //boolean wasEmpty = isEmpty; if (isOpen()) { closeStartElement(); } String prefix = (String) prefixStack.pop(); String local = (String) localNameStack.pop(); uriStack.pop(); //if(!wasEmpty) { openEndTag(); writeName(prefix,"",local); closeEndTag(); //} context.closeScope(); } public void writeRaw(String data) throws XMLStreamException { closeStartElement(); write(data); } public void close() throws XMLStreamException { flush(); } public void flush() throws XMLStreamException { try { writer.flush(); } catch (IOException e) { throw new XMLStreamException(e); } } public void writeEndDocument() throws XMLStreamException { while(!localNameStack.isEmpty()) writeEndElement(); } public void writeAttribute(String localName, String value) throws XMLStreamException { writeAttribute("",localName,value); } public void writeAttribute(String namespaceURI, String localName, String value) throws XMLStreamException { if (!isOpen()) throw new XMLStreamException("A start element must be written before an attribute"); prepareNamespace(namespaceURI); write(" "); writeName("",namespaceURI,localName); write("=\""); writeCharactersInternal(value.toCharArray(),0,value.length(),true); write("\""); } public void writeAttribute(String prefix, String namespaceURI, String localName, String value) throws XMLStreamException { if (!isOpen()) throw new XMLStreamException("A start element must be written before an attribute"); prepareNamespace(namespaceURI); context.bindNamespace(prefix,namespaceURI); write(" "); writeName(prefix,namespaceURI,localName); write("=\""); writeCharactersInternal(value.toCharArray(),0,value.length(),true); write("\""); } public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { if(!isOpen()) throw new XMLStreamException("A start element must be written before a namespace"); if (prefix == null || "".equals(prefix) || "xmlns".equals(prefix)) { writeDefaultNamespace(namespaceURI); return; } if( needsWritingNs(prefix) ) { write(" xmlns:"); write(prefix); write("=\""); write(namespaceURI); write("\""); setPrefix(prefix,namespaceURI); } } private HashSet setNeedsWritingNs = new HashSet(); private void clearNeedsWritingNs() { setNeedsWritingNs.clear(); } private boolean needsWritingNs(String prefix) { boolean needs = ! setNeedsWritingNs.contains(prefix); if(needs) { setNeedsWritingNs.add(prefix); } return needs; } public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { if(!isOpen()) throw new XMLStreamException("A start element must be written before the default namespace"); if( needsWritingNs(DEFAULTNS) ) { write(" xmlns"); write("=\""); write(namespaceURI); write("\""); setPrefix(DEFAULTNS,namespaceURI); } } public void writeComment(String data) throws XMLStreamException { closeStartElement(); write(""); } public void writeProcessingInstruction(String target) throws XMLStreamException { closeStartElement(); writeProcessingInstruction(target,null); } public void writeProcessingInstruction(String target, String text) throws XMLStreamException { closeStartElement(); write(""); } public void writeDTD(String dtd) throws XMLStreamException { write(dtd); } public void writeCData(String data) throws XMLStreamException { closeStartElement(); write(""); } public void writeEntityRef(String name) throws XMLStreamException { closeStartElement(); write("&"); write(name); write(";"); } public void writeStartDocument() throws XMLStreamException { write(""); } public void writeStartDocument(String version) throws XMLStreamException { write(""); } public void writeStartDocument(String encoding, String version) throws XMLStreamException { write(""); } public void writeCharacters(String text) throws XMLStreamException { closeStartElement(); writeCharactersInternal(text.toCharArray(),0,text.length(),false); } public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { closeStartElement(); writeCharactersInternal(text,start,len,false); } public String getPrefix(String uri) throws XMLStreamException { return context.getPrefix(uri); } public void setPrefix(String prefix, String uri) throws XMLStreamException { //if() { needToWrite(uri); context.bindNamespace(prefix,uri); //} } public void setDefaultNamespace(String uri) throws XMLStreamException { needToWrite(uri); context.bindDefaultNameSpace(uri); } public void setNamespaceContext(NamespaceContext context) throws XMLStreamException { if (context == null) throw new NullPointerException("The namespace "+ " context may"+ " not be null."); this.context = new NamespaceContextImpl(context); } public NamespaceContext getNamespaceContext() { return context; } public Object getProperty(String name) throws IllegalArgumentException { return config.getProperty(name); } public static void main(String args[]) throws Exception { /******* Writer w = new java.io.OutputStreamWriter(System.out); XMLWriterBase writer = new XMLWriterBase(w); writer.writeStartDocument(); writer.setPrefix("c","http://c"); writer.setDefaultNamespace("http://c"); writer.writeStartElement("http://c","a"); writer.writeAttribute("b","blah"); writer.writeNamespace("c","http://c"); writer.writeDefaultNamespace("http://c"); writer.setPrefix("d","http://c"); writer.writeEmptyElement("http://c","d"); writer.writeAttribute("http://c","chris","fry"); writer.writeNamespace("d","http://c"); writer.writeCharacters("foo bar foo"); writer.writeEndElement(); writer.flush(); ********/ XMLOutputFactory output = XMLOutputFactoryBase.newInstance(); output.setProperty(javax.xml.stream.XMLOutputFactory.IS_REPAIRING_NAMESPACES,new Boolean(true)); Writer myWriter = new java.io.OutputStreamWriter( new java.io.FileOutputStream("tmp"),"us-ascii"); XMLStreamWriter writer2 = output.createXMLStreamWriter(myWriter); writer2.writeStartDocument(); writer2.setPrefix("c","http://c"); writer2.setDefaultNamespace("http://d"); writer2.writeStartElement("http://c","a"); writer2.writeAttribute("b","blah"); writer2.writeEmptyElement("http://c","d"); writer2.writeEmptyElement("http://d","e"); writer2.writeEmptyElement("http://e","f"); writer2.writeEmptyElement("http://f","g"); writer2.writeAttribute("http://c","chris","fry"); writer2.writeCharacters("foo bar foo"); writer2.writeCharacters("bad char coming["); char c = 0x1024; char[] array = new char[1]; array[0]=c; writer2.writeCharacters(new String(array)); writer2.writeCharacters("]"); writer2.writeEndElement(); writer2.flush(); } } stax-1.2.0.orig/src/com/bea/xml/stream/AttributeBase.java0000644000175000017500000001623010444554664023174 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream; import java.io.Writer; import javax.xml.stream.Location; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.Characters; import javax.xml.stream.events.EndElement; import javax.xml.namespace.QName; /** *

An implementation of the Attribute class.

* */ public class AttributeBase implements javax.xml.stream.events.Attribute, Location { private String value; private QName name; private QName attributeType; private String locationURI; private int eventType = -1; private int line = -1; private int column = -1; private int characterOffset = 0; public AttributeBase(String prefix, String namespaceURI, String localName, String value, String attributeType) { if (prefix == null) prefix = ""; name = new QName(namespaceURI, localName,prefix); this.value = value; this.attributeType = new QName(attributeType); } public AttributeBase(String prefix, String localName, String value) { if (prefix == null) prefix = ""; name = new QName("",localName,prefix); this.value = value; } public AttributeBase(QName name, String value) { this.name = name; this.value = value; } public String toString() { if (name.getPrefix()!=null && !name.getPrefix().equals("")) return "['"+name.getNamespaceURI()+"']:"+name.getPrefix()+":"+name.getLocalPart()+"='"+value+"'"; return name.getLocalPart()+"='"+value+"'"; } public int getLineNumber() { return line; } public void setLineNumber(int line) { this.line = line; } public int getColumnNumber() { return column; } public void setColumnNumber(int col) { this.column = col; } public int getCharacterOffset() { return characterOffset; } public void setCharacterOffset(int c) { characterOffset = c; } public String getLocationURI() { return locationURI; } public void setLocationURI(String uri) { locationURI = uri; } public int getEventType() { return XMLEvent.ATTRIBUTE; } public boolean hasName() { return name != null; } public QName getName() { return name; } public boolean isNamespaceDeclaration() { return false; } public String getLocalName() { return name.getLocalPart(); } public String getValue() { return value; } public String getDTDType() { return "CDATA"; } public String getNamespaceURI() { return name.getNamespaceURI();} public void setNamespaceURI(String uri) { name = new QName(uri,name.getLocalPart()); } /** * By default, all attributes are created as specified since RI doesn't * handle attribute defaulting. */ public boolean isSpecified() { return true;} public boolean isStartElement() { return false; } public boolean isEndElement() { return false; } public boolean isEntityReference() { return false; } public boolean isProcessingInstruction() { return false; } public boolean isCharacters() { return false; } public boolean isAttribute() { return true; } public boolean isNamespace() { return false; } public boolean isStartDocument() { return false; } public boolean isEndDocument() { return false; } public boolean isEndEntity() { return false; } public boolean isStartEntity() { return false; } public String getPublicId() { return null; } public String getSystemId() { return null; } public Location getLocation() { return this; } public StartElement asStartElement() { throw new ClassCastException("cannnot cast AttributeBase to StartElement"); } public EndElement asEndElement() { throw new ClassCastException("cannnot cast AttributeBase to EndElement"); } public Characters asCharacters() { throw new ClassCastException("cannnot cast AttributeBase to Characters"); } public void recycle(){} public boolean isDefault() { return true; } public String getSourceName() { return null ; } public QName getSchemaType() { return null; } public void writeAsEncodedUnicode(Writer writer) throws javax.xml.stream.XMLStreamException { try { String prefix = name.getPrefix(); if (prefix != null && prefix.length() > 0) { writer.write(prefix); writer.write(':'); } writer.write(name.getLocalPart()); writer.write("=\""); final String data = this.value; int len = data.length(); if (len > 0) { int i = 0; // Let's see how much we can output without encoding: loop: for (; i < len; ++i) { final char c = data.charAt(i); switch (c) { case '&': case '<': case '"': break loop; default: if (c < 32) { break loop; } } } // got it all? if (i == len) { writer.write(data); } else { // nope... if (i > 0) { writer.write(data, 0, i); } for (; i < len; ++i) { final char c = data.charAt(i); switch (c) { case '&': writer.write("&"); break; case '<': writer.write("<"); break; case '"': writer.write("""); break; default: if (c < 32) { writeEncodedChar(writer, c); } else { writer.write(c); } } } } } writer.write('"'); } catch (java.io.IOException e) { throw new XMLStreamException(e); } } public static void writeEncodedChar(java.io.Writer writer, char c) throws java.io.IOException { // This is slow, but gets work done: writer.write("&#"); writer.write(Integer.toString(c)); writer.write(';'); } } stax-1.2.0.orig/src/com/bea/xml/stream/StaticAllocator.java0000644000175000017500000001774310444554664023540 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream; import com.bea.xml.stream.util.ElementTypeNames; import java.util.Iterator; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.util.XMLEventAllocator; import javax.xml.stream.util.XMLEventConsumer; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.ProcessingInstruction; import javax.xml.stream.events.Comment; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.Namespace; import javax.xml.stream.events.Characters; import javax.xml.stream.events.StartDocument; import javax.xml.stream.events.EndDocument; import javax.xml.stream.events.Namespace; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.EntityReference; import javax.xml.stream.events.DTD; import com.bea.xml.stream.events.CharactersEvent; import com.bea.xml.stream.events.CommentEvent; import com.bea.xml.stream.events.EndDocumentEvent; import com.bea.xml.stream.events.EndElementEvent; import com.bea.xml.stream.events.EntityReferenceEvent; import com.bea.xml.stream.events.ProcessingInstructionEvent; import com.bea.xml.stream.events.StartDocumentEvent; import com.bea.xml.stream.events.StartElementEvent; import com.bea.xml.stream.events.DTDEvent; /** *

Return a single event for each allocate call

*/ public class StaticAllocator implements XMLEventAllocator { public static final String FEATURE_STAX_NOTATIONS = "javax.xml.stream.notations"; public static final String FEATURE_STAX_ENTITIES = "javax.xml.stream.entities"; StartElementEvent startElement = new StartElementEvent(); EndElementEvent endElement = new EndElementEvent(); CharactersEvent characters = new CharactersEvent(); CharactersEvent cData = new CharactersEvent("",true); CharactersEvent space = new CharactersEvent(); CommentEvent comment = new CommentEvent(); EntityReferenceEvent entity = new EntityReferenceEvent(); ProcessingInstructionEvent pi = new ProcessingInstructionEvent(); StartDocumentEvent startDoc = new StartDocumentEvent(); EndDocumentEvent endDoc = new EndDocumentEvent(); DTDEvent dtd = new DTDEvent(); public StaticAllocator() { } public XMLEventAllocator newInstance() { return new StaticAllocator(); } public StartElement allocateStartElement(XMLStreamReader reader) throws XMLStreamException { startElement.reset(); String prefix = EventFactory.checkPrefix(reader.getPrefix()); startElement.setName(new QName(reader.getNamespaceURI(), reader.getLocalName(), prefix)); Iterator ai = XMLEventAllocatorBase.getAttributes(reader); while (ai.hasNext()) startElement.addAttribute((Attribute)ai.next()); Iterator ni = XMLEventAllocatorBase.getNamespaces(reader); while (ni.hasNext()) startElement.addAttribute((Namespace)ni.next()); return startElement; } public EndElement allocateEndElement(XMLStreamReader reader) throws XMLStreamException { endElement.reset(); String prefix = EventFactory.checkPrefix(reader.getPrefix()); endElement.setName(new QName(reader.getNamespaceURI(), reader.getLocalName(), prefix )); Iterator ni = XMLEventAllocatorBase.getNamespaces(reader); while (ni.hasNext()) endElement.addNamespace((Namespace) ni.next()); return endElement; } public Characters allocateCharacters(XMLStreamReader reader) throws XMLStreamException { characters.setData(reader.getText()); return characters; } public Characters allocateCData(XMLStreamReader reader) throws XMLStreamException { cData.setData(reader.getText()); return cData; } public Characters allocateSpace(XMLStreamReader reader) throws XMLStreamException { space.setSpace(true); space.setData(reader.getText()); return space; } public EntityReference allocateEntityReference(XMLStreamReader reader) throws XMLStreamException { entity.setName(reader.getLocalName()); entity.setReplacementText(reader.getText()); return entity; } public ProcessingInstruction allocatePI(XMLStreamReader reader) throws XMLStreamException { pi.setTarget(reader.getPITarget()); pi.setData(reader.getPIData()); return pi; } public Comment allocateComment(XMLStreamReader reader) throws XMLStreamException { comment.setData(reader.getText()); return comment; } public StartDocument allocateStartDocument(XMLStreamReader reader) throws XMLStreamException { allocateXMLDeclaration(reader); return startDoc; } public EndDocument allocateEndDocument(XMLStreamReader reader) throws XMLStreamException { return endDoc; } public DTD allocateDTD(XMLStreamReader reader) throws XMLStreamException { dtd.setDTD(reader.getText()); return dtd; } public StartDocument allocateXMLDeclaration(XMLStreamReader reader) throws XMLStreamException { startDoc.clear(); String encoding = reader.getCharacterEncodingScheme(); String version = reader.getVersion(); boolean standalone = reader.isStandalone(); if (encoding != null && version != null && !standalone ) { startDoc.setEncoding(encoding); startDoc.setVersion(version); startDoc.setStandalone(standalone); return startDoc; } if (version != null && encoding != null) { startDoc.setEncoding(encoding); startDoc.setVersion(version); return startDoc; } if (encoding != null) startDoc.setEncoding(encoding); return startDoc; } public XMLEvent allocate(XMLStreamReader reader) throws XMLStreamException { switch (reader.getEventType()) { case XMLEvent.START_ELEMENT: return allocateStartElement(reader); case XMLEvent.END_ELEMENT: return allocateEndElement(reader); case XMLEvent.CHARACTERS: return allocateCharacters(reader); case XMLEvent.SPACE: return allocateCharacters(reader); case XMLEvent.CDATA: return allocateCData(reader); case XMLEvent.ENTITY_REFERENCE: return allocateEntityReference(reader); case XMLEvent.PROCESSING_INSTRUCTION: return allocatePI(reader); case XMLEvent.COMMENT: return allocateComment(reader); //case XMLEvent.XML_DECLARATION: return allocateXMLDeclaration(reader); case XMLEvent.START_DOCUMENT: return allocateStartDocument(reader); case XMLEvent.END_DOCUMENT: return allocateEndDocument(reader); case XMLEvent.DTD: return allocateDTD(reader); default: throw new XMLStreamException("Unable to allocate event["+ ElementTypeNames.getEventTypeString(reader.getEventType())+"]"); } // return new com.bea.xml.stream.events.NullEvent(); } public void allocate(XMLStreamReader reader, XMLEventConsumer consumer) throws XMLStreamException { consumer.add(allocate(reader)); } public String toString() { return "Static Allocator"; } } stax-1.2.0.orig/src/com/bea/xml/stream/XMLStreamPlayer.java0000644000175000017500000002410710444554664023431 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream; import java.io.Reader; import java.io.InputStream; import java.io.InputStreamReader; import javax.xml.namespace.NamespaceContext; import javax.xml.namespace.QName; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import javax.xml.stream.Location; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.Namespace; import com.bea.xml.stream.util.NamespaceContextImpl; /** *

Creates an XMLStreamReader over a non-xml ascii format

*/ public class XMLStreamPlayer implements XMLStreamReader { EventState state; EventScanner scanner; NamespaceContextImpl context = new NamespaceContextImpl(); public XMLStreamPlayer(){} public XMLStreamPlayer(InputStream stream) { try { scanner = new EventScanner(new InputStreamReader(stream)); next(); if (getEventType()==XMLEvent.START_DOCUMENT) { String encoding = getCharacterEncodingScheme(); scanner = new EventScanner(new InputStreamReader(stream, encoding)); } } catch (Exception e) { throw new IllegalArgumentException("Unable to instantiate the XMLStreamPlayer"+e.getMessage()); } } public XMLStreamPlayer(Reader reader) { try { scanner = new EventScanner(reader); next(); } catch (Exception e) { System.out.println(e); } } public Object getProperty(java.lang.String name) throws java.lang.IllegalArgumentException { return null; } public int next() throws XMLStreamException { try { if (scanner.hasNext() == false) { state = null; return -1; } state = scanner.readElement(); if (isStartElement()) { context.openScope(); for (int i =0; i < getNamespaceCount(); i++) { context.bindNamespace(getNamespacePrefix(i), getNamespaceURI(i)); } } else if (isEndElement()) { if (context.getDepth() > 0) context.closeScope(); } return state.getType(); } catch (Exception e) { System.out.println(e); e.printStackTrace(); throw new XMLStreamException(e.getMessage(),e); } } public void require(int type, String namespaceURI, String localName) throws XMLStreamException {} public String getElementText() throws XMLStreamException { StringBuffer buf = new StringBuffer(); if(getEventType() != START_ELEMENT) throw new XMLStreamException( "Precondition for readText is getEventType() == START_ELEMENT"); do { if(next() == END_DOCUMENT) throw new XMLStreamException("Unexpected end of Document"); if(isStartElement()) throw new XMLStreamException("Unexpected Element start"); if(isCharacters()) buf.append(getText()); } while(!isEndElement()); return buf.toString(); } public int nextTag() throws XMLStreamException { do { if(next() == END_DOCUMENT) throw new XMLStreamException("Unexpected end of Document"); if(isCharacters() && !isWhiteSpace()) throw new XMLStreamException("Unexpected text"); } while(!isStartElement() && !isEndElement()); return getEventType(); } public boolean hasNext() throws XMLStreamException { try { return state != null && state.getType() != XMLStreamConstants.END_DOCUMENT; } catch (Exception e) { throw new XMLStreamException(e); } } public void close() throws XMLStreamException {} public String getNamespaceURI(String prefix) { return context.getNamespaceURI(prefix); } private Attribute getAttributeInternal(int index) { return (Attribute) state.getAttributes().get(index); } private Attribute getNamespaceInternal(int index) { return (Attribute) state.getNamespaces().get(index); } public boolean isStartElement() { return ((getEventType() & XMLStreamConstants.START_ELEMENT) != 0); } public boolean isEndElement() { return ((getEventType() & XMLStreamConstants.END_ELEMENT) != 0); } public boolean isCharacters() { return ((getEventType() & XMLStreamConstants.CHARACTERS) != 0); } public boolean isWhiteSpace() { return false; } public String getAttributeValue(String namespaceUri, String localName) { for (int i=0; i < getAttributeCount(); i++) { Attribute a = getAttributeInternal(i); if (localName.equals(a.getName().getLocalPart())) if (namespaceUri == null) return a.getValue(); else if (namespaceUri.equals(a.getName().getNamespaceURI())) return a.getValue(); } return null; } public int getAttributeCount() { if (isStartElement()) return state.getAttributes().size(); else return 0; } public QName getAttributeName(int index) { return new QName(getAttributeNamespace(index), getAttributeLocalName(index), getAttributePrefix(index)); } public String getAttributeNamespace(int index) { Attribute a = getAttributeInternal(index); if (a == null) return null; return a.getName().getNamespaceURI(); } public String getAttributeLocalName(int index) { Attribute a = getAttributeInternal(index); if (a == null) return null; return a.getName().getLocalPart(); } public String getAttributePrefix(int index) { Attribute a = getAttributeInternal(index); if (a == null) return null; return a.getName().getPrefix(); } public String getAttributeType(int index) { return "CDATA"; } public String getAttributeValue(int index){ Attribute a = getAttributeInternal(index); if (a == null) return null; return a.getValue(); } public boolean isAttributeSpecified(int index) { return false; } // Namespaces public int getNamespaceCount() { if (isStartElement()) return state.getNamespaces().size(); else return 0; } public String getNamespacePrefix(int index) { Attribute a = getNamespaceInternal(index); if (a == null) return null; return a.getName().getLocalPart(); } public String getNamespaceURI(int index) { Attribute a = getNamespaceInternal(index); if (a == null) return null; return a.getValue(); } public NamespaceContext getNamespaceContext() { return context; } public XMLStreamReader subReader() throws XMLStreamException { return null; } public int getEventType() { if (state == null) return XMLStreamConstants.END_DOCUMENT; return state.getType(); } public String getText() { return state.getData(); } public Reader getTextStream() { throw new UnsupportedOperationException(); } public char[] getTextCharacters() { return state.getData().toCharArray(); } public int getTextCharacters(int src, char[] target, int targetStart, int length) throws XMLStreamException { throw new UnsupportedOperationException(); } public int getTextStart() { return 0; } public int getTextLength(){ return state.getData().length(); } public String getEncoding() { return state.getData(); } public boolean hasText() { return (0 != (getEventType() & (XMLStreamConstants.CHARACTERS | XMLStreamConstants.DTD | XMLStreamConstants.COMMENT | XMLStreamConstants.ENTITY_REFERENCE))); } public Location getLocation() { return null; } public QName getName() { return new QName(getNamespaceURI(), getLocalName(), getPrefix()); } public String getLocalName() { return state.getLocalName(); } public boolean hasName() { return (0 != (getEventType() & (XMLEvent.START_ELEMENT | XMLEvent.END_ELEMENT | XMLEvent.ENTITY_REFERENCE))); } public String getNamespaceURI() { return state.getNamespaceURI(); } public String getPrefix() { return state.getPrefix(); } public String getVersion() { return "1.0"; } public boolean isStandalone() { return true; } public boolean standaloneSet() { return false; } public String getCharacterEncodingScheme() { return null; } public String getPITarget() { return state.getData(); } public String getPIData() { return state.getExtraData(); } public boolean endDocumentIsPresent() { return scanner.endDocumentIsPresent(); } public static void main(String args[]) throws Exception { XMLStreamReader reader = new XMLStreamPlayer( new java.io.FileReader(args[0])); XMLOutputFactory xmlof = XMLOutputFactory.newInstance(); XMLStreamWriter xmlw = xmlof.createXMLStreamWriter(System.out); ReaderToWriter rtow = new ReaderToWriter(xmlw); while (reader.hasNext()) { rtow.write(reader); reader.next(); } xmlw.flush(); } } stax-1.2.0.orig/src/com/bea/xml/stream/XMLStreamRecorder.java0000644000175000017500000001365210444554664023745 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream; import java.io.Writer; import java.io.IOException; import javax.xml.stream.XMLStreamWriter; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; /** *

Writes XML in a non-xml format to create XML tests.

*/ public class XMLStreamRecorder extends XMLWriterBase { public XMLStreamRecorder(){} public XMLStreamRecorder(Writer writer) { super(writer); } protected String writeName(String prefix,String namespaceURI, String localName) throws XMLStreamException { if (!"".equals(namespaceURI)) write("['"+namespaceURI+"':"); else write("["); prefix = super.writeName(prefix,namespaceURI,localName); write(']'); return prefix; } protected void writeType(int type) throws XMLStreamException { closeStartElement(); write('['); write(com.bea.xml.stream.util.ElementTypeNames.getEventTypeString(type)); write(']'); } protected void openStartTag() throws XMLStreamException { write('['); } protected void closeStartTag() throws XMLStreamException{ write("];\n"); } protected void openEndTag() throws XMLStreamException { write('['); } protected void closeEndTag() throws XMLStreamException { write(']'); } public void writeAttribute(String namespaceURI, String localName, String value) throws XMLStreamException { write("[[ATTRIBUTE]"); writeName("",namespaceURI,localName); write("="); writeCharactersInternal(value.toCharArray(),0,value.length(),true); write("]"); } public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { if(!isOpen()) throw new XMLStreamException("A start element must be written before a namespace"); if (prefix == null || "".equals(prefix) || "xmlns".equals(prefix)) { writeDefaultNamespace(namespaceURI); return; } write("[[NAMESPACE]["); write("xmlns:"); write(prefix); write("]=["); write(namespaceURI); write("]"); setPrefix(prefix,namespaceURI); write(']'); } public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { write("[[DEFAULT]["); if(!isOpen()) throw new XMLStreamException("A start element must be written before the default namespace"); write("xmlns]"); write("=["); write(namespaceURI); write("]"); setPrefix(DEFAULTNS,namespaceURI); write(']'); } public void writeComment(String data) throws XMLStreamException { closeStartElement(); write("["); if (data != null) write(data); write("]"); } public void writeProcessingInstruction(String target, String text) throws XMLStreamException { closeStartElement(); write("["); if (target != null) write("["+target+"]"); if (text != null) { write(",["+text+"]"); } write("]"); } public void writeDTD(String dtd) throws XMLStreamException { write("["); super.write(dtd); write("]"); } public void writeCData(String data) throws XMLStreamException { write("["); if (data != null) write(data); write("]"); } public void writeEntityRef(String name) throws XMLStreamException { write("["); super.writeEntityRef(name); write("]"); } public void writeStartDocument() throws XMLStreamException { write("[[1.0],[utf-8]]"); } public void writeStartDocument(String version) throws XMLStreamException { write("[["); write(version); write("],[utf-8]]"); } public void writeStartDocument(String encoding, String version) throws XMLStreamException { write("[["); write(version); write("],["); write(encoding); write("]]"); } protected void writeCharactersInternal(char characters[], int start, int length, boolean isAttributeValue) throws XMLStreamException { if(length == 0) write("[]"); else { write("["); write(characters,start,length); write("]"); } } public void write(XMLStreamReader xmlr) throws XMLStreamException { writeType(xmlr.getEventType()); super.write(xmlr); if (!isOpen()) write(";\n"); } public static void main(String args[]) throws Exception { XMLInputFactory xmlif = XMLInputFactory.newInstance(); XMLOutputFactory xmlof = XMLOutputFactory.newInstance(); XMLStreamReader xmlr = xmlif.createXMLStreamReader(new java.io.FileReader(args[0])); XMLStreamRecorder r = new XMLStreamRecorder(new java.io.OutputStreamWriter(new java.io.FileOutputStream("out.stream"))); while (xmlr.hasNext()) { r.write(xmlr); xmlr.next(); } r.write(xmlr); r.flush(); } } stax-1.2.0.orig/src/com/bea/xml/stream/events/0000755000175000017500000000000010444554664021075 5ustar twernertwernerstax-1.2.0.orig/src/com/bea/xml/stream/events/NotationDeclarationEvent.java0000644000175000017500000000252610444554664026710 0ustar twernertwernerpackage com.bea.xml.stream.events; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.events.NotationDeclaration; /** * Simple implementation of {@link NotationDeclaration}. * * @author Tatu Saloranta */ public class NotationDeclarationEvent extends BaseEvent implements NotationDeclaration { protected final String name; protected final String publicId; protected final String systemId; public NotationDeclarationEvent(String name, String publicId, String systemId) { super(XMLEvent.NOTATION_DECLARATION); this.name = name; this.publicId = publicId; this.systemId = systemId; } public String getName() { return name; } public String getPublicId() { return publicId; } public String getSystemId() { return systemId; } protected void doWriteAsEncodedUnicode(java.io.Writer writer) throws java.io.IOException { writer.write("'); } } stax-1.2.0.orig/src/com/bea/xml/stream/events/StartDocumentEvent.java0000644000175000017500000000540310444554664025540 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream.events; import javax.xml.stream.events.StartDocument; import javax.xml.stream.events.XMLEvent; public class StartDocumentEvent extends BaseEvent implements StartDocument { protected String systemId=""; protected String publicId=""; protected String encodingScheme="UTF-8"; protected boolean standalone=false; protected String version="1.0"; private boolean encodingSchemeSet = false; private boolean standaloneSet = false; public StartDocumentEvent(){super();init();} protected void init() {setEventType(XMLEvent.START_DOCUMENT); } public String getSystemId() { return systemId; } // public String getPublicId() { return publicId; } public String getCharacterEncodingScheme() { return encodingScheme; } public boolean isStandalone(){ return standalone; } public String getVersion() { return version; } public void setStandalone(boolean standalone) { standaloneSet = true; this.standalone = standalone; } public void setStandalone(String standalone) { standaloneSet = true; if (standalone == null) {this.standalone = true; return;} if (standalone.equals("yes")) this.standalone = true; else this.standalone = false; } public boolean encodingSet() { return encodingSchemeSet; } public boolean standaloneSet() { return standaloneSet; } public void setEncoding(String encoding) { encodingScheme = encoding; encodingSchemeSet = true; } public void setVersion(String version) { this.version = version; } public void clear() { encodingScheme = "UTF-8"; standalone = true; version = "1.0"; encodingSchemeSet = false; standaloneSet=false; } protected void doWriteAsEncodedUnicode(java.io.Writer writer) throws java.io.IOException { writer.write(""); } } stax-1.2.0.orig/src/com/bea/xml/stream/events/StartElementEvent.java0000644000175000017500000001107010444554664025350 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream.events; import com.bea.xml.stream.util.EmptyIterator; import javax.xml.namespace.NamespaceContext; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.Namespace; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.events.StartElement; import javax.xml.namespace.QName; public class StartElementEvent extends NamedEvent implements StartElement { private List attributes; private List namespaces; private NamespaceContext context; public StartElementEvent() { super();} public StartElementEvent(QName name) { super(name); init(); } public void reset() { if (attributes != null) attributes.clear(); if (namespaces != null) namespaces.clear(); if (context != null) context = null; } public StartElementEvent(StartElement element) { super(element.getName()); init(); setName(element.getName()); Iterator ai = element.getAttributes(); while(ai.hasNext()) addAttribute((Attribute) ai.next()); Iterator ni = element.getNamespaces(); ni = element.getNamespaces(); while(ni.hasNext()) addNamespace((Namespace) ni.next()); } protected void init() {setEventType(XMLEvent.START_ELEMENT); } public Iterator getAttributes() { if (attributes == null) return EmptyIterator.emptyIterator; return attributes.iterator(); } public Iterator getNamespaces() { if (namespaces == null) return EmptyIterator.emptyIterator; return namespaces.iterator(); } public Attribute getAttributeByName(QName name) { if (name == null) return null; Iterator i = getAttributes(); while (i.hasNext()) { Attribute a = (Attribute) i.next(); if (a.getName().equals(name)) return a; } return null; } public void setAttributes(List attributes) { this.attributes = attributes; } public void addAttribute(Attribute attribute) { if (attributes == null) attributes = new ArrayList(); attributes.add(attribute); } public void addNamespace(Namespace attribute) { if (namespaces == null) namespaces = new ArrayList(); namespaces.add(attribute); } public String getNamespaceURI(String prefix) { if (context == null) return null; return (String) context.getNamespaceURI(prefix); } public void setNamespaceContext(NamespaceContext c) { this.context = c; } public NamespaceContext getNamespaceContext() { return context; } public String toString() { String value = "<"+nameAsString(); Iterator ai = getAttributes(); while (ai.hasNext()) value = value +" "+ ai.next().toString(); Iterator ni = getNamespaces(); while (ni.hasNext()) value = value +" "+ ni.next().toString(); value = value + ">"; return value; } protected void doWriteAsEncodedUnicode(java.io.Writer writer) throws java.io.IOException, XMLStreamException { writer.write('<'); QName name = getName(); String prefix = name.getPrefix(); if (prefix != null && prefix.length() > 0) { writer.write(prefix); writer.write(':'); } writer.write(name.getLocalPart()); // Any namespace declarations? Iterator ni = getNamespaces(); while (ni.hasNext()) { writer.write(' '); // Ouch: neither ns nor attr are based on BaseEvent... doh! XMLEvent evt = (XMLEvent) ni.next(); evt.writeAsEncodedUnicode(writer); } // Any attributes? Iterator ai = getAttributes(); while (ai.hasNext()) { writer.write(' '); XMLEvent evt = (XMLEvent) ai.next(); evt.writeAsEncodedUnicode(writer); } writer.write('>'); } } stax-1.2.0.orig/src/com/bea/xml/stream/events/EntityReferenceEvent.java0000644000175000017500000000450010444554664026034 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream.events; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.events.EntityReference; import javax.xml.stream.events.EntityDeclaration; public class EntityReferenceEvent extends BaseEvent implements EntityReference { private String name; private String replacementText; private EntityDeclaration ed; public EntityReferenceEvent() {super();init();} public EntityReferenceEvent(String name, EntityDeclaration ed) { super(); init(); this.name = name; this.ed = ed; } public String getReplacementText() { return ed.getReplacementText(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setReplacementText(String text) { this.replacementText = text; } public String getBaseURI() { return null; } public String getPublicId() { return null; } public String getSystemId() { return null; } public EntityDeclaration getDeclaration() { return ed; } protected void init() {setEventType(XMLEvent.ENTITY_REFERENCE); } protected void doWriteAsEncodedUnicode(java.io.Writer writer) throws java.io.IOException { writer.write('&'); writer.write(getName()); writer.write(';'); } /** * toString() overridden to output more information than what the * default implementation from base event class outputs. */ public String toString() { String replacement = getReplacementText(); if (replacement == null) replacement=""; return "&"+ getName()+ ":='"+ replacement+ "'"; } } stax-1.2.0.orig/src/com/bea/xml/stream/events/BaseEvent.java0000644000175000017500000001032110444554664023611 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream.events; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import javax.xml.stream.XMLStreamException; import javax.xml.namespace.QName; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.Location; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.Characters; import com.bea.xml.stream.util.ElementTypeNames; /** *

Base event class for events to extend from

*/ public abstract class BaseEvent implements XMLEvent, Location { private int eventType = -1; private int line = -1; private int column = -1; private int characterOffset = 0; private String locationURI; public BaseEvent(){} public BaseEvent(int type) { eventType = type; } public int getEventType() { return eventType; } protected void setEventType(int type) { this.eventType = type; } public String getTypeAsString() { return ElementTypeNames.getEventTypeString(eventType); } public boolean isStartElement() { return (eventType == XMLEvent.START_ELEMENT); } public boolean isEndElement() { return (eventType == XMLEvent.END_ELEMENT); } public boolean isEntityReference(){ return (eventType == XMLEvent.ENTITY_REFERENCE); } public boolean isProcessingInstruction(){ return (eventType == XMLEvent.PROCESSING_INSTRUCTION); } public boolean isCharacters(){ return (eventType == XMLEvent.CHARACTERS); } public boolean isStartDocument(){ return (eventType == XMLEvent.START_DOCUMENT); } public boolean isEndDocument(){ return (eventType == XMLEvent.END_DOCUMENT); } public boolean isAttribute(){ return (eventType == XMLEvent.ATTRIBUTE); } public boolean isNamespace(){ return (eventType == XMLEvent.NAMESPACE); } public Location getLocation() { return this; } public String getPublicId() { return null; } public String getSystemId() { return null; } public String getSourceName() { return null; } public int getLineNumber() { return line; } public void setLineNumber(int line) { this.line = line; } public int getColumnNumber() { return column; } public void setColumnNumber(int col) { this.column = col; } public int getCharacterOffset() { return characterOffset; } public void setCharacterOffset(int c) { characterOffset = c; } public String getLocationURI() { return locationURI; } public void setLocationURI(String uri) { locationURI = uri; } public StartElement asStartElement() { return (StartElement) this; } public EndElement asEndElement() { return (EndElement) this; } public Characters asCharacters() { return (Characters) this; } public void recycle() { } public QName getSchemaType() { return null; } public final void writeAsEncodedUnicode(Writer writer) throws XMLStreamException { try { doWriteAsEncodedUnicode(writer); } catch (IOException e) { throw new XMLStreamException(e); } } /** * Template method to be implemented by sub-classes. */ protected abstract void doWriteAsEncodedUnicode(Writer writer) throws IOException, XMLStreamException; public String toString() { StringWriter sw = new StringWriter(64); try { writeAsEncodedUnicode(sw); } catch (XMLStreamException e) { sw.write("[ERROR: "); sw.write(e.toString()); sw.write("]"); } return sw.toString(); } } stax-1.2.0.orig/src/com/bea/xml/stream/events/ProcessingInstructionEvent.java0000644000175000017500000000341010444554664027316 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream.events; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.events.ProcessingInstruction; import javax.xml.namespace.QName; public class ProcessingInstructionEvent extends BaseEvent implements ProcessingInstruction { String name; String content; public ProcessingInstructionEvent() {super();init();} public ProcessingInstructionEvent(String name, String content) { super(); init(); this.name = name; this.content=content; } protected void init() {setEventType(XMLEvent.PROCESSING_INSTRUCTION); } public String getTarget() { return name; } public void setTarget(String target) { name= target; } public void setData(String data) { this.content = data; } public String getData() { return content; } protected void doWriteAsEncodedUnicode(java.io.Writer writer) throws java.io.IOException { writer.write(""); } } stax-1.2.0.orig/src/com/bea/xml/stream/events/NamedEvent.java0000644000175000017500000000343710444554664023775 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream.events; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; public abstract class NamedEvent extends BaseEvent { private QName name; public NamedEvent() {} public NamedEvent(QName name) { this.name = name; } public NamedEvent(String localName) { name = new QName(localName); } public NamedEvent(String prefix, String namespaceURI, String localName) { name = new QName(namespaceURI,localName,prefix); } public QName getName() { return name; } public void setName(QName n) { name = n; } public String nameAsString() { if ("".equals(name.getNamespaceURI())) return name.getLocalPart(); else if (name.getPrefix() != null && !name.getPrefix().equals("")) return "['"+name.getNamespaceURI()+"']:"+ name.getPrefix()+":"+ name.getLocalPart(); else return "['"+name.getNamespaceURI()+"']:"+name.getLocalPart(); } protected abstract void doWriteAsEncodedUnicode(java.io.Writer writer) throws java.io.IOException, XMLStreamException; } stax-1.2.0.orig/src/com/bea/xml/stream/events/EntityDeclarationEvent.java0000644000175000017500000000256410444554664026373 0ustar twernertwernerpackage com.bea.xml.stream.events; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.events.EntityDeclaration; /** * Simple implementation of {@link EntityDeclaration}. Since no external * or unparsed entities are supported (yet?), this is quite simplistic * implementation. * * @author Tatu Saloranta */ public class EntityDeclarationEvent extends BaseEvent implements EntityDeclaration { protected final String name; protected final String replacementText; public EntityDeclarationEvent(String name, String replText) { super(XMLEvent.ENTITY_DECLARATION); this.name = name; replacementText = replText; } public String getReplacementText() { return replacementText; } public String getName() { return name; } public String getBaseURI() { return null; } public String getPublicId() { return null; } public String getSystemId() { return null; } public String getNotationName() { return null; } protected void doWriteAsEncodedUnicode(java.io.Writer writer) throws java.io.IOException { writer.write(""); } } stax-1.2.0.orig/src/com/bea/xml/stream/events/EndDocumentEvent.java0000644000175000017500000000227710444554664025157 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream.events; import javax.xml.stream.events.EndDocument; import javax.xml.stream.events.XMLEvent; public class EndDocumentEvent extends BaseEvent implements EndDocument { public EndDocumentEvent(){super();init();} protected void init() {setEventType(XMLEvent.END_DOCUMENT); } protected void doWriteAsEncodedUnicode(java.io.Writer writer) { // nothing to output } // Separate toString() since writeAsEncodedUnicode doesn't write anything public String toString() { return ""; } } stax-1.2.0.orig/src/com/bea/xml/stream/events/DTDEvent.java0000644000175000017500000000545510444554664023366 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream.events; import java.util.List; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.XMLEventReader; import javax.xml.stream.events.DTD; import javax.xml.stream.events.EntityDeclaration; import javax.xml.stream.events.NotationDeclaration; import com.wutka.dtd.DTDEntity; import com.wutka.dtd.DTDExternalID; import com.wutka.dtd.DTDNotation; import com.wutka.dtd.DTDPublic; import com.wutka.dtd.DTDSystem; public class DTDEvent extends BaseEvent implements DTD { private String dtd; private List notations; private List entities; public DTDEvent() { init(); } public DTDEvent(String dtd) { init(); setDTD(dtd); } protected void init() {setEventType(XMLEvent.DTD); } public static EntityDeclaration createEntityDeclaration(DTDEntity dtdEntity) { return new EntityDeclarationEvent(dtdEntity.getName(), dtdEntity.getValue()); } public static NotationDeclaration createNotationDeclaration(DTDNotation dtdNotation) { DTDExternalID extId = dtdNotation.getExternalID(); String systemId = extId.getSystem(); String publicId = (extId instanceof DTDPublic) ? ((DTDPublic) extId).getPub() : null; return new NotationDeclarationEvent(dtdNotation.getName(), publicId, systemId); } public void setDTD(String dtd) { this.dtd=dtd; } public void setNotations(List l) { notations = l; } public void setEntities(List l) { entities = l; } public Object getProcessedDTD() { return null; } public String getDocumentTypeDeclaration() { return dtd; } public List getEntities() { return entities; } public List getNotations() { return notations; } protected void doWriteAsEncodedUnicode(java.io.Writer writer) throws java.io.IOException { writer.write(" 0) { writer.write('['); writer.write(dtd); writer.write(']'); } writer.write('>'); } } stax-1.2.0.orig/src/com/bea/xml/stream/events/EndElementEvent.java0000644000175000017500000000465110444554664024770 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream.events; import com.bea.xml.stream.util.EmptyIterator; import java.util.ArrayList; import java.util.List; import java.util.Iterator; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.Namespace; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.events.EndElement; public class EndElementEvent extends NamedEvent implements EndElement { private List outOfScopeNamespaces; public EndElementEvent() { super(); init(); } public EndElementEvent(QName name) { super(name); init(); } protected void init() { setEventType(XMLEvent.END_ELEMENT); } public Iterator getNamespaces() { if (outOfScopeNamespaces==null) return EmptyIterator.emptyIterator; return outOfScopeNamespaces.iterator(); } public void addNamespace(Namespace n) { if (outOfScopeNamespaces == null) outOfScopeNamespaces = new ArrayList(); outOfScopeNamespaces.add(n); } public void reset() { if (outOfScopeNamespaces != null) outOfScopeNamespaces.clear(); } public String toString() { String value = ""; return value; } protected void doWriteAsEncodedUnicode(java.io.Writer writer) throws java.io.IOException { writer.write(" 0) { writer.write(prefix); writer.write(':'); } writer.write(name.getLocalPart()); writer.write('>'); } } stax-1.2.0.orig/src/com/bea/xml/stream/events/CommentEvent.java0000644000175000017500000000247510444554664024354 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream.events; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.events.Comment; public class CommentEvent extends CharactersEvent implements Comment { public CommentEvent() {init();} public CommentEvent(String data) { init(); setData(data); } protected void init() {setEventType(XMLEvent.COMMENT); } public String getText() { return getData(); } protected void doWriteAsEncodedUnicode(java.io.Writer writer) throws java.io.IOException { writer.write(""); } } stax-1.2.0.orig/src/com/bea/xml/stream/events/CharactersEvent.java0000644000175000017500000000701410444554664025023 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream.events; import java.io.IOException; import java.io.Writer; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.events.Characters; public class CharactersEvent extends BaseEvent implements Characters { private String data; private boolean isCData=false; private boolean isSpace=false; private boolean isIgnorable=false; public CharactersEvent() { super(); init(); } public CharactersEvent(String data) { super(); init(); setData(data); } public CharactersEvent(String data, boolean isCData) { super(); init(); setData(data); this.isCData = isCData; } public void setSpace(boolean space) { isSpace = space; } public boolean isWhiteSpace() { return isSpace; } public boolean isIgnorableWhiteSpace() { return isIgnorable; } public void setIgnorable(boolean ignorable) { isIgnorable = ignorable; } protected void init() {setEventType(XMLEvent.CHARACTERS); } public String getData() { return data; } public void setData(String data) { this.data = data; } public boolean hasData() {return data != null;} public boolean isCData() { return isCData; } public char[] getDataAsArray() { return data.toCharArray(); } protected void doWriteAsEncodedUnicode(Writer writer) throws IOException { if (isCData) { writer.write(""); } else { String data = getData(); int len = data.length(); if (len > 0) { int i = 0; // Let's see how much we can output without encoding: loop: for (; i < len; ++i) { switch (data.charAt(i)) { case '&': case '<': case '>': // only mandatory as part of ']]>' but let's play it safe break loop; } } // got it all? if (i == len) { writer.write(data); } else { // nope... if (i > 0) { writer.write(data, 0, i); } for (; i < len; ++i) { final char c = data.charAt(i); switch (c) { case '&': writer.write("&"); break; case '<': writer.write("<"); break; case '>': writer.write(">"); break; default: writer.write(c); } } } } } } } stax-1.2.0.orig/src/com/bea/xml/stream/SubReader.java0000644000175000017500000001127010444554664022311 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream; import javax.xml.namespace.QName; import com.bea.xml.stream.util.EmptyIterator; import com.bea.xml.stream.util.ElementTypeNames; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamException; import java.util.List; /** *

Creates a SubReader over a node of a document

*/ public class SubReader extends ReaderDelegate { private int depth=0; private boolean open=true; public SubReader(XMLStreamReader reader) throws XMLStreamException { super(reader); if (!reader.isStartElement()) throw new XMLStreamException("Unable to instantiate a subReader "+ "because the underlying reader "+ "was not on a start element."); open = true; depth++; } public int next() throws XMLStreamException { if (depth <= 0) open = false; int type = super.next(); if (isStartElement()) depth++; if (isEndElement()) { depth--; } return type; } public int nextElement() throws XMLStreamException { next(); while (hasNext() && !isStartElement() && !isEndElement()) next(); return super.getEventType(); } public boolean hasNext() throws XMLStreamException { if (!open) return false; return super.hasNext(); } public boolean moveToStartElement() throws XMLStreamException { if (isStartElement()) return true; while(hasNext()) { if (isStartElement()) return true; else next(); } return false; } public boolean moveToStartElement(String localName) throws XMLStreamException { if (localName == null) return false; while( moveToStartElement() ) { if (localName.equals(getLocalName())) return true; if (!hasNext()) return false; next(); } return false; } public boolean moveToStartElement(String localName, String namespaceUri) throws XMLStreamException { if (localName == null || namespaceUri == null) return false; while(moveToStartElement(localName)) { if(namespaceUri.equals(getNamespaceURI())) return true; if (!hasNext()) return false; next(); } return false; } public boolean moveToEndElement() throws XMLStreamException { if (isEndElement()) return true; while (hasNext()) { if (isEndElement()) return true; else next(); } return false; } public boolean moveToEndElement(String localName) throws XMLStreamException { if (localName == null) return false; while( moveToEndElement() ) { if (localName.equals(getLocalName())) return true; if (!hasNext()) return false; next(); } return false; } public boolean moveToEndElement(String localName, String namespaceUri) throws XMLStreamException { if (localName == null || namespaceUri == null) return false; while(moveToEndElement(localName)) { if(namespaceUri.equals(getNamespaceURI())) return true; if (!hasNext()) return false; next(); } return false; } public static void print(XMLStreamReader r, int depth) throws XMLStreamException { System.out.print("["+depth+"]Sub: "+ElementTypeNames.getEventTypeString(r.getEventType())); if(r.hasName()) System.out.println("->"+r.getLocalName()); else if(r.hasText()) System.out.println("->["+r.getText()+"]"); else System.out.println(); } public static void sub(XMLStreamReader r, int depth) throws Exception { while (r.hasNext()) { print(r,depth); r.next(); } } public static void main(String args[]) throws Exception { MXParser r = new MXParser(); r.setInput(new java.io.FileReader(args[0])); r.moveToStartElement(); r.next(); while(r.moveToStartElement()) { System.out.println("SE->"+r.getName()); XMLStreamReader subr = r.subReader(); sub(subr,1); } } } stax-1.2.0.orig/src/com/bea/xml/stream/XMLOutputFactoryBase.java0000644000175000017500000000661710444554664024452 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream; import java.io.*; import java.util.Hashtable; import javax.xml.transform.Result; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLStreamWriter; import javax.xml.stream.XMLStreamException; /** *

Creates instances of the various interfaces for XML output

*/ public class XMLOutputFactoryBase extends XMLOutputFactory { ConfigurationContextBase config = new ConfigurationContextBase(); public XMLStreamWriter createXMLStreamWriter(java.io.Writer stream) throws XMLStreamException { XMLWriterBase b = new XMLWriterBase(stream); b.setConfigurationContext(config); return b; } public XMLStreamWriter createXMLStreamWriter(java.io.OutputStream stream) throws XMLStreamException { return createXMLStreamWriter(new BufferedWriter(new OutputStreamWriter(stream), 500)); } public XMLStreamWriter createXMLStreamWriter(java.io.OutputStream stream, String encoding) throws XMLStreamException { try { return createXMLStreamWriter(new BufferedWriter(new OutputStreamWriter(stream,encoding), 500)); } catch (java.io.UnsupportedEncodingException uee) { throw new XMLStreamException("Unsupported encoding "+encoding,uee); } } public XMLEventWriter createXMLEventWriter(java.io.OutputStream stream) throws XMLStreamException { return new XMLEventWriterBase(createXMLStreamWriter(stream)); } public XMLEventWriter createXMLEventWriter(java.io.Writer stream) throws XMLStreamException { return new XMLEventWriterBase(createXMLStreamWriter(stream)); } public XMLEventWriter createXMLEventWriter(java.io.OutputStream stream, String encoding) throws XMLStreamException { return new XMLEventWriterBase(createXMLStreamWriter(stream,encoding)); } public void setProperty(java.lang.String name, Object value){ config.setProperty(name,value); } public Object getProperty(java.lang.String name) { return config.getProperty(name); } public boolean isPrefixDefaulting(){ return config.isPrefixDefaulting(); } public void setPrefixDefaulting(boolean value){ config.setPrefixDefaulting(value); } public boolean isPropertySupported(String name) { return config.isPropertySupported(name); } public XMLStreamWriter createXMLStreamWriter(Result result) throws XMLStreamException { throw new UnsupportedOperationException(); } public XMLEventWriter createXMLEventWriter(Result result) throws XMLStreamException { throw new UnsupportedOperationException(); } } stax-1.2.0.orig/src/com/bea/xml/stream/XMLEventAllocatorBase.java0000644000175000017500000002155010444554664024535 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream; import com.bea.xml.stream.util.ElementTypeNames; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.util.XMLEventAllocator; import javax.xml.stream.util.XMLEventConsumer; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.*; import com.bea.xml.stream.util.EmptyIterator; import com.bea.xml.stream.events.DTDEvent; import com.bea.xml.stream.events.EntityDeclarationEvent; /** *

An allocator that creates an event per method call.

*/ public class XMLEventAllocatorBase implements XMLEventAllocator { XMLEventFactory factory; public XMLEventAllocatorBase() { factory = XMLEventFactory.newInstance(); } public XMLEventAllocator newInstance() { return new XMLEventAllocatorBase(); } public static Iterator getAttributes(XMLStreamReader reader) { if (reader.getAttributeCount()==0) return EmptyIterator.emptyIterator; int attributeCount = reader.getAttributeCount(); ArrayList atts = new ArrayList(); for (int i = 0; i < attributeCount; i++){ atts.add(new AttributeBase(reader.getAttributePrefix(i), reader.getAttributeNamespace(i), reader.getAttributeLocalName(i), reader.getAttributeValue(i), reader.getAttributeType(i))); } return atts.iterator(); } public static Iterator getNamespaces(XMLStreamReader reader) { if (reader.getNamespaceCount()==0) return EmptyIterator.emptyIterator; ArrayList ns = new ArrayList(); for (int i = 0; i < reader.getNamespaceCount(); i++){ String prefix = reader.getNamespacePrefix(i); if(prefix == null || prefix.equals("")){ ns.add(new NamespaceBase(reader.getNamespaceURI(i))); } else { ns.add(new NamespaceBase(prefix, reader.getNamespaceURI(i))); } } return ns.iterator(); } public StartElement allocateStartElement(XMLStreamReader reader) throws XMLStreamException { String prefix = reader.getPrefix(); String uri = reader.getNamespaceURI(); if (prefix == null) prefix = ""; if (uri == null) uri = ""; return factory.createStartElement(prefix, uri, reader.getLocalName(), getAttributes(reader), getNamespaces(reader)); } public EndElement allocateEndElement(XMLStreamReader reader) throws XMLStreamException { String prefix = reader.getPrefix(); String uri = reader.getNamespaceURI(); if (prefix == null) prefix = ""; if (uri == null) uri = ""; return factory.createEndElement(prefix, uri, reader.getLocalName(), getNamespaces(reader) ); } public Characters allocateCharacters(XMLStreamReader reader) throws XMLStreamException { int start = reader.getTextStart(); int length = reader.getTextLength(); String result = new String(reader.getTextCharacters(), start, length); if (reader.isWhiteSpace()) return factory.createSpace(result); else return factory.createCharacters(result); } public Characters allocateCData(XMLStreamReader reader) throws XMLStreamException { return factory.createCData(reader.getText()); } public Characters allocateSpace(XMLStreamReader reader) throws XMLStreamException { return factory.createSpace(reader.getText()); } public EntityReference allocateEntityReference(XMLStreamReader reader) throws XMLStreamException { // no factory method for entity declarations... weird. String name = reader.getLocalName(); if (reader instanceof MXParser) { /* Should be able to get additional information (public/system id * for external entities, declaration)... but not yet implemented. */ // !!! TBI } EntityDeclarationEvent ed = new EntityDeclarationEvent(name, reader.getText()); return factory.createEntityReference(name, ed); } public ProcessingInstruction allocatePI(XMLStreamReader reader) throws XMLStreamException { return factory.createProcessingInstruction(reader.getPITarget(), reader.getPIData()); } public Comment allocateComment(XMLStreamReader reader) throws XMLStreamException { return factory.createComment(reader.getText()); } public StartDocument allocateStartDocument(XMLStreamReader reader) throws XMLStreamException { return allocateXMLDeclaration(reader); } public EndDocument allocateEndDocument(XMLStreamReader reader) throws XMLStreamException { return factory.createEndDocument(); } public DTD allocateDTD(XMLStreamReader reader) throws XMLStreamException { /* 07-Mar-2006, TSa: Need to be able to specify notations and * (external unparsed?) entities contained in the DTD, so can not * use the constructor that just takes String.. */ if (reader instanceof MXParser) { MXParser mxp = (MXParser) reader; DTDEvent evt = new DTDEvent(reader.getText()); evt.setNotations((List) mxp.getProperty(MXParser.FEATURE_STAX_NOTATIONS)); evt.setEntities((List) mxp.getProperty(MXParser.FEATURE_STAX_ENTITIES)); return evt; } // Blah. Using some other reader... return factory.createDTD(reader.getText()); } public StartDocument allocateXMLDeclaration(XMLStreamReader reader) throws XMLStreamException { String encoding = reader.getCharacterEncodingScheme(); String version = reader.getVersion(); boolean standalone = reader.isStandalone(); if (encoding != null && version != null && !standalone ) { return factory.createStartDocument(encoding, version, standalone); } if (version != null && encoding != null) return factory.createStartDocument(encoding, version); if (encoding != null) return factory.createStartDocument(encoding); return factory.createStartDocument(); } public XMLEvent allocate(XMLStreamReader reader) throws XMLStreamException { switch (reader.getEventType()) { case XMLEvent.START_ELEMENT: return allocateStartElement(reader); case XMLEvent.END_ELEMENT: return allocateEndElement(reader); case XMLEvent.CHARACTERS: return allocateCharacters(reader); case XMLEvent.SPACE: return allocateCharacters(reader); case XMLEvent.CDATA: return allocateCData(reader); case XMLEvent.ENTITY_REFERENCE: return allocateEntityReference(reader); case XMLEvent.PROCESSING_INSTRUCTION: return allocatePI(reader); case XMLEvent.COMMENT: return allocateComment(reader); // case XMLEvent.XML_DECLARATION: return allocateXMLDeclaration(reader); case XMLEvent.START_DOCUMENT: return allocateStartDocument(reader); case XMLEvent.END_DOCUMENT: return allocateEndDocument(reader); case XMLEvent.DTD: return allocateDTD(reader); default: throw new XMLStreamException("Unable to allocate event["+ reader.getEventType()+" , "+ ElementTypeNames.getEventTypeString(reader.getEventType())+"]"); } // return new com.bea.xml.stream.events.NullEvent(); } public void allocate(XMLStreamReader reader, XMLEventConsumer consumer) throws XMLStreamException { consumer.add(allocate(reader)); } public String toString() { return "NonStaticAllocator"; } } stax-1.2.0.orig/src/com/bea/xml/stream/ReaderDelegate.java0000644000175000017500000001737510444554664023306 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream; import javax.xml.namespace.QName; import javax.xml.namespace.NamespaceContext; import com.bea.xml.stream.util.EmptyIterator; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.Location; import javax.xml.stream.XMLStreamException; import java.util.List; import java.io.InputStream; import java.io.Reader; /** *

An implementation of the ReaderDelegate class

*/ public class ReaderDelegate implements XMLStreamReader { private XMLStreamReader reader; public ReaderDelegate(XMLStreamReader reader) { this.reader = reader; } public void setDelegate(XMLStreamReader reader) { this.reader = reader; } public XMLStreamReader getDelegate() { 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 skip() // throws XMLStreamException //{ // reader.skip(); // } 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 QName getAttributeName(int index) { return reader.getAttributeName(index); } public int getTextCharacters(int sourceStart, char[] target, int targetStart, int length) throws XMLStreamException { return reader.getTextCharacters(sourceStart, target, targetStart, length); } /**********8 public boolean moveToStartElement() throws XMLStreamException { return reader.moveToStartElement(); } public boolean moveToStartElement(String localName) throws XMLStreamException { return reader.moveToStartElement(localName); } public boolean moveToStartElement(String localName, String namespaceUri) throws XMLStreamException { return reader.moveToStartElement(localName,namespaceUri); } public boolean moveToEndElement() throws XMLStreamException { return reader.moveToEndElement(); } public boolean moveToEndElement(String localName) throws XMLStreamException { return reader.moveToEndElement(localName); } public boolean moveToEndElement(String localName, String namespaceUri) throws XMLStreamException { return reader.moveToEndElement(localName,namespaceUri); } public boolean hasAttributes() { return reader.hasAttributes(); } public boolean hasNamespaces() { return reader.hasNamespaces(); } ************/ public String getAttributeValue(String namespaceUri, String localName) { return reader.getAttributeValue(namespaceUri,localName); } public int getAttributeCount() { return reader.getAttributeCount(); } 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 AttributeIterator getAttributes() { // return reader.getAttributes(); // // public NamespaceIterator getNamespaces() { // return reader.getNamespaces(); // } // public XMLStreamReader subReader() // throws XMLStreamException // { // return reader.subReader(); // } // public void recycle() // throws XMLStreamException // { // reader.recycle(); // } public int getEventType() { return reader.getEventType(); } public String getText() { return reader.getText(); } 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 int getLineNumber() { // return reader.getLineNumber(); // } //public int getColumnNumber() { // return reader.getColumnNumber(); // } // public int getCharacterOffset() { // return reader.getCharacterOffset(); // } 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 NamespaceIterator getOutOfScopeNamespaces() { // return reader.getOutOfScopeNamespaces(); // } // public ConfigurationContext getConfigurationContext() { // return reader.getConfigurationContext(); // } public Object getProperty(String name) { return reader.getProperty(name); } } stax-1.2.0.orig/src/com/bea/xml/stream/MXParserFactory.java0000644000175000017500000002200310444554664023462 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream; import java.io.*; import javax.xml.stream.EventFilter; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLReporter; import javax.xml.stream.StreamFilter; import javax.xml.stream.XMLResolver; import javax.xml.stream.XMLStreamException; import javax.xml.stream.util.XMLEventAllocator; import javax.xml.transform.Source; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.dom.DOMSource; import org.xml.sax.InputSource; public class MXParserFactory extends XMLInputFactory { ConfigurationContextBase config = new ConfigurationContextBase(); public static XMLInputFactory newInstance() { return XMLInputFactory.newInstance(); } public XMLStreamReader createXMLStreamReader(Source source) throws XMLStreamException { /* 13-Mar-2006, TSa: Let's add minimal support, to make life bit * easier when interacting with SAX tools... */ if (source instanceof SAXSource) { SAXSource ss = (SAXSource) source; InputSource isource = ss.getInputSource(); if (isource != null) { String sysId = isource.getSystemId(); Reader r = isource.getCharacterStream(); if (r != null) { return createXMLStreamReader(sysId, r); } InputStream in = isource.getByteStream(); if (in != null) { return createXMLStreamReader(sysId, in); } } throw new XMLStreamException("Can only create STaX reader for a SAXSource if Reader or InputStream exposed via getSource(); can not use -- not implemented."); } if (source instanceof DOMSource) { // !!! TBI? //DOMSource sr = (DOMSource) source; } throw new UnsupportedOperationException("XMLInputFactory.createXMLStreamReader("+source.getClass().getName()+") not yet implemented"); } /** * Create a new XMLStreamReader from a java.io.stream * @param stream the InputStream to read from */ public XMLStreamReader createXMLStreamReader(InputStream stream) throws XMLStreamException { MXParser pp = new MXParser(); pp.setInput(stream); pp.setConfigurationContext(config); return pp; } /** * Create a new XMLStreamReader from a java.io.stream * @param stream the InputStream to read from * @param encoding the character encoding of the stream */ public XMLStreamReader createXMLStreamReader(InputStream stream, String encoding) throws XMLStreamException { MXParser pp = new MXParser(); pp.setInput(stream, encoding); pp.setConfigurationContext(config); return pp; } public XMLStreamReader createXMLStreamReader(String systemId, java.io.InputStream stream) throws XMLStreamException { return createXMLStreamReader(stream); } public XMLStreamReader createXMLStreamReader(String systemId, java.io.Reader reader) throws XMLStreamException { return createXMLStreamReader(reader); } public XMLEventReader createXMLEventReader(String systemId, java.io.Reader reader) throws XMLStreamException { return createXMLEventReader(reader); } public XMLEventReader createXMLEventReader(String systemId, java.io.InputStream stream) throws XMLStreamException { return createXMLEventReader(stream); } /** * Create a new XMLEventReader from a reader * @param reader the XML data to read from */ public XMLEventReader createXMLEventReader(Reader reader) throws XMLStreamException { return createXMLEventReader(createXMLStreamReader(reader)); } /** * Create a new XMLEventReader from an XMLStreamReader * @param reader the XMLEventReader to read from */ public XMLEventReader createXMLEventReader(XMLStreamReader reader) throws XMLStreamException { XMLEventReaderBase base; if (config.getEventAllocator() == null) { base = new XMLEventReaderBase(reader); } else { base = new XMLEventReaderBase(reader, (config.getEventAllocator()).newInstance()); } return base; } /** * Create a new XMLEventReader from a JAXP source * @param source the source to read from */ public XMLEventReader createXMLEventReader(Source source) throws XMLStreamException { return createXMLEventReader(createXMLStreamReader(source)); } /** * Create a new XMLEventReader from an input stream * @param stream the InputStream to read from */ public XMLEventReader createXMLEventReader(InputStream stream) throws XMLStreamException { return createXMLEventReader(createXMLStreamReader(stream)); } /** * Create a new XMLEventReader from an input stream * @param stream the InputStream to read from * @param encoding the character encoding of the stream */ public XMLEventReader createXMLEventReader(InputStream stream, String encoding) throws XMLStreamException { return createXMLEventReader(createXMLStreamReader(stream,encoding)); } /** * The resolver that will be set on any XMLStreamReader or XMLEventReader created by this factory instance. */ public XMLResolver getXMLResolver() { return config.getXMLResolver(); } /** * The resolver that will be set on any XMLStreamReader or XMLEventReader created by this factory instance. * @param resolver the resolver to use to resolve references */ public void setXMLResolver(XMLResolver resolver) { config.setXMLResolver(resolver); } /** * Create a filtered reader that wraps the filter around the reader * @param reader the reader to filter * @param filter the filter to apply to the reader */ public XMLStreamReader createFilteredReader(XMLStreamReader reader, StreamFilter filter) throws XMLStreamException { return new StreamReaderFilter(reader,filter); } /** * Create a filtered event reader that wraps the filter around the event reader * @param reader the event reader to wrap * @param filter the filter to apply to the event reader */ public XMLEventReader createFilteredReader(XMLEventReader reader, EventFilter filter) throws XMLStreamException { return new EventReaderFilter(reader,filter); } /** * The reporter that will be set on any XMLStreamReader or XMLEventReader created by this factory instance. */ public XMLReporter getXMLReporter() { return config.getXMLReporter(); } /** * The reporter that will be set on any XMLStreamReader or XMLEventReader created by this factory instance. * @param reporter the resolver to use to report non fatal errors */ public void setXMLReporter(XMLReporter reporter) { config.setXMLReporter(reporter); } /** * Set a user defined event allocator for events * @param allocator the user defined allocator */ public void setEventAllocator(XMLEventAllocator allocator) { config.setEventAllocator(allocator); } /** * Gets the allocator used by streams created with this factory */ public XMLEventAllocator getEventAllocator() { return config.getEventAllocator(); } /** * Specifies that the stream produced by this code will append all adjacent text nodes. */ public void setCoalescing(boolean coalescing){ config.setCoalescing(coalescing); } /** * Indicates whether or not the factory is configured to produced streams that coalesce adjacent text nodes. */ public boolean isCoalescing(){ return config.isCoalescing(); } public void setProperty(String name, Object value) throws IllegalArgumentException { // TODO - cwitt : check against supported feature list config.setProperty(name,value); } public Object getProperty(String name) throws IllegalArgumentException { return config.getProperty(name); } public XMLStreamReader createXMLStreamReader(Reader in) throws XMLStreamException { MXParser pp = new MXParser(); pp.setInput(in); pp.setConfigurationContext(config); return pp; } public boolean isPropertySupported(String name) { return config.isPropertySupported(name); } } stax-1.2.0.orig/src/com/bea/xml/stream/ConfigurationContextBase.java0000644000175000017500000001570210444554664025410 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream; import java.util.Enumeration; import java.util.Hashtable; import java.util.HashSet; import javax.xml.stream.util.XMLEventAllocator; import javax.xml.stream.EventFilter; import javax.xml.stream.StreamFilter; import javax.xml.stream.XMLReporter; import javax.xml.stream.XMLResolver; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; public class ConfigurationContextBase { private static HashSet supportedFeatures; private static String EVENT_FILTER = "RI_EVENT_FILTER"; private static String STREAM_FILTER = "RI_STREAM_FILTER"; private static String NOTATIONS = "javax.xml.stream.notations"; private static String ENTITIES = "javax.xml.stream.entities"; static final String REPORT_CDATA = "http://java.sun.com/xml/stream/properties/report-cdata-event"; static { supportedFeatures = new HashSet(); supportedFeatures.add(XMLInputFactory.IS_VALIDATING); supportedFeatures.add(XMLInputFactory.IS_COALESCING); supportedFeatures.add(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES); supportedFeatures.add(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES); supportedFeatures.add(XMLOutputFactory.IS_REPAIRING_NAMESPACES); supportedFeatures.add(XMLInputFactory.IS_NAMESPACE_AWARE); supportedFeatures.add(XMLInputFactory.SUPPORT_DTD); supportedFeatures.add(XMLInputFactory.REPORTER); supportedFeatures.add(XMLInputFactory.RESOLVER); supportedFeatures.add(XMLInputFactory.ALLOCATOR); supportedFeatures.add(NOTATIONS); supportedFeatures.add(ENTITIES); supportedFeatures.add(REPORT_CDATA); }; private Hashtable features = new Hashtable(); public ConfigurationContextBase() { features.put(XMLInputFactory.IS_VALIDATING, Boolean.FALSE); features.put(XMLInputFactory.IS_COALESCING, Boolean.FALSE); features.put(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE); features.put(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE); features.put(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE); features.put(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE); features.put(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE); } public void setEventAllocator(XMLEventAllocator a) { features.put(XMLInputFactory.ALLOCATOR,a); } public XMLEventAllocator getEventAllocator() { return (XMLEventAllocator) features.get(XMLInputFactory.ALLOCATOR); } public void setProperty(String name, Object feature) { if (name.equals(XMLInputFactory.IS_VALIDATING)) { setValidating(((Boolean) feature).booleanValue()); } else if (name.equals(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES)) { setSupportExternalEntities(((Boolean) feature).booleanValue()); } else if (name.equals(XMLInputFactory.IS_NAMESPACE_AWARE)) { setNamespaceAware(((Boolean) feature).booleanValue()); } else { check(name); features.put(name,feature); } } public void check(String name) { if (!supportedFeatures.contains(name)) throw new IllegalArgumentException("Unable to access unsupported "+ "property "+name); } public Object getProperty(String name) { check(name); return features.get(name); } public void setXMLReporter(XMLReporter r) { features.put(XMLInputFactory.REPORTER,r); } public XMLReporter getXMLReporter() { return (XMLReporter) features.get(XMLInputFactory.REPORTER); } public void setXMLResolver(XMLResolver r) { features.put(XMLInputFactory.RESOLVER,r); } public XMLResolver getXMLResolver() { return (XMLResolver) features.get(XMLInputFactory.RESOLVER); } public boolean getBool(String name) { check(name); Boolean val = (Boolean) features.get(name); return val.booleanValue(); } public void setBool(String name, boolean val) { check(name); features.put(name, val ? Boolean.TRUE : Boolean.FALSE); } public void setCoalescing(boolean val) { setBool(XMLInputFactory.IS_COALESCING,val); } public boolean isCoalescing() { return getBool(XMLInputFactory.IS_COALESCING); } public void setValidating(boolean val) { if (val) { throw new IllegalArgumentException("This implementation does not " + "support validation"); } // No need to re-set to the same value... //setBool(XMLInputFactory.IS_VALIDATING,val); } public boolean isValidating() { return getBool(XMLInputFactory.IS_VALIDATING); } public void setReplacingEntities(boolean val) { setBool(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES,val); } public boolean isReplacingEntities() { return getBool(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES); } public void setSupportExternalEntities(boolean val) { if (val) { throw new IllegalArgumentException("This implementation does not " + "resolve external entities "); } // Already false... //setBool(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES,val); } public boolean isSupportingExternalEntities() { return getBool(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES); } public void setPrefixDefaulting(boolean val) { setBool(XMLOutputFactory.IS_REPAIRING_NAMESPACES,val); } public boolean isPrefixDefaulting() { return getBool(XMLOutputFactory.IS_REPAIRING_NAMESPACES); } public void setNamespaceAware(boolean val) { /* 07-Sep-2005, TSa: since implementation does not really support * non-ns-aware mode, let's throw an exception: */ if (!val) { throw new IllegalArgumentException("This implementation does not allow disabling namespace processing"); } // Already true //setBool(XMLInputFactory.IS_NAMESPACE_AWARE,val); } public boolean isNamespaceAware() { return getBool(XMLInputFactory.IS_NAMESPACE_AWARE); } public String getVersion() { return "1.0"; } public Enumeration getProperties() { return features.keys(); } public boolean isPropertySupported(String name) { return supportedFeatures.contains(name); } } stax-1.2.0.orig/src/com/bea/xml/stream/MXParser.java0000644000175000017500000047011010444554664022140 0ustar twernertwerner/* * Copyright (c) 2002 Extreme! Lab, Indiana University. All rights reserved. * * This software is open source. See the bottom of this file for the licence. * */ package com.bea.xml.stream; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Vector; import java.util.Enumeration; import java.util.Iterator; import javax.xml.namespace.NamespaceContext; import com.bea.xml.stream.events.DTDEvent; import com.bea.xml.stream.reader.XmlReader; import com.bea.xml.stream.util.EmptyIterator; import com.bea.xml.stream.util.ElementTypeNames; import javax.xml.XMLConstants; import javax.xml.namespace.QName; import javax.xml.stream.Location; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamException; import com.wutka.dtd.DTDParser; import com.wutka.dtd.DTD; import com.wutka.dtd.DTDAttlist; import com.wutka.dtd.DTDAttribute; import com.wutka.dtd.DTDElement; import com.wutka.dtd.DTDEntity; import com.wutka.dtd.DTDNotation; import javax.xml.stream.XMLInputFactory; /** * XML Streaming Parser. * * @author Aleksander Slominski */ public class MXParser implements XMLStreamReader, Location { protected final static char CHAR_UTF8_BOM = '\uFEFF'; protected final static int MAX_UNICODE_CHAR = 0x10FFFF; protected static final String FEATURE_XML_ROUNDTRIP= "http://xmlpull.org/v1/doc/features.html#xml-roundtrip"; protected static final String FEATURE_NAMES_INTERNED = "http://xmlpull.org/v1/doc/features.html#names-interned"; public static final String FEATURE_PROCESS_DOCDECL = "http://xmlpull.org/v1/doc/features.html#process-docdecl"; //"http://java.sun.com/xml/stream/properties/report-cdata-event" public static final String FEATURE_STAX_NOTATIONS = "javax.xml.stream.notations"; public static final String FEATURE_STAX_ENTITIES = "javax.xml.stream.entities"; /** * Since EOF exception has no descriptive message, let's use something * slightly more meaningful... */ final static String EOF_MSG = "Unexpected end of stream"; private boolean reportCdataEvent = false; /** * These constants are used for diagnostics messages, and need to * match with ones from {@link XMLStreamConstants}. */ public static final String [] TYPES = { "[UNKNOWN]", // 0 not used "START_ELEMENT", "END_ELEMENT", "PROCESSING_INSTRUCTION", "CHARACTERS", // "TEXT", "COMMENT", "SPACE", // "IGNORABLE_WHITESPACE", "START_DOCUMENT", "END_DOCUMENT", "ENTITY_REFERENCE", "ATTRIBUTE", "DTD", "CDATA", "NAMESPACE", "NOTATION_DECLARATION", "ENTITY_DECLARATION", }; // TODO - cwitt : split TEXT into CHARACTERS and WHITESPACE private static final int TEXT=0x00004000; // TODO - cwitt : remove DOCDECL ? private static final int DOCDECL=0x00008000; // TODO - cwitt : move to XMLEvent ? // will not be available in event interface (info under start_document // in that case), just in cursor //private static final int XML_DECLARATION=0x00010000; // NOTE - cwitt : from XmlPullParser interface /** * This constant defines URI used for "no namespace" (when the default * namespace not defined, for elements; when attribute has no prefix, * or for all URIs if namespace support is disabled). */ public static final String NO_NAMESPACE = null; /** * Implementation notice: * the is instance variable that controls if newString() is interning. *

NOTE: newStringIntern always returns interned strings * and newString MAY return interned String depending on this variable. *

NOTE: by default in this minimal implementation it is false! */ protected boolean allStringsInterned; protected void resetStringCache() { //System.out.println("resetStringCache() minimum called"); } protected String newString(char[] cbuf, int off, int len) { return new String(cbuf, off, len); } protected String newStringIntern(char[] cbuf, int off, int len) { return (new String(cbuf, off, len)).intern(); } private static final boolean TRACE_SIZING = false; // NOTE: features are not resetable and typicaly defaults to false ... // TODO - cwitt : we always want to set these to true, so the featues // don't need to be defined in the factory, will remove them later here public static final String FEATURE_PROCESS_NAMESPACES = "http://xmlpull.org/v1/doc/features.html#process-namespaces"; protected boolean processNamespaces = true; protected boolean roundtripSupported = true; // global parser state protected int lineNumber; protected int columnNumber; protected boolean seenRoot; protected boolean reachedEnd; protected int eventType; protected boolean emptyElementTag; // element stack protected int depth; protected char[] elRawName[]; protected int elRawNameEnd[]; //pnrotected int elRawNameEnd[]; protected String elName[]; protected String elPrefix[]; protected String elUri[]; //protected String elValue[]; protected int elNamespaceCount[]; /** * XML version found from the xml declaration, if any. */ protected String xmlVersion=null; /** * Flag that indicates whether 'standalone="yes"' was found from * the xml declaration. */ protected boolean standalone=false; protected boolean standaloneSet=false; protected String charEncodingScheme; protected String piTarget; protected String piData; /** * If the internal DTD subset was parsed, this object will be non-null, * and can be used for accessing entities, elements and notations * declared in the internal subset. */ protected DTD mDtdIntSubset; protected HashMap defaultAttributes; /** * Make sure that we have enough space to keep element stack if passed size. * It will always create one additional slot then current depth */ protected void ensureElementsCapacity() { int elStackSize = elName != null ? elName.length : 0; if( (depth + 1) >= elStackSize) { // we add at least one extra slot ... int newSize = (depth >= 7 ? 2 * depth : 8) + 2; // = lucky 7 + 1 //25 if(TRACE_SIZING) { System.err.println("elStackSize "+elStackSize+" ==> "+newSize); } boolean needsCopying = elStackSize > 0; String[] arr = null; arr = new String[newSize]; if(needsCopying) System.arraycopy(elName, 0, arr, 0, elStackSize); elName = arr; arr = new String[newSize]; if(needsCopying) System.arraycopy(elPrefix, 0, arr, 0, elStackSize); elPrefix = arr; arr = new String[newSize]; if(needsCopying) System.arraycopy(elUri, 0, arr, 0, elStackSize); elUri = arr; int[] iarr = new int[newSize]; if(needsCopying) { System.arraycopy(elNamespaceCount, 0, iarr, 0, elStackSize); } else { // special initialization iarr[0] = 0; } elNamespaceCount = iarr; //TODO: avoid using element raw name ... iarr = new int[newSize]; if(needsCopying) { System.arraycopy(elRawNameEnd, 0, iarr, 0, elStackSize); } elRawNameEnd = iarr; char[][] carr = new char[newSize][]; if(needsCopying) { System.arraycopy(elRawName, 0, carr, 0, elStackSize); } elRawName = carr; // arr = new String[newSize]; // if(needsCopying) System.arraycopy(elLocalName, 0, arr, 0, elStackSize); // elLocalName = arr; // arr = new String[newSize]; // if(needsCopying) System.arraycopy(elDefaultNs, 0, arr, 0, elStackSize); // elDefaultNs = arr; // int[] iarr = new int[newSize]; // if(needsCopying) System.arraycopy(elNsStackPos, 0, iarr, 0, elStackSize); // for (int i = elStackSize; i < iarr.length; i++) // { // iarr[i] = (i > 0) ? -1 : 0; // } // elNsStackPos = iarr; //assert depth < elName.length; } } // nameStart / name lookup tables based on XML 1.1 http://www.w3.org/TR/2001/WD-xml11-20011213/ protected static final int LOOKUP_MAX = 0x400; protected static final char LOOKUP_MAX_CHAR = (char)LOOKUP_MAX; // protected static int lookupNameStartChar[] = new int[ LOOKUP_MAX_CHAR / 32 ]; // protected static int lookupNameChar[] = new int[ LOOKUP_MAX_CHAR / 32 ]; protected static boolean lookupNameStartChar[] = new boolean[ LOOKUP_MAX ]; protected static boolean lookupNameChar[] = new boolean[ LOOKUP_MAX ]; private static final void setName(char ch) //{ lookupNameChar[ (int)ch / 32 ] |= (1 << (ch % 32)); } { lookupNameChar[ ch ] = true; } private static final void setNameStart(char ch) //{ lookupNameStartChar[ (int)ch / 32 ] |= (1 << (ch % 32)); setName(ch); } { lookupNameStartChar[ ch ] = true; setName(ch); } static { setNameStart(':'); for (char ch = 'A'; ch <= 'Z'; ++ch) setNameStart(ch); setNameStart('_'); for (char ch = 'a'; ch <= 'z'; ++ch) setNameStart(ch); for (char ch = '\u00c0'; ch <= '\u02FF'; ++ch) setNameStart(ch); for (char ch = '\u0370'; ch <= '\u037d'; ++ch) setNameStart(ch); for (char ch = '\u037f'; ch < '\u0400'; ++ch) setNameStart(ch); setName('-'); setName('.'); for (char ch = '0'; ch <= '9'; ++ch) setName(ch); setName('\u00b7'); for (char ch = '\u0300'; ch <= '\u036f'; ++ch) setName(ch); } //private final static boolean isNameStartChar(char ch) { protected boolean isNameStartChar(char ch) { return (ch < LOOKUP_MAX_CHAR && lookupNameStartChar[ ch ]) || (ch >= LOOKUP_MAX_CHAR && ch <= '\u2027') || (ch >= '\u202A' && ch <= '\u218F') || (ch >= '\u2800' && ch <= '\uFFEF') ; // if(ch < LOOKUP_MAX_CHAR) return lookupNameStartChar[ ch ]; // else return ch <= '\u2027' // || (ch >= '\u202A' && ch <= '\u218F') // || (ch >= '\u2800' && ch <= '\uFFEF') // ; //return false; // return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == ':' // || (ch >= '0' && ch <= '9'); // if(ch < LOOKUP_MAX_CHAR) return (lookupNameStartChar[ (int)ch / 32 ] & (1 << (ch % 32))) != 0; // if(ch <= '\u2027') return true; // //[#x202A-#x218F] // if(ch < '\u202A') return false; // if(ch <= '\u218F') return true; // // added pairts [#x2800-#xD7FF] | [#xE000-#xFDCF] | [#xFDE0-#xFFEF] | [#x10000-#x10FFFF] // if(ch < '\u2800') return false; // if(ch <= '\uFFEF') return true; // return false; // else return (supportXml11 && ( (ch < '\u2027') || (ch > '\u2029' && ch < '\u2200') ... } //private final static boolean isNameChar(char ch) { protected boolean isNameChar(char ch) { //return isNameStartChar(ch); // if(ch < LOOKUP_MAX_CHAR) return (lookupNameChar[ (int)ch / 32 ] & (1 << (ch % 32))) != 0; return (ch < LOOKUP_MAX_CHAR && lookupNameChar[ ch ]) || (ch >= LOOKUP_MAX_CHAR && ch <= '\u2027') || (ch >= '\u202A' && ch <= '\u218F') || (ch >= '\u2800' && ch <= '\uFFEF') ; //return false; // return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == ':' // || (ch >= '0' && ch <= '9'); // if(ch < LOOKUP_MAX_CHAR) return (lookupNameStartChar[ (int)ch / 32 ] & (1 << (ch % 32))) != 0; //else return // else if(ch <= '\u2027') return true; // //[#x202A-#x218F] // else if(ch < '\u202A') return false; // else if(ch <= '\u218F') return true; // // added pairts [#x2800-#xD7FF] | [#xE000-#xFDCF] | [#xFDE0-#xFFEF] | [#x10000-#x10FFFF] // else if(ch < '\u2800') return false; // else if(ch <= '\uFFEF') return true; //else return false; } protected boolean isS(char ch) { return (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t'); // || (supportXml11 && (ch == '\u0085' || ch == '\u2028'); } //protected boolean isChar(char ch) { return (ch < '\uD800' || ch > '\uDFFF') // ch != '\u0000' ch < '\uFFFE' protected void checkCharValidity(int ch, boolean surrogatesOk) throws XMLStreamException { if (ch < 0x0020) { if (!isS((char) ch)) { throw new XMLStreamException("Illegal white space character (code 0x"+Integer.toHexString(ch)+")"); } } else if (ch >= 0xD800) { // surrogates illegal at this level if (ch <= 0xDFFF) { if (!surrogatesOk) { throw new XMLStreamException("Illegal character (code 0x"+Integer.toHexString(ch)+"): surrogate characters are not valid XML characters", getLocation()); } } else if (ch > MAX_UNICODE_CHAR) { throw new XMLStreamException("Illegal character (code 0x"+Integer.toHexString(ch)+"), past max. Unicode character 0x"+Integer.toHexString(MAX_UNICODE_CHAR), getLocation()); } } } // attribute stack protected int attributeCount; protected String attributeName[]; protected int attributeNameHash[]; //protected int attributeNameStart[]; //protected int attributeNameEnd[]; protected String attributePrefix[]; protected String attributeUri[]; protected String attributeValue[]; //protected int attributeValueStart[]; //protected int attributeValueEnd[]; /** * Make sure that in attributes temporary array is enough space. */ protected void ensureAttributesCapacity(int size) { int attrPosSize = attributeName != null ? attributeName.length : 0; if(size >= attrPosSize) { int newSize = size > 7 ? 2 * size : 8; // = lucky 7 + 1 //25 if(TRACE_SIZING) { System.err.println("attrPosSize "+attrPosSize+" ==> "+newSize); } boolean needsCopying = attrPosSize > 0; String[] arr = null; arr = new String[newSize]; if(needsCopying) System.arraycopy(attributeName, 0, arr, 0, attrPosSize); attributeName = arr; arr = new String[newSize]; if(needsCopying) System.arraycopy(attributePrefix, 0, arr, 0, attrPosSize); attributePrefix = arr; arr = new String[newSize]; if(needsCopying) System.arraycopy(attributeUri, 0, arr, 0, attrPosSize); attributeUri = arr; arr = new String[newSize]; if(needsCopying) System.arraycopy(attributeValue, 0, arr, 0, attrPosSize); attributeValue = arr; if( ! allStringsInterned ) { int[] iarr = new int[newSize]; if(needsCopying) System.arraycopy(attributeNameHash, 0, iarr, 0, attrPosSize); attributeNameHash = iarr; } arr = null; // //assert attrUri.length > size } } /* TSa, 28-Oct-2004: Need to either initialize them here, or check for * nulls later on. This seems to work */ private final static String[] NO_STRINGS = new String[0]; private final static int[] NO_INTS = new int[0]; private final static char[] NO_CHARS = new char[0]; // namespace stack protected int namespaceEnd; protected String namespacePrefix[] = NO_STRINGS; protected int namespacePrefixHash[]; protected String namespaceUri[] = NO_STRINGS; protected void ensureNamespacesCapacity(int size) { int namespaceSize = namespacePrefix != null ? namespacePrefix.length : 0; if(size >= namespaceSize) { int newSize = size > 7 ? 2 * size : 8; // = lucky 7 + 1 //25 if(TRACE_SIZING) { System.err.println("namespaceSize "+namespaceSize+" ==> "+newSize); } String[] newNamespacePrefix = new String[newSize]; String[] newNamespaceUri = new String[newSize]; if(namespacePrefix != null) { System.arraycopy( namespacePrefix, 0, newNamespacePrefix, 0, namespaceEnd); System.arraycopy( namespaceUri, 0, newNamespaceUri, 0, namespaceEnd); } namespacePrefix = newNamespacePrefix; namespaceUri = newNamespaceUri; if( ! allStringsInterned ) { int[] newNamespacePrefixHash = new int[newSize]; if(namespacePrefixHash != null) { System.arraycopy( namespacePrefixHash, 0, newNamespacePrefixHash, 0, namespaceEnd); } namespacePrefixHash = newNamespacePrefixHash; } //prefixesSize = newSize; // //assert nsPrefixes.length > size && nsPrefixes.length == newSize } } // local namespace stack protected int localNamespaceEnd; protected String localNamespacePrefix[]; protected int localNamespacePrefixHash[]; protected String localNamespaceUri[]; protected void ensureLocalNamespacesCapacity(int size) { int localNamespaceSize = localNamespacePrefix != null ? localNamespacePrefix.length : 0; if(size >= localNamespaceSize) { int newSize = size > 7 ? 2 * size : 8; // = lucky 7 + 1 //25 if(TRACE_SIZING) { System.err.println("localNamespaceSize "+localNamespaceSize+" ==> "+newSize); } String[] newLocalNamespacePrefix = new String[newSize]; String[] newLocalNamespaceUri = new String[newSize]; if(localNamespacePrefix != null) { System.arraycopy( localNamespacePrefix, 0, newLocalNamespacePrefix, 0, localNamespaceEnd); System.arraycopy( localNamespaceUri, 0, newLocalNamespaceUri, 0, localNamespaceEnd); } localNamespacePrefix = newLocalNamespacePrefix; localNamespaceUri = newLocalNamespaceUri; if( ! allStringsInterned ) { int[] newLocalNamespacePrefixHash = new int[newSize]; if(localNamespacePrefixHash != null) { System.arraycopy( localNamespacePrefixHash, 0, newLocalNamespacePrefixHash, 0, localNamespaceEnd); } localNamespacePrefixHash = newLocalNamespacePrefixHash; } //prefixesSize = newSize; // //assert nsPrefixes.length > size && nsPrefixes.length == newSize } } public int getLocalNamespaceCount() { int startNs = elNamespaceCount[ depth - 1 ]; return namespaceEnd-startNs; } // This returns an array of all the namespaces uris defined // in the scope of this element // To index into it you need to add the namespaceCount from // the previous depth private String getLocalNamespaceURI(int pos) { return namespaceUri[pos]; } // This returns an array of all the namespaces prefixes defined // in the scope of this element // the prefix for the default ns is bound to null // To index into it you need to add the namespaceCount from // the previous depth private String getLocalNamespacePrefix(int pos){ return namespacePrefix[pos]; } /** * simplistic implementation of hash function that has constant * time to compute - so it also means diminishing hash quality for long strings * but for XML parsing it should be good enough ... */ protected static final int fastHash( char ch[], int off, int len ) { if(len == 0) return 0; //assert len >0 int hash = ch[off]; // hash at beginnig //try { hash = (hash << 7) + ch[ off + len - 1 ]; // hash at the end //} catch(ArrayIndexOutOfBoundsException aie) { // aie.printStackTrace(); //should never happen ... // throw new RuntimeException("this is violation of pre-condition"); //} if(len > 16) hash = (hash << 7) + ch[ off + (len / 4)]; // 1/4 from beginning if(len > 8) hash = (hash << 7) + ch[ off + (len / 2)]; // 1/2 of string size ... // notice that hash is at most done 3 times <<7 so shifted by 21 bits 8 bit value // so max result == 29 bits so it is quite just below 31 bits for long (2^32) ... //assert hash >= 0; return hash; } // entity replacement stack protected int entityEnd; protected String entityName[]; protected char[] entityNameBuf[]; protected int entityNameHash[]; protected char[] entityReplacementBuf[]; protected String entityReplacement[]; protected void ensureEntityCapacity() { int entitySize = entityReplacementBuf != null ? entityReplacementBuf.length : 0; if(entityEnd >= entitySize) { int newSize = (entityEnd > 7) ? (2 * entityEnd) : 8; // = lucky 7 + 1 //25 if(TRACE_SIZING) { System.err.println("entitySize "+entitySize+" ==> "+newSize); } String[] newEntityName = new String[newSize]; char[] newEntityNameBuf[] = new char[newSize][]; String[] newEntityReplacement = new String[newSize]; char[] newEntityReplacementBuf[] = new char[newSize][]; if(entityName != null) { System.arraycopy(entityName, 0, newEntityName, 0, entityEnd); System.arraycopy(entityNameBuf, 0, newEntityNameBuf, 0, entityEnd); System.arraycopy(entityReplacement, 0, newEntityReplacement, 0, entityEnd); System.arraycopy(entityReplacementBuf, 0, newEntityReplacementBuf, 0, entityEnd); } entityName = newEntityName; entityNameBuf = newEntityNameBuf; entityReplacement = newEntityReplacement; entityReplacementBuf = newEntityReplacementBuf; if( ! allStringsInterned ) { int[] newEntityNameHash = new int[newSize]; if(entityNameHash != null) { System.arraycopy(entityNameHash, 0, newEntityNameHash, 0, entityEnd); } entityNameHash = newEntityNameHash; } } } // input buffer management protected static final int READ_CHUNK_SIZE = 8*1024; //max data chars in one read() call protected Reader reader; protected String inputEncoding; protected int bufLoadFactor = 95; // 99% //protected int bufHardLimit; // only matters when expanding /** * Logics for this should be clarified... but it looks like we use a * 8k buffer if there's 1M of free memory or more, otherwise just * 256 bytes? */ protected char buf[] = new char[(Runtime.getRuntime().freeMemory() > 1000000L) ? READ_CHUNK_SIZE : 256 ]; protected int bufSoftLimit = ( bufLoadFactor * buf.length ) /100; // desirable size of buffer protected int bufAbsoluteStart; // this is buf protected int bufStart; protected int bufEnd; protected int pos; protected int posStart; protected int posEnd; protected char pc[] = new char[ Runtime.getRuntime().freeMemory() > 1000000L ? READ_CHUNK_SIZE : 64 ]; protected int pcStart; protected int pcEnd; // parsing state //protected boolean needsMore; //protected boolean seenMarkup; protected boolean usePC; protected boolean seenStartTag; protected boolean seenEndTag; protected boolean pastEndTag; protected boolean seenAmpersand; protected boolean seenMarkup; protected boolean seenDocdecl; // transient variable set during each call to next/Token() protected boolean tokenize; /** * Lazily-constructed String that contains what getText() returns; * cleared by tokenizer before parsing new events */ protected String text; protected String entityRefName; /** * Replacement value for the current entity, when automatic entity * expansion is disabled. Will always refer to some other array; * either globally shared ones (for general entities), or the temp * buffer for char entities. As such, does not need to be cleared * by tokenizer: will get properly overwritten as needed */ protected char[] entityValue = null; private void reset() { //System.out.println("reset() called"); lineNumber = 1; columnNumber = 0; seenRoot = false; reachedEnd = false; eventType = XMLStreamConstants.START_DOCUMENT; emptyElementTag = false; depth = 0; attributeCount = 0; namespaceEnd = 0; localNamespaceEnd = 0; entityEnd = 0; reader = null; inputEncoding = null; bufAbsoluteStart = 0; bufEnd = bufStart = 0; pos = posStart = posEnd = 0; pcEnd = pcStart = 0; usePC = false; seenStartTag = false; seenEndTag = false; pastEndTag = false; seenAmpersand = false; seenMarkup = false; seenDocdecl = false; resetStringCache(); } public MXParser() { } /** * Method setFeature * * @param name a String * @param state a boolean * * @throws XMLStreamException * */ public void setFeature(String name, boolean state) throws XMLStreamException { if(name == null) throw new IllegalArgumentException("feature name should not be nulll"); if(FEATURE_PROCESS_NAMESPACES.equals(name)) { if(eventType != XMLStreamConstants.START_DOCUMENT) throw new XMLStreamException( "namespace processing feature can only be changed before parsing", getLocation()); processNamespaces = state; // } else if(FEATURE_REPORT_NAMESPACE_ATTRIBUTES.equals(name)) { // if(type != XMLStreamConstants.START_DOCUMENT) throw new XMLStreamException( // "namespace reporting feature can only be changed before parsing", // getLineNumber(), getColumnNumber(), getPositionDescription(), null); // reportNsAttribs = state; } else if(FEATURE_NAMES_INTERNED.equals(name)) { if(state != false) { throw new XMLStreamException( "interning names in this implementation is not supported"); } } else if(FEATURE_PROCESS_DOCDECL.equals(name)) { if(state != false) { throw new XMLStreamException( "processing DOCDECL is not supported"); } //} else if(REPORT_DOCDECL.equals(name)) { // paramNotifyDoctype = state; } else if(FEATURE_XML_ROUNDTRIP.equals(name)) { if(state == false) { throw new XMLStreamException( "roundtrip feature can not be switched off"); } } else { throw new XMLStreamException("unknown feature "+name); } } /** Unknown properties are always returned as false */ public boolean getFeature(String name) { if(name == null) throw new IllegalArgumentException("feature name should not be null"); if(FEATURE_PROCESS_NAMESPACES.equals(name)) { return processNamespaces; // } else if(FEATURE_REPORT_NAMESPACE_ATTRIBUTES.equals(name)) { // return reportNsAttribs; } else if(FEATURE_NAMES_INTERNED.equals(name)) { return false; } else if(FEATURE_PROCESS_DOCDECL.equals(name)) { return false; //} else if(REPORT_DOCDECL.equals(name)) { // return paramNotifyDoctype; } else if(FEATURE_XML_ROUNDTRIP.equals(name)) { return true; //roundtripSupported; } return false; } public void setProperty(String name, Object value) throws XMLStreamException { throw new XMLStreamException("unsupported property: '"+name+"'"); } public boolean checkForXMLDecl() throws XMLStreamException { try { BufferedReader breader = new BufferedReader(reader,7); reader = breader; breader.mark(7); // Hmmh. May get UTF-8 BOM, apparently... int ch = breader.read(); if (ch == CHAR_UTF8_BOM) { // let's just consume it no matter what breader.mark(7); ch = breader.read(); } if (ch == '<' && breader.read() == '?' && breader.read() == 'x' && breader.read() == 'm' && breader.read() == 'l') { breader.reset(); return true; } breader.reset(); return false; } catch (IOException e) { throw new XMLStreamException(e); } } public void setInput(Reader in) throws XMLStreamException { reset(); reader = in; if(checkForXMLDecl()) { next(); } } public void setInput(InputStream in) throws XMLStreamException { try { Reader r = XmlReader.createReader(in); /* 07-Mar-2006, TSa: Let's figure out encoding we detected * (whether based on xml declaration, BOM, or recognized * signature)... */ String enc = null; if (r instanceof XmlReader.BaseReader) { enc = ((XmlReader.BaseReader) r).getEncoding(); } setInput(r); if (enc != null) { inputEncoding = enc; } } catch (IOException e) { throw new XMLStreamException(e); } } public void setInput(InputStream inputStream, String inputEncoding) throws XMLStreamException { if(inputStream == null) { throw new IllegalArgumentException("input stream can not be null"); } Reader reader; try { reader = (inputEncoding != null) ? XmlReader.createReader(inputStream, inputEncoding) : XmlReader.createReader(inputStream); } catch (IOException ioe) { String encMsg = (inputEncoding == null) ? "(for encoding '"+inputEncoding+"')" : ""; throw new XMLStreamException("could not create reader "+encMsg+": "+ioe, getLocation(), ioe); } setInput(reader); //must be here as reest() was called in setInput() and has set this.inputEncoding to null ... if (inputEncoding != null) { this.inputEncoding = inputEncoding; } } public String getInputEncoding() { return inputEncoding; } public void defineEntityReplacementText(String entityName, String replacementText) throws XMLStreamException { // throw new XMLStreamException("not allowed"); //protected char[] entityReplacement[]; ensureEntityCapacity(); // this is to make sure that if interning works we will take advatage of it ... char[] ch = entityName.toCharArray(); this.entityName[entityEnd] = newString(ch, 0, entityName.length()); entityNameBuf[entityEnd] = ch; entityReplacement[entityEnd] = replacementText; /* 06-Nov-2004, TSa: Null is apparently returned for external * entities (including parsed ones); to prevent an NPE, let's * just use a shared dummy array... (could use null too?) */ ch = (replacementText == null) ? NO_CHARS : replacementText.toCharArray(); entityReplacementBuf[entityEnd] = ch; if(!allStringsInterned) { entityNameHash[ entityEnd ] = fastHash(entityNameBuf[entityEnd], 0, entityNameBuf[entityEnd].length); } ++entityEnd; //TODO disallow < or & in entity replacement text (or ]]>???) // TOOD keepEntityNormalizedForAttributeValue cached as well ... } public int getNamespaceCount() { if (!isElementEvent(eventType)) { throwIllegalState(new int[] { START_ELEMENT, END_ELEMENT }); } return getNamespaceCount(depth); } public int getNamespaceCount(int depth) { if(processNamespaces == false || depth == 0) { return 0; } //int maxDepth = eventType == XMLStreamConstants.END_ELEMENT ? this.depth + 1 : this.depth; //if(depth < 0 || depth > maxDepth) throw new IllegalArgumentException( if(depth < 0) throw new IllegalArgumentException("namespace count may be 0.."+this.depth+" not "+depth); return elNamespaceCount[ depth ]-elNamespaceCount[depth-1]; } public String getNamespacePrefix(int pos) { if (!isElementEvent(eventType)) { throwIllegalState(new int[] { START_ELEMENT, END_ELEMENT }); } int currentDepth = depth; int end = getNamespaceCount(currentDepth);//eventType == XMLStreamConstants.END_ELEMENT ? elNamespaceCount[ depth + 1 ] : namespaceEnd; int newpos = pos + elNamespaceCount[currentDepth-1]; if(pos < end) { return namespacePrefix[ newpos ]; } else { throw new ArrayIndexOutOfBoundsException( "position "+pos+" exceeded number of available namespaces "+end); } } public String getNamespaceURI(int pos) { if (!isElementEvent(eventType)) { throwIllegalState(new int[] { START_ELEMENT, END_ELEMENT }); } int currentDepth = depth; int end = getNamespaceCount(currentDepth); //eventType == XMLStreamConstants.END_ELEMENT ? elNamespaceCount[ depth + 1 ] : namespaceEnd; int newpos = pos + elNamespaceCount[currentDepth-1]; if(pos < end) { return namespaceUri[ newpos ]; } else { throw new ArrayIndexOutOfBoundsException( "position "+pos+" exceedded number of available namespaces "+end); } } public String getNamespaceURI( String prefix ) //throws XMLStreamException { if (!isElementEvent(eventType)) { throwIllegalState(new int[] { START_ELEMENT, END_ELEMENT }); } //int count = namespaceCount[ depth ]; if(prefix != null && prefix.length() > 0) { // non-default namespace for( int i = namespaceEnd -1; i >= 0; i--) { if( prefix.equals( namespacePrefix[ i ] ) ) { return namespaceUri[ i ]; } } if("xml".equals( prefix )) { return XMLConstants.XML_NS_URI; } else if("xmlns".equals( prefix )) { return XMLConstants.XMLNS_ATTRIBUTE_NS_URI; } } else { for( int i = namespaceEnd -1; i >= 0; i--) { if( namespacePrefix[ i ] == null ) { return namespaceUri[ i ]; } } } return null; } public int getDepth() { return depth; } private static int findFragment(int bufMinPos, char[] b, int start, int end) { //System.err.println("bufStart="+bufStart+" b="+printable(new String(b, start, end - start))+" start="+start+" end="+end); if(start < bufMinPos) { start = bufMinPos; if(start > end) start = end; return start; } if(end - start > 65) { start = end - 10; // try to find good location } int i = start + 1; while(--i > bufMinPos) { if((end - i) > 65) break; char c = b[i]; if(c == '<' && (start - i) > 10) break; } return i; } /** * Return string describing current position of parsers as * text 'STATE [seen %s...] @line:column'. */ public String getPositionDescription () { String fragment = null; if(posStart <= pos) { int start = findFragment(0, buf, posStart, pos); //System.err.println("start="+start); if(start < pos) { fragment = new String(buf, start, pos - start); } if(bufAbsoluteStart > 0 || start > 0) fragment = "..." + fragment; } // return " at line "+tokenizerPosRow // +" and column "+(tokenizerPosCol-1) // +(fragment != null ? " seen "+printable(fragment)+"..." : ""); return " "+//TYPES[ eventType ] + (fragment != null ? " seen "+printable(fragment)+"..." : "")+ " @"+getLineNumber()+":"+getColumnNumber(); } public int getLineNumber() { return lineNumber; } public int getColumnNumber() { return columnNumber; } public String getLocationURI() { return null; } public boolean isWhiteSpace() // throws XMLStreamException { if(eventType == XMLStreamConstants.CHARACTERS || eventType == XMLStreamConstants.CDATA) { if(usePC) { for (int i = pcStart; i = attributeCount) throw new IndexOutOfBoundsException( "attribute position must be 0.."+(attributeCount-1)+" and not "+index); return attributeUri[ index ]; } public String getAttributeLocalName(int index) { if(eventType != XMLStreamConstants.START_ELEMENT) { throwIllegalState(START_ELEMENT); } if(index < 0 || index >= attributeCount) throw new IndexOutOfBoundsException( "attribute position must be 0.."+(attributeCount-1)+" and not "+index); return attributeName[ index ]; } public String getAttributePrefix(int index) { if(eventType != XMLStreamConstants.START_ELEMENT) { throwIllegalState(START_ELEMENT); } if(processNamespaces == false) return null; if(index < 0 || index >= attributeCount) throw new IndexOutOfBoundsException( "attribute position must be 0.."+(attributeCount-1)+" and not "+index); return attributePrefix[ index ]; } public String getAttributeType(int index) { if(eventType != XMLStreamConstants.START_ELEMENT) { throwIllegalState(START_ELEMENT); } if(index < 0 || index >= attributeCount) throw new IndexOutOfBoundsException( "attribute position must be 0.."+(attributeCount-1)+" and not "+index); return "CDATA"; } public boolean isAttributeSpecified(int index) { if(eventType != XMLStreamConstants.START_ELEMENT) { throwIllegalState(START_ELEMENT); } if(index < 0 || index >= attributeCount) throw new IndexOutOfBoundsException( "attribute position must be 0.."+(attributeCount-1)+" and not "+index); return true; } public String getAttributeValue(int index) { if(eventType != XMLStreamConstants.START_ELEMENT) { throwIllegalState(START_ELEMENT); } if(index < 0 || index >= attributeCount) throw new IndexOutOfBoundsException( "attribute position must be 0.."+(attributeCount-1)+" and not "+index); return attributeValue[ index ]; } public String getAttributeValue(String namespace, String name) { if(eventType != XMLStreamConstants.START_ELEMENT) { throwIllegalState(START_ELEMENT); } if(name == null) { throw new IllegalArgumentException("attribute name can not be null"); } // TODO make check if namespace is interned!!! etc. for names!!! if(namespace != null) { for(int i = 0; i < attributeCount; ++i) { /* Let's first check local name, then URI; slightly faster * that way (local names more likely to differ than URIs) */ if (name.equals(attributeName[i]) && namespace.equals(attributeUri[i])) { return attributeValue[i]; } } } else { for(int i = 0; i < attributeCount; ++i) { if(name.equals(attributeName[i])) { return attributeValue[i]; } } } return null; } public int getEventType() { return eventType; } public void require(int type, String namespace, String name) throws XMLStreamException { int currType = getEventType(); boolean ok = (type == currType); if (ok && name != null) { if (currType == START_ELEMENT || currType == END_ELEMENT || currType == ENTITY_REFERENCE) { ok = name.equals(getLocalName()); } else { throw new XMLStreamException("Using non-null local name argument for require(); " +ElementTypeNames.getEventTypeString(currType) +" event does not have local name", getLocation()); } } if (ok && namespace != null) { if (currType == START_ELEMENT || currType == START_ELEMENT) { /* 20-Mar-2006, TSa: Unbound namespaces are reported as * null; but caller has to give "" to match against * it (since null means 'do not check'). */ String currNsUri = getNamespaceURI(); if (namespace.length() == 0) { ok = (currNsUri == null); } else { ok = namespace.equals(currNsUri); } } } if (!ok) { throw new XMLStreamException ( "expected event "+ElementTypeNames.getEventTypeString(type) +(name != null ? " with name '"+name+"'" : "") +(namespace != null && name != null ? " and" : "") +(namespace != null ? " with namespace '"+namespace+"'" : "") +" but got" +(type != getEventType() ? " "+ElementTypeNames.getEventTypeString(getEventType()) : "") +(name != null && getLocalName() != null && !name.equals (getName ()) ? " name '"+getLocalName()+"'" : "") +(namespace != null && name != null && getLocalName() != null && !name.equals (getName ()) && getNamespaceURI() != null && !namespace.equals (getNamespaceURI()) ? " and" : "") +(namespace != null && getNamespaceURI() != null && !namespace.equals (getNamespaceURI()) ? " namespace '"+getNamespaceURI()+"'" : "") +(" (position:"+ getPositionDescription())+")", getLocation()); } } public String nextText() throws XMLStreamException { if(getEventType() != XMLStreamConstants.START_ELEMENT) { throw new XMLStreamException( "parser must be on START_ELEMENT to read next text", getLocation()); } int eventType = next(); if(eventType == XMLStreamConstants.CHARACTERS) { String result = getText(); eventType = next(); if(eventType != XMLStreamConstants.END_ELEMENT) { throw new XMLStreamException( "TEXT must be immediately followed by END_ELEMENT and not " +ElementTypeNames.getEventTypeString(getEventType()), getLocation()); } return result; } else if(eventType == XMLStreamConstants.END_ELEMENT) { return ""; } else { throw new XMLStreamException( "parser must be on START_ELEMENT or TEXT to read text", getLocation()); } } public int nextTag() throws XMLStreamException { next(); // Skip white space, comments and processing instructions: while (eventType == XMLStreamConstants.SPACE || eventType == XMLStreamConstants.COMMENT || eventType == XMLStreamConstants.PROCESSING_INSTRUCTION || (eventType == XMLStreamConstants.CHARACTERS && isWhiteSpace()) || (eventType == XMLStreamConstants.CDATA && isWhiteSpace())) { next(); } if (eventType != XMLStreamConstants.START_ELEMENT && eventType != XMLStreamConstants.END_ELEMENT) { throw new XMLStreamException("expected XMLStreamConstants.START_ELEMENT or XMLStreamConstants.END_ELEMENT not " +ElementTypeNames.getEventTypeString(getEventType()), getLocation()); } return eventType; } public String getElementText() throws XMLStreamException { StringBuffer buf = new StringBuffer(); if(getEventType() != START_ELEMENT) throw new XMLStreamException( "Precondition for readText is getEventType() == START_ELEMENT"); do { if(next() == END_DOCUMENT) throw new XMLStreamException("Unexpected end of Document"); if(isStartElement()) throw new XMLStreamException("Unexpected Element start"); if(isCharacters() || getEventType() == XMLStreamConstants.ENTITY_REFERENCE) buf.append(getText()); } while(!isEndElement()); return buf.toString(); } public int next() throws XMLStreamException { tokenize = true; pcEnd = pcStart = 0; usePC = false; return nextImpl(); } public int nextToken() throws XMLStreamException { tokenize = true; return nextImpl(); } public int nextElement() throws XMLStreamException { return nextTag(); } public boolean hasNext() throws XMLStreamException { return !(eventType == XMLStreamConstants.END_DOCUMENT); } public void skip() throws XMLStreamException { nextToken(); } public void close() throws XMLStreamException { } public boolean isStartElement() { return (eventType == XMLStreamConstants.START_ELEMENT); } public boolean isEndElement() { return (eventType == XMLStreamConstants.END_ELEMENT); } public boolean isCharacters() { return (eventType == XMLStreamConstants.CHARACTERS); } public boolean isEOF() { return (eventType == XMLStreamConstants.END_DOCUMENT); } public boolean moveToStartElement() throws XMLStreamException { if (isStartElement()) return true; while(hasNext()) { if (isStartElement()) return true; else next(); } return false; } public boolean moveToStartElement(String localName) throws XMLStreamException { if (localName == null) return false; while( moveToStartElement() ) { if (localName.equals(getLocalName())) return true; if (!hasNext()) return false; next(); } return false; } public boolean moveToStartElement(String localName, String namespaceUri) throws XMLStreamException { if (localName == null || namespaceUri == null) return false; while(moveToStartElement(localName)) { if(namespaceUri.equals(getNamespaceURI())) return true; if (!hasNext()) return false; next(); } return false; } public boolean moveToEndElement() throws XMLStreamException { if (isEndElement()) return true; while (hasNext()) { if (isEndElement()) return true; else next(); } return false; } public boolean moveToEndElement(String localName) throws XMLStreamException { if (localName == null) return false; while( moveToEndElement() ) { if (localName.equals(getLocalName())) return true; if (!hasNext()) return false; next(); } return false; } public boolean moveToEndElement(String localName, String namespaceUri) throws XMLStreamException { if (localName == null || namespaceUri == null) return false; while(moveToEndElement(localName)) { if(namespaceUri.equals(getNamespaceURI())) return true; if (!hasNext()) return false; next(); } return false; } public boolean hasAttributes() { if (getAttributeCount() > 0) return true; return false; } public boolean hasNamespaces() { if(getNamespaceCount() > 0) return true; return false; } public Iterator getAttributes() { if (!hasAttributes()) return EmptyIterator.emptyIterator; int attributeCount = getAttributeCount(); ArrayList atts = new ArrayList(); for (int i = 0; i < attributeCount; i++){ atts.add(new AttributeBase(getAttributePrefix(i), getAttributeNamespace(i), getAttributeLocalName(i), getAttributeValue(i), getAttributeType(i))); } return atts.iterator(); } public Iterator internalGetNamespaces(int depth, int namespaceCount) { ArrayList ns = new ArrayList(); int startNs = elNamespaceCount[ depth - 1 ]; for (int i = 0; i < namespaceCount; i++){ String prefix = getLocalNamespacePrefix(i+startNs); if(prefix == null){ ns.add(new NamespaceBase(getLocalNamespaceURI(i+startNs))); } else { ns.add(new NamespaceBase(prefix, getLocalNamespaceURI(i+startNs))); } } return ns.iterator(); } public Iterator getNamespaces() { if (!hasNamespaces()) return EmptyIterator.emptyIterator; int namespaceCount = getLocalNamespaceCount(); return internalGetNamespaces(depth,namespaceCount); } public Iterator getOutOfScopeNamespaces() { int startNs = elNamespaceCount[ depth-1 ]; int endNs = elNamespaceCount[depth]; int namespaceCount = endNs-startNs; return internalGetNamespaces(depth, namespaceCount); } public XMLStreamReader subReader() throws XMLStreamException { return new SubReader(this); } public void recycle() throws XMLStreamException { reset(); } public Reader getTextStream() { throw new UnsupportedOperationException(); } private final void checkTextEvent() { if (!hasText()) { throw new IllegalStateException("Current state ("+eventTypeDesc(eventType)+") does not have textual content"); } } private final void checkTextEventXxx() { if (eventType != XMLStreamConstants.CHARACTERS && eventType != XMLStreamConstants.CDATA && eventType != XMLStreamConstants.COMMENT && eventType != XMLStreamConstants.SPACE) { throw new IllegalStateException("getTextXxx methods cannot be called for "+eventTypeDesc(eventType)); } } public String getText() { checkTextEvent(); if(eventType == XMLStreamConstants.ENTITY_REFERENCE) { // Do we have the value constructed? if (text == null && entityValue != null) { text = new String(entityValue); } return text; } if(usePC) { text = new String(pc, pcStart, pcEnd - pcStart); } else { text = new String(buf, posStart, posEnd - posStart); } return text; } public int getTextCharacters(int sourceStart, char[] target, int targetStart, int length) throws XMLStreamException { checkTextEventXxx(); int intLen = getTextLength(); /* First: "'sourceStart' argument must be greater or equal to 0 and * less than or equal to the number of characters associated with * the event" */ if (sourceStart < 0 || sourceStart > intLen) { throw new ArrayIndexOutOfBoundsException(); } /* We need not explicitly check for target restrictions: arraycopy * will throw appropriate exceptions (could check them too if that * seems cleaner though?) */ int avail = intLen - sourceStart; if (avail < length) { length = avail; } if (length > 0) { char[] intBuf = getTextCharacters(); int intStart = getTextStart(); System.arraycopy(intBuf, intStart + sourceStart, target, targetStart, length); } return length; } public char[] getTextCharacters() { checkTextEventXxx(); if( eventType == XMLStreamConstants.CHARACTERS ) { if(usePC) { return pc; } else { return buf; } } return buf; } public int getTextStart() { checkTextEventXxx(); if(usePC) { return pcStart; } else { return posStart; } } public int getTextLength() { checkTextEventXxx(); if(usePC) { return pcEnd - pcStart; } else { return posEnd - posStart; } } public boolean hasText() { return (eventType == XMLStreamConstants.CHARACTERS || eventType == XMLStreamConstants.DTD || eventType == XMLStreamConstants.CDATA || eventType == XMLStreamConstants.COMMENT || eventType == XMLStreamConstants.SPACE || eventType == XMLStreamConstants.ENTITY_REFERENCE); } public String getValue() { return getText(); } public String getEncoding() { return getInputEncoding(); } public int getCharacterOffset() { // TODO - cwitt : which buffer are we using? return posEnd; } private static final String checkNull(String s) { if (s != null) return s; else return ""; } private static String eventTypeDesc(int type) { return (type < 0 || type >= TYPES.length) ? "[UNKNOWN]" : TYPES[type]; } private static boolean isElementEvent(int type) { return type == XMLStreamConstants.START_ELEMENT || type == XMLStreamConstants.END_ELEMENT; } public QName getAttributeName(int index) { if(eventType != XMLStreamConstants.START_ELEMENT) { throwIllegalState(START_ELEMENT); } return new QName(checkNull(getAttributeNamespace(index)), getAttributeLocalName(index), checkNull(getAttributePrefix(index))); } public QName getName() { /* getLocalName() would verify event type, but it also allows * ENTITY_REFERENCE, which is not allowed here */ if (!isElementEvent(eventType)) { throw new IllegalStateException("Current state not START_ELEMENT or END_ELEMENT"); } return new QName(checkNull(getNamespaceURI()), getLocalName(), checkNull(getPrefix())); } public boolean hasName() { /* return (0 != (eventType & (XMLStreamConstants.START_ELEMENT | XMLStreamConstants.END_ELEMENT | XMLStreamConstants.ENTITY_REFERENCE))); */ // StAX specs indicate ENTITY_REFERENCE should return false return isElementEvent(eventType); } public String getVersion() { return xmlVersion; } public boolean isStandalone() { return standalone; } public boolean standaloneSet() { return standaloneSet; } public String getCharacterEncodingScheme() { return charEncodingScheme; } // COMMENT - cwitt : end of added XMLStreamReader impl protected int nextImpl() throws XMLStreamException { try { text = null; bufStart = posEnd; if(pastEndTag) { pastEndTag = false; --depth; namespaceEnd = elNamespaceCount[ depth ]; // less namespaces available } if(emptyElementTag) { emptyElementTag = false; pastEndTag = true; return eventType = XMLStreamConstants.END_ELEMENT; } // [1] document ::= prolog element Misc* if(depth > 0) { if(seenStartTag) { seenStartTag = false; return eventType = parseStartTag(); } if(seenEndTag) { seenEndTag = false; return eventType = parseEndTag(); } // ASSUMPTION: we are _on_ first character of content or markup!!!! // [43] content ::= CharData? ((element | Reference | XMLStreamConstants.CDATA | PI | XMLStreamConstants.COMMENT) CharData?)* char ch; if(seenMarkup) { // we have read ahead ... seenMarkup = false; ch = '<'; } else if(seenAmpersand) { seenAmpersand = false; ch = '&'; } else { ch = more(); } posStart = pos - 1; // VERY IMPORTANT: this is correct start of event!!! // when true there is some potential event TEXT to return - keep gathering boolean hadCharData = false; // when true TEXT data is not continous (like ) and requires PC merging boolean needsMerging = false; MAIN_LOOP: while(true) { // work on MARKUP if(ch == '<') { if(hadCharData) { //posEnd = pos - 1; if(tokenize) { seenMarkup = true; return eventType = XMLStreamConstants.CHARACTERS; } } ch = more(); if(ch == '/') { if(!tokenize && hadCharData) { seenEndTag = true; //posEnd = pos - 2; return eventType = XMLStreamConstants.CHARACTERS; } return eventType = parseEndTag(); } else if(ch == '!') { ch = more(); if(ch == '-') { // note: if(tokenize == false) posStart/End is NOT changed!!!! parseComment(); if(tokenize) return eventType = XMLStreamConstants.COMMENT; if( !usePC && hadCharData ) needsMerging = true; } else if(ch == '[') { //posEnd = pos - 3; // must remeber previous posStart/End as it merges with content of CDATA int oldStart = posStart; int oldEnd = posEnd; parseCDATA(); int cdStart = posStart; int cdEnd = posEnd; posStart = oldStart; posEnd = oldEnd; int cdLen = cdEnd - cdStart; if(cdLen > 0) { // was there anything insdie CDATA section? if(hadCharData) { // do merging if there was anything in XMLStreamConstants.CDATA!!!! if(!usePC) { // posEnd is correct already!!! if(posEnd > posStart) { joinPC(); } else { usePC = true; pcStart = pcEnd = 0; } } if(pcEnd + cdLen >= pc.length) ensurePC(pcEnd + cdLen); // copy [cdStart..cdEnd) into PC System.arraycopy(buf, cdStart, pc, pcEnd, cdLen); pcEnd += cdLen; } else { needsMerging = true; posStart = cdStart; posEnd = cdEnd; } hadCharData = true; } else { if( !usePC && hadCharData ) needsMerging = true; } // if(tokenize) return eventType = XMLStreamConstants.CDATA; if(reportCdataEvent) return eventType = XMLStreamConstants.CDATA; } else { throw new XMLStreamException( "unexpected character in markup "+printable(ch), getLocation()); } } else if(ch == '?') { parsePI(); if(tokenize) return eventType = XMLStreamConstants.PROCESSING_INSTRUCTION; if( !usePC && hadCharData ) needsMerging = true; } else if( isNameStartChar(ch) ) { if(!tokenize && hadCharData) { seenStartTag = true; //posEnd = pos - 2; return eventType = XMLStreamConstants.CHARACTERS; } return eventType = parseStartTag(); } else { throw new XMLStreamException( "unexpected character in markup "+printable(ch), getLocation()); } // do content comapctation if it makes sense!!!! } else if(ch == '&') { // work on ENTITY //posEnd = pos - 1; if(tokenize && hadCharData) { seenAmpersand = true; return eventType = XMLStreamConstants.CHARACTERS; } int oldStart = posStart; int oldEnd = posEnd; boolean replace = getConfigurationContext().isReplacingEntities(); char[] resolvedEntity = parseEntityRef(replace); if (!replace) { return (eventType = XMLStreamConstants.ENTITY_REFERENCE); } eventType = XMLStreamConstants.CHARACTERS; // check if replacement text can be resolved !!! if(resolvedEntity == null) { if(entityRefName == null) { entityRefName = newString(buf, posStart, posEnd - posStart); } throw new XMLStreamException( "could not resolve entity named '"+printable(entityRefName)+"'", getLocation()); } //int entStart = posStart; //int entEnd = posEnd; posStart = oldStart; posEnd = oldEnd; if(!usePC) { if(hadCharData) { joinPC(); // posEnd is already set correctly!!! needsMerging = false; } else { usePC = true; pcStart = pcEnd = 0; } } //assert usePC == true; // write into PC replacement text - do merge for replacement text!!!! for (int i = 0; i < resolvedEntity.length; i++) { if(pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = resolvedEntity[ i ]; } // fix for disappearing char if last entiry ref //see http://www.extreme.indiana.edu/bugzilla/show_bug.cgi?id=192 hadCharData = true; //assert needsMerging == false; } else { if(needsMerging) { //assert usePC == false; joinPC(); // posEnd is already set correctly!!! //posStart = pos - 1; needsMerging = false; } //no MARKUP not ENTITIES so work on character data ... // [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*) hadCharData = true; boolean normalizedCR = false; // use loop locality here!!!! do { //if(tokenize == false) { if (true) { // deal with normalization issues ... if(ch == '\r') { normalizedCR = true; posEnd = pos -1; // posEnd is alreadys set if(!usePC) { if(posEnd > posStart) { joinPC(); } else { usePC = true; pcStart = pcEnd = 0; } } //assert usePC == true; if(pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = '\n'; } else if(ch == '\n') { // if(!usePC) { joinPC(); } else { if(pcEnd >= pc.length) ensurePC(); } if(!normalizedCR && usePC) { if(pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = '\n'; } normalizedCR = false; } else { if(usePC) { if(pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = ch; } normalizedCR = false; } } ch = more(); } while(ch != '<' && ch != '&'); posEnd = pos - 1; continue MAIN_LOOP; // skip ch = more() from below - we are alreayd ahead ... } ch = more(); } // endless while(true) } else { if(seenRoot) { return parseEpilog(); } else { return parseProlog(); } } } catch(EOFException eofe) { throw new XMLStreamException(EOF_MSG, getLocation(), eofe); } } protected int parseProlog() throws XMLStreamException { // [2] prolog: ::= XMLDecl? Misc* (doctypedecl Misc*)? and look for [39] element try { char ch; if(seenMarkup) { ch = buf[ pos - 1 ]; } else { ch = more(); } if(eventType == XMLStreamConstants.START_DOCUMENT) { // bootstrap parsing with getting first character input! // deal with BOM // detect BOM and frop it (Unicode int Order Mark) if(ch == '\uFFFE') { throw new XMLStreamException( "first character in input was UNICODE noncharacter (0xFFFE)"+ "- input requires int swapping", getLocation()); } if(ch == CHAR_UTF8_BOM) { // skipping UNICODE int Order Mark (so called BOM) ch = more(); } } seenMarkup = false; boolean gotS = false; posStart = pos - 1; while(true) { // deal with Misc // [27] Misc ::= XMLStreamConstants.COMMENT | PI | S // deal with docdecl --> mark it! // else parseStartTag seen <[^/] if(ch == '<') { if(gotS && tokenize) { posEnd = pos - 1; seenMarkup = true; return eventType = XMLStreamConstants.SPACE; } ch = more(); if(ch == '?') { // check if it is 'xml' // deal with XMLDecl boolean isXMLDecl = parsePI(); if(tokenize) { if (isXMLDecl) return (eventType = XMLStreamConstants.START_DOCUMENT); return (eventType = XMLStreamConstants.PROCESSING_INSTRUCTION); } } else if(ch == '!') { ch = more(); if(ch == 'D') { if(seenDocdecl) { throw new XMLStreamException( "only one docdecl allowed in XML document", getLocation()); } seenDocdecl = true; parseDocdecl(); if(tokenize) return eventType = XMLStreamConstants.DTD; } else if(ch == '-') { parseComment(); if(tokenize) return eventType = XMLStreamConstants.COMMENT; } else { throw new XMLStreamException( "unexpected markup ' /* 28-Oct-2004, TSa: Let's update this right away; otherwise it's * impossible to call public methods that check that current state * is correct. */ eventType = XMLStreamConstants.END_ELEMENT; try { char ch = more(); if(!isNameStartChar(ch)) { throw new XMLStreamException( "expected name start and not "+printable(ch), getLocation()); } posStart = pos - 3; int nameStart = pos - 1 + bufAbsoluteStart; do { ch = more(); } while(isNameChar(ch)); // now we go one level down -- do checks //--depth; //FIXME // check that end tag name is the same as start tag //String name = new String(buf, nameStart - bufAbsoluteStart, // (pos - 1) - (nameStart - bufAbsoluteStart)); int last = pos - 1; int off = nameStart - bufAbsoluteStart; int len = last - off; char[] cbuf = elRawName[depth]; if(elRawNameEnd[depth] != len) { // construct strings for exception String startname = new String(cbuf, 0, elRawNameEnd[depth]); String endname = new String(buf, off, len); throw new XMLStreamException( "end tag name '"+endname+"' must match start tag name '"+startname+"'", getLocation()); } for (int i = 0; i < len; i++) { if(buf[off++] != cbuf[i]) { // construct strings for exception String startname = new String(cbuf, 0, len); String endname = new String(buf, off - i - 1, len); throw new XMLStreamException( "end tag name '"+endname+"' must be the same as start tag '"+startname+"'", getLocation()); } } while(isS(ch)) { ch = more(); } // skip additional white spaces if(ch != '>') throw new XMLStreamException( "expected > to finsh end tag not "+printable(ch), getLocation()); //namespaceEnd = elNamespaceCount[ depth ]; //FIXME posEnd = pos; pastEndTag = true; } catch(EOFException eofe) { throw new XMLStreamException(EOF_MSG, getLocation(), eofe); } return XMLStreamConstants.END_ELEMENT; } public int parseStartTag() throws XMLStreamException { //ASSUMPTION ch is past ' // [44] EmptyElemTag ::= '<' Name (S Attribute)* S? '/>' /* 28-Oct-2004, TSa: Let's update this right away; otherwise it's * impossible to call public methods that check that current state * is correct. */ eventType = XMLStreamConstants.START_ELEMENT; try { ++depth; //FIXME posStart = pos - 2; emptyElementTag = false; attributeCount = 0; localNamespaceEnd = 0; // retrieve name int nameStart = pos - 1 + bufAbsoluteStart; int colonPos = -1; char ch = buf[ pos - 1]; if(ch == ':' && processNamespaces) throw new XMLStreamException( "when namespaces processing enabled colon can not be at element name start", getLocation()); while(true) { ch = more(); if(!isNameChar(ch)) break; if(ch == ':' && processNamespaces) { if(colonPos != -1) throw new XMLStreamException( "only one colon is allowed in name of element when namespaces are enabled", getLocation()); colonPos = pos - 1 + bufAbsoluteStart; } } // retrieve name ensureElementsCapacity(); //TODO check for efficient interning and then use elRawNameInterned!!!! int elLen = (pos - 1) - (nameStart - bufAbsoluteStart); if(elRawName[ depth ] == null || elRawName[ depth ].length < elLen) { elRawName[ depth ] = new char[ 2 * elLen ]; } System.arraycopy(buf, nameStart - bufAbsoluteStart, elRawName[ depth ], 0, elLen); elRawNameEnd[ depth ] = elLen; String name = null; // work on prefixes and namespace URI String prefix = null; if(processNamespaces) { if(colonPos != -1) { prefix = elPrefix[ depth ] = newString(buf, nameStart - bufAbsoluteStart, colonPos - nameStart); name = elName[ depth ] = newString(buf, colonPos + 1 - bufAbsoluteStart, //(pos -1) - (colonPos + 1)); pos - 2 - (colonPos - bufAbsoluteStart)); } else { prefix = elPrefix[ depth ] = null; name = elName[ depth ] = newString(buf, nameStart - bufAbsoluteStart, elLen); } } else { name = elName[ depth ] = newString(buf, nameStart - bufAbsoluteStart, elLen); } while(true) { boolean gotS = isS(ch); if (gotS) { do { ch = more(); } while (isS(ch)); } if(ch == '>') { break; } else if(ch == '/') { emptyElementTag = true; ch = more(); if(ch != '>') throw new XMLStreamException( "expected > to end empty tag not "+printable(ch), getLocation()); break; } else if(isNameStartChar(ch)) { if (!gotS) { if(ch != '>') throw new XMLStreamException("expected a white space between attributes", getLocation()); } ch = parseAttribute(); ch = more(); continue; } else { throw new XMLStreamException( "start tag unexpected character "+printable(ch), getLocation()); } //ch = more(); // skip space } // now when namespaces were declared we can resolve them if(processNamespaces) { String uri = getNamespaceURI(prefix); if(uri == null) { if(prefix == null) { // no prefix and no uri => use default namespace uri = NO_NAMESPACE; } else { throw new XMLStreamException( "could not determine namespace bound to element prefix "+prefix, getLocation()); } } elUri[ depth ] = uri; //String uri = getNamespaceURI(prefix); //if(uri == null && prefix == null) { // no prefix and no uri => use default namespace // uri = ""; //} // resolve attribute namespaces for (int i = 0; i < attributeCount; i++) { String attrPrefix = attributePrefix[ i ]; if(attrPrefix != null) { String attrUri = getNamespaceURI(attrPrefix); if(attrUri == null) { throw new XMLStreamException( "could not determine namespace bound to attribute prefix "+attrPrefix, getLocation()); } attributeUri[ i ] = attrUri; } else { attributeUri[ i ] = NO_NAMESPACE; } } //TODO //[ WFC: Unique Att Spec ] // check namespaced attribute uniqueness contraint!!! for (int i = 1; i < attributeCount; i++) { for (int j = 0; j < i; j++) { if( attributeUri[j] == attributeUri[i] && (allStringsInterned && attributeName[j].equals(attributeName[i]) || (!allStringsInterned && attributeNameHash[ j ] == attributeNameHash[ i ] && attributeName[j].equals(attributeName[i])) ) ) { // prepare data for nice error message? String attr1 = attributeName[j]; if(attributeUri[j] != null) attr1 = attributeUri[j]+":"+attr1; String attr2 = attributeName[i]; if(attributeUri[i] != null) attr2 = attributeUri[i]+":"+attr2; throw new XMLStreamException( "duplicated attributes "+attr1+" and "+attr2, getLocation()); } } } } else { // ! processNamespaces //[ WFC: Unique Att Spec ] // check raw attribute uniqueness contraint!!! for (int i = 1; i < attributeCount; i++) { for (int j = 0; j < i; j++) { if((allStringsInterned && attributeName[j].equals(attributeName[i]) || (!allStringsInterned && attributeNameHash[ j ] == attributeNameHash[ i ] && attributeName[j].equals(attributeName[i])) ) ) { // prepare data for nice error messgae? String attr1 = attributeName[j]; String attr2 = attributeName[i]; throw new XMLStreamException( "duplicated attributes "+attr1+" and "+attr2, getLocation()); } } } } elNamespaceCount[ depth ] = namespaceEnd; posEnd = pos; if (defaultAttributes != null) if (prefix != null) addDefaultAttributes(prefix+":"+name); else addDefaultAttributes(name); } catch (EOFException eofe) { throw new XMLStreamException(EOF_MSG, getLocation(), eofe); } return XMLStreamConstants.START_ELEMENT; } protected void addDefaultAttributes(String elementName) throws XMLStreamException { if (defaultAttributes == null) return; DTDAttlist attList = (DTDAttlist) defaultAttributes.get(elementName); if (elementName == null || attList == null) return; DTDAttribute[] atts = attList.getAttribute(); for (int i=0; i < atts.length; i++) { DTDAttribute att = atts[i]; if (att.getDefaultValue() != null) { boolean found = false; int count = attributeCount; for (int j=0; j < count; j++) { if (attributeName[j].equals(att.getName())) { found = true; break; } } if (!found) { attributeCount++; ensureAttributesCapacity(attributeCount); attributePrefix[attributeCount-1] = null; attributeUri[attributeCount-1] = NO_NAMESPACE; attributeName[attributeCount-1] = att.getName(); attributeValue[attributeCount-1] = att.getDefaultValue(); } } } } protected char parseAttribute() throws XMLStreamException { try { // parse attribute // [41] Attribute ::= Name Eq AttValue // [WFC: No External Entity References] // [WFC: No < in Attribute Values] int prevPosStart = posStart + bufAbsoluteStart; int nameStart = pos - 1 + bufAbsoluteStart; int colonPos = -1; char ch = buf[ pos - 1 ]; if(ch == ':' && processNamespaces) throw new XMLStreamException( "when namespaces processing enabled colon can not be at attribute name start", getLocation()); boolean startsWithXmlns = processNamespaces && ch == 'x'; int xmlnsPos = 0; ch = more(); while(isNameChar(ch)) { if(processNamespaces) { if(startsWithXmlns && xmlnsPos < 5) { ++xmlnsPos; if(xmlnsPos == 1) { if(ch != 'm') startsWithXmlns = false; } else if(xmlnsPos == 2) { if(ch != 'l') startsWithXmlns = false; } else if(xmlnsPos == 3) { if(ch != 'n') startsWithXmlns = false; } else if(xmlnsPos == 4) { if(ch != 's') startsWithXmlns = false; } else if(xmlnsPos == 5) { if(ch != ':') throw new XMLStreamException( "after xmlns in attribute name must be colon" +"when namespaces are enabled", getLocation()); //colonPos = pos - 1 + bufAbsoluteStart; } } if(ch == ':') { if(colonPos != -1) throw new XMLStreamException( "only one colon is allowed in attribute name" +" when namespaces are enabled", getLocation()); colonPos = pos - 1 + bufAbsoluteStart; } } ch = more(); } ensureAttributesCapacity(attributeCount); // --- start processing attributes String name = null; String prefix = null; // work on prefixes and namespace URI if(processNamespaces) { if(xmlnsPos < 4) startsWithXmlns = false; if(startsWithXmlns) { if(colonPos != -1) { //prefix = attributePrefix[ attributeCount ] = null; name = //attributeName[ attributeCount ] = newString(buf, colonPos - bufAbsoluteStart + 1, //pos - 1 - (colonPos + 1 - bufAbsoluteStart) pos - 2 - (colonPos - bufAbsoluteStart) ); /* 07-Mar-2006, TSa: Illegal to try to (re)declare * prefix "xmlns" (even to its correct URI)... * (similar check for "xml" has to wait until we * see the URI -- that can be re-declared to the * same URI) */ if (name.equals("xmlns")) { throw new XMLStreamException("trying to bind reserved NS prefix 'xmlns'", getLocation()); } } } else { if(colonPos != -1) { prefix = attributePrefix[ attributeCount ] = newString(buf, nameStart - bufAbsoluteStart, //colonPos - (nameStart - bufAbsoluteStart)); colonPos - nameStart); name = attributeName[ attributeCount ] = newString(buf, colonPos - bufAbsoluteStart + 1, //pos - 1 - (colonPos + 1 - bufAbsoluteStart)); pos - 2 - (colonPos - bufAbsoluteStart)); //name.substring(0, colonPos-nameStart); } else { prefix = attributePrefix[ attributeCount ] = null; name = attributeName[ attributeCount ] = newString(buf, nameStart - bufAbsoluteStart, pos - 1 - (nameStart - bufAbsoluteStart)); } if(!allStringsInterned) { attributeNameHash[ attributeCount ] = name.hashCode(); } } } else { // retrieve name name = attributeName[ attributeCount ] = newString(buf, nameStart - bufAbsoluteStart, pos - 1 - (nameStart - bufAbsoluteStart)); ////assert name != null; if(!allStringsInterned) { attributeNameHash[ attributeCount ] = name.hashCode(); } } // [25] Eq ::= S? '=' S? while(isS(ch)) { ch = more(); } // skip additional spaces if(ch != '=') throw new XMLStreamException( "expected = after attribute name", getLocation()); ch = more(); while(isS(ch)) { ch = more(); } // skip additional spaces // [10] AttValue ::= '"' ([^<&"] | Reference)* '"' // | "'" ([^<&'] | Reference)* "'" char delimit = ch; if(delimit != '"' && delimit != '\'') throw new XMLStreamException( "attribute value must start with quotation or apostrophe not " +printable(delimit), getLocation()); // parse until delimit or < and resolve Reference //[67] Reference ::= EntityRef | CharRef //int valueStart = pos + bufAbsoluteStart; boolean normalizedCR = false; usePC = false; pcStart = pcEnd; posStart = pos; while(true) { ch = more(); if(ch == delimit) { break; } if(ch == '<') { throw new XMLStreamException( "markup not allowed inside attribute value - illegal < ", getLocation()); } if(ch == '&') { // extractEntityRef posEnd = pos - 1; if(!usePC) { boolean hadCharData = posEnd > posStart; if(hadCharData) { // posEnd is already set correctly!!! joinPC(); } else { usePC = true; pcStart = pcEnd = 0; } } //assert usePC == true; char[] resolvedEntity = parseEntityRef(getConfigurationContext().isReplacingEntities()); // check if replacement text can be resolved !!! if(resolvedEntity == null) { if(entityRefName == null) { entityRefName = newString(buf, posStart, posEnd - posStart); } throw new XMLStreamException( "could not resolve entity named '"+printable(entityRefName)+"'", getLocation()); } // write into PC replacement text - do merge for replacement text!!!! for (int i = 0; i < resolvedEntity.length; i++) { if(pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = resolvedEntity[ i ]; } } else if(ch == '\t' || ch == '\n' || ch == '\r') { // do attribute value normalization // as described in http://www.w3.org/TR/REC-xml#AVNormalize // TODO add test for it form spec ... // handle EOL normalization ... if(!usePC) { posEnd = pos - 1; if(posEnd > posStart) { joinPC(); } else { usePC = true; pcEnd = pcStart = 0; } } //assert usePC == true; if(pcEnd >= pc.length) ensurePC(pcEnd); if(ch != '\n' || !normalizedCR) { pc[pcEnd++] = ' '; //'\n'; } } else { if(usePC) { if(pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = ch; } } normalizedCR = (ch == '\r'); } if(processNamespaces && startsWithXmlns) { String ns = null; if(!usePC) { ns = newStringIntern(buf, posStart, pos - 1 - posStart); } else { ns = newStringIntern(pc, pcStart, pcEnd - pcStart); } ensureNamespacesCapacity(namespaceEnd); int prefixHash = -1; /* 07-Mar-2006, TSa: It is illegal (as per XML Namespaces * specs) to bind anything to 'xmlns' URI; and anything * other than 'xml' to 'xml' URI... */ if (ns.equals(XMLConstants.XML_NS_URI)) { if (!"xml".equals(name)) { throw new XMLStreamException("trying to bind reserved NS URI '"+XMLConstants.XML_NS_URI+"' to prefix other than 'xml'"); } } else if (ns.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) { // Can bind nothing to this URI: throw new XMLStreamException("trying to bind reserved NS URI '"+XMLConstants.XMLNS_ATTRIBUTE_NS_URI+"'"); } if(colonPos != -1) { if(ns.length() == 0) { throw new XMLStreamException( "non-default namespace can not be declared to be empty string (in xml 1.0)", getLocation()); } /* 07-Mar-2006, TSa: Can only declare 'xml' to bind to * its standard URI -- otherwise that's an error. */ if (name.equals("xml")) { if (!ns.equals(XMLConstants.XML_NS_URI)) { throw new XMLStreamException("trying to bind reserved NS prefix 'xml' to URI other than its standard value ("+XMLConstants.XML_NS_URI+")", getLocation()); } } // declare new namespace namespacePrefix[ namespaceEnd ] = name; if(!allStringsInterned) { prefixHash = namespacePrefixHash[ namespaceEnd ] = name.hashCode(); } } else { // declare new default namespace ... namespacePrefix[ namespaceEnd ] = null; if (ns.length() == 0) { // need to use null ns = NO_NAMESPACE; } if(!allStringsInterned) { prefixHash = namespacePrefixHash[ namespaceEnd ] = -1; } } namespaceUri[ namespaceEnd ] = ns; // detect duplicate namespace declarations!!! int startNs = elNamespaceCount[ depth - 1 ]; for (int i = namespaceEnd - 1; i >= startNs; --i) { if(((allStringsInterned || name == null) && namespacePrefix[ i ] == name) || (!allStringsInterned && name != null && namespacePrefixHash[ i ] == prefixHash && name.equals(namespacePrefix[ i ]) )) { String s = name == null ? "default" : "'"+name+"'"; throw new XMLStreamException( "duplicated namespace declaration for "+s+" prefix", getLocation()); } } // ++localNamespaceEnd; ++namespaceEnd; } else { if(!usePC) { attributeValue[ attributeCount ] = new String(buf, posStart, pos - 1 - posStart); } else { attributeValue[ attributeCount ] = new String(pc, pcStart, pcEnd - pcStart); } ++attributeCount; } posStart = prevPosStart - bufAbsoluteStart; return ch; } catch (EOFException eofe) { throw new XMLStreamException(EOF_MSG, getLocation(), eofe); } } /** * This buffer is used for expanding single character (non-surrogate) * character entity expansions. */ protected char[] charRefOneCharBuf = new char[1]; /** * This buffer is used in cases where an entity expands to a surrogate * pair. Since this is a rare occurence, it's lazily created if needed. */ protected char[] charRefTwoCharBuf = null; /** * @return Character array that contains value the reference expands * to. */ protected char[] parseEntityRef(boolean replace) throws XMLStreamException { try { // ASSUMPTION just after & entityRefName = null; posStart = pos; char ch = more(); // Character entity? if(ch == '#') { // parse character reference int charRef = 0; ch = more(); if(ch == 'x') { //encoded in hex do { ch = more(); if (ch == ';') { break; } charRef = (charRef << 4); // 16x if(ch >= '0' && ch <= '9') { charRef += (ch - '0'); } else if(ch >= 'a' && ch <= 'f') { charRef += (ch - ('a' - 10)); } else if(ch >= 'A' && ch <= 'F') { charRef += (ch - ('A' - 10)); } else { throw new XMLStreamException( "character reference (with hex value) may not contain " +printable(ch), getLocation()); } } while (charRef <= MAX_UNICODE_CHAR); } else { // encoded in decimal do { if(ch >= '0' && ch <= '9') { charRef = (charRef * 10) + (ch - '0'); } else if (ch == ';') { break; } else { throw new XMLStreamException( "character reference (with decimal value) may not contain " +printable(ch), getLocation()); } ch = more(); } while (charRef <= MAX_UNICODE_CHAR); } posEnd = pos - 1; /* 07-Mar-2006, TSa: Character entities still have to expand * to valid XML characters... */ checkCharValidity(charRef, false); if (charRef > 0xFFFF) { // surrogate pair if (charRefTwoCharBuf == null) { charRefTwoCharBuf = new char[2]; } charRef -= 0x10000; charRefTwoCharBuf[0] = (char) ((charRef >> 10) + 0xD800); charRefTwoCharBuf[1] = (char) ((charRef & 0x3FF) + 0xDC00); return (entityValue = charRefTwoCharBuf); } // normal char: charRefOneCharBuf[0] = (char) charRef; return (entityValue = charRefOneCharBuf); } // Not a character entity, general entity: // scan until ; do{ ch = more(); } while(ch != ';'); posEnd = pos - 1; // determine what name maps to int len = posEnd - posStart; if(len == 2) { if (buf[posStart] == 'l' && buf[posStart+1] == 't') { if(!replace) text = "<"; charRefOneCharBuf[0] = '<'; return (entityValue = charRefOneCharBuf); //if(paramPC || isParserTokenizing) { // if(pcEnd >= pc.length) ensurePC(); // pc[pcEnd++] = '<'; //} } if (buf[posStart] == 'g' && buf[posStart+1] == 't') { if(!replace) text = ">"; charRefOneCharBuf[0] = '>'; return (entityValue = charRefOneCharBuf); } } else if(len == 3) { if (buf[posStart] == 'a' && buf[posStart+1] == 'm' && buf[posStart+2] == 'p') { if(!replace) text = "&"; charRefOneCharBuf[0] = '&'; return (entityValue = charRefOneCharBuf); } } else if(len == 4) { if (buf[posStart] == 'a' && buf[posStart+1] == 'p' && buf[posStart+2] == 'o' && buf[posStart+3] == 's') { if(!replace) text = "'"; charRefOneCharBuf[0] = '\''; return (entityValue = charRefOneCharBuf); } if (buf[posStart] == 'q' && buf[posStart+1] == 'u' && buf[posStart+2] == 'o' && buf[posStart+3] == 't') { if(!replace) text = "\""; charRefOneCharBuf[0] = '"'; return (entityValue = charRefOneCharBuf); } } // No, should be a general entity: return (entityValue = lookupEntityReplacement(len)); } catch (EOFException eofe) { throw new XMLStreamException(EOF_MSG, getLocation(), eofe); } } /** * @return Character array that contains (unparsed) entity expansion * value; or null if no such entity has been declared */ protected char[] lookupEntityReplacement(int entitNameLen) throws XMLStreamException { if(!allStringsInterned) { int hash = fastHash(buf, posStart, posEnd - posStart); LOOP: for (int i = entityEnd - 1; i >= 0; --i) { if(hash == entityNameHash[ i ] && entitNameLen == entityNameBuf[ i ].length) { char[] entityBuf = entityNameBuf[ i ]; for (int j = 0; j < entitNameLen; j++) { if(buf[posStart + j] != entityBuf[j]) continue LOOP; } if(tokenize) { text = entityReplacement[ i ]; } entityRefName = entityName[i]; return entityReplacementBuf[ i ]; } } } else { entityRefName = newString(buf, posStart, posEnd - posStart); for (int i = entityEnd - 1; i >= 0; --i) { // take advantage that interning for newString is enforced if(entityRefName == entityName[ i ]) { if(tokenize) { text = entityReplacement[ i ]; } return entityReplacementBuf[ i ]; } } } return null; } protected void parseComment() throws XMLStreamException { // implements XML 1.0 Section 2.5 XMLStreamConstants.COMMENTs //ASSUMPTION: seen if(ch == '-') { if(expDash < at) { // first dash expDash = at+1; } else { // second dash ch = more(); if(ch != '>') { throw new XMLStreamException("in COMMENT after two dashes (--) next character must be '>' not "+printable(ch), getLocation()); } break; } } else if(ch == '\r') { columnNumber = 1; // more() fails to set this skipLfAt = at+1; // to skip trailing \n, if any // Need to replace current char with \n: if (!anySkipped) { // no gaps yet? buf[pos-1] = '\n'; continue; } // If gaps, let's just follow through: ch = '\n'; } else if(ch == '\n') { // part of \r\n? if (skipLfAt == at) { // yes, let's skip if (!anySkipped) { anySkipped = true; posEnd = pos-1; // to replace this \n next time } continue; } } /* Ok, need to add at the end of buffer, if we have * replaced any \r\n combos with \n... or */ if (anySkipped) { buf[posEnd] = ch; ++posEnd; } } if (anySkipped) { // need to trim one '-' --posEnd; } else { // the whole '-->' is in input buffer posEnd = pos-3; } } catch(EOFException ex) { // detect EOF and create meaningful error ... throw new XMLStreamException( "COMMENT started on line "+curLine+" and column "+curColumn+" was not closed", getLocation(), ex); } } catch (EOFException eofe) { throw new XMLStreamException(EOF_MSG, getLocation(), eofe); } } public String getPITarget() { if (eventType != XMLStreamConstants.PROCESSING_INSTRUCTION) { throwIllegalState(PROCESSING_INSTRUCTION); } return piTarget; } public String getPIData() { if (eventType != XMLStreamConstants.PROCESSING_INSTRUCTION) { throwIllegalState(PROCESSING_INSTRUCTION); } return piData; } public NamespaceContext getNamespaceContext() { return new ReadOnlyNamespaceContextBase(namespacePrefix, namespaceUri, namespaceEnd); } /** * @return True if this was the xml declaration; false if a regular * processing instruction */ protected boolean parsePI() throws XMLStreamException { // implements XML 1.0 Section 2.6 Processing Instructions // [16] PI ::= '' Char*)))? '?>' int curLine = lineNumber; int curColumn = columnNumber; try { //ASSUMPTION: seen '... break; } else if (isNameChar(ch)) { ; // good } else if (isS(ch)) { break; } else { throw new XMLStreamException("unexpected character "+printable(ch)+" after processing instruction name; expected a white space or '?>'", getLocation()); } } int len = pos-posStart-1; // Let's first verify there was a target: if (len == 0) { // missing target throw new XMLStreamException("processing instruction must have PITarget name", getLocation()); } // [17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l')) piTarget=new String(buf, posStart, len); /* And then let's skip (unnecessary) white space, if we hit white * space. */ if (ch != '?') { ch = skipS(ch); } boolean isXMLDecl = piTarget.equalsIgnoreCase("xml"); // Do we now have the xml declaration? if(isXMLDecl) { /* 10-Mar-2006, TSa: This is not really sufficient I think. * We really should check xml declaration earlier, and * never have double check here. But, usually this should * work, too... */ if((posStart+bufAbsoluteStart) > 2) { //') { if (at == expLT) { break; } } else if(ch == '\r') { columnNumber = 1; // more() fails to set this skipLfAt = at+1; // to skip trailing \n, if any // Need to replace current char with \n: if (!anySkipped) { // no gaps yet? buf[pos-1] = '\n'; continue; } // If gaps, let's just follow through: ch = '\n'; } else if(ch == '\n') { // part of \r\n? if (skipLfAt == at) { // yes, let's skip if (!anySkipped) { anySkipped = true; posEnd = pos-1; // to replace this \n next time } continue; } } /* Ok, need to add at the end of buffer, if we have * replaced any \r\n combos with \n... or */ if (anySkipped) { buf[posEnd] = ch; ++posEnd; } } if (anySkipped) { // need to trim one '?' --posEnd; } else { // "?>" is in input buffer posEnd = pos-2; } } piData = new String(buf, posStart, (posEnd-posStart)); return isXMLDecl; } catch(EOFException ex) { // detect EOF and create meaningful error ... throw new XMLStreamException("processing instruction started on line "+curLine+" and column "+curColumn +" was not closed", getLocation(), ex); } } protected final static char[] VERSION = {'v','e','r','s','i','o','n'}; protected final static char[] ENCODING = {'e','n','c','o','d','i','n','g'}; protected final static char[] STANDALONE = {'s','t','a','n','d','a','l','o','n','e'}; protected final static char[] YES = {'y','e','s'}; protected final static char[] NO = {'n','o'}; protected char requireInput(char ch, char[] input) throws XMLStreamException { for (int i = 0; i < input.length; i++) { if(ch != input[i]) { throw new XMLStreamException( "expected "+printable(input[i])+" in "+new String(input) +" and not "+printable(ch), getLocation()); } try { ch = more(); } catch (EOFException eofe) { throw new XMLStreamException(EOF_MSG, getLocation(), eofe); } } return ch; } protected char requireNextS() throws XMLStreamException { char ch; try { ch = more(); } catch (EOFException eofe) { throw new XMLStreamException(EOF_MSG, getLocation(), eofe); } if(!isS(ch)) { throw new XMLStreamException( "white space is required and not "+printable(ch), getLocation()); } return skipS(ch); } protected char skipS(char ch) throws XMLStreamException { try { while(isS(ch)) { ch = more(); } // skip additional spaces return ch; } catch (EOFException eofe) { throw new XMLStreamException(EOF_MSG, getLocation(), eofe); } } protected void parseXmlDecl(char ch) throws XMLStreamException { // [23] XMLDecl ::= '' // --- parse VersionInfo // [24] VersionInfo ::= S 'version' Eq ("'" VersionNum "'" | '"' VersionNum '"') // parse is positioned just on first S past 'z') && (ch < 'A' || ch > 'Z') && (ch < '0' || ch > '9') && ch != '_' && ch != '.' && ch != ':' && ch != '-') { throw new XMLStreamException( " 'z') && (ch < 'A' || ch > 'Z')) { throw new XMLStreamException( " 'z') && (ch < 'A' || ch > 'Z') && (ch < '0' || ch > '9') && ch != '.' && ch != '_' && ch != '-') { throw new XMLStreamException( " as last part of ') { throw new XMLStreamException( "expected ?> as last part of ' /* 07-Nov-2004, TSa: Should be fairly easy to verify (obligatory) * root element, and optional public/system ids too. */ // (but only in validating mode, since that's a VC, not WFC) // First obligatory white space: char ch = requireNextS(); // Then obligatory root element name (copied from parseEndTag()) if(!isNameStartChar(ch)) { throwNotNameStart(ch); } int nameStart = pos - 1 + bufAbsoluteStart; do { ch = more(); } while(isNameChar(ch)); // Ok, root element name gotten. Any white space to skip? ch = skipS(ch); if (ch == 'S' || ch == 'P') { // SYSTEM/PUBLIC identifier if (ch == 'S') { if (more() != 'Y' || more() != 'S' || more() != 'T' || more() != 'E' || more() != 'M') { throw new XMLStreamException("expected keyword SYSTEM", getLocation()); } } else { if(more() != 'U' || more() != 'B' || more() != 'L' || more() != 'I' || more() != 'C') { throw new XMLStreamException("expected keyword PUBLIC", getLocation()); } // Need to skip the public id char quotChar = requireNextS(); if (quotChar != '"' && quotChar != '\'') { throw new XMLStreamException("Public identifier has to be enclosed in quotes, not "+printable(ch), getLocation()); } while ((ch = more()) != quotChar) { // should probably check if it's valid... } } char quotChar = requireNextS(); if (quotChar != '"' && quotChar != '\'') { throw new XMLStreamException("System identifier has to be enclosed in quotes, not "+printable(ch), getLocation()); } while ((ch = more()) != quotChar) { // should probably check if it's valid... } // Ok, great, names skipped, can try to locate the int. subset ch = skipS(more()); } if (ch == '[') { posStart = pos; int bracketLevel = 1; loop: /* Ok, let's try to find the boundary of the internal * subset. It's not 100% reliable, since we don't really * parse... but should be good enough for now */ while(true) { ch = more(); switch (ch) { case '[': ++bracketLevel; break; case ']': // should we check for underflow? --bracketLevel; break; case '>': if (bracketLevel <= 0) { break loop; } break; case '\'': // entity expansion value, attr. default or such? case '"': while (more() != ch) { // let's just loop over it... } break; } } posEnd = pos-2; // to exclude closing bracket processDTD(); } else { // No internal subset, empty contents posStart = posEnd = pos; ch = skipS(ch); if (ch != '>') { throw new XMLStreamException("Expected closing '>' after internal DTD subset, not '" +printable(ch)+"'", getLocation()); } } } catch (EOFException eofe) { throw new XMLStreamException(EOF_MSG, getLocation(), eofe); } } protected void processDTD() throws XMLStreamException { try { String internalDTD = new String(buf, posStart, posEnd - posStart); DTDParser dtdParser = new DTDParser(new java.io.StringReader(internalDTD)); mDtdIntSubset = dtdParser.parse(); // Get general entities Vector v = mDtdIntSubset.getItemsByType(DTDEntity.class); Enumeration e = v.elements(); while(e.hasMoreElements()) { DTDEntity entity = (DTDEntity) e.nextElement(); if (!entity.isParsed()) { defineEntityReplacementText(entity.getName(), entity.getValue()); } } // Get default attributes v = mDtdIntSubset.getItemsByType(DTDAttlist.class); e = v.elements(); while(e.hasMoreElements()) { DTDAttlist list = (DTDAttlist) e.nextElement(); DTDAttribute[] atts = list.getAttribute(); for (int i=0; i < atts.length; i++) { DTDAttribute att = atts[i]; if (att.getDefaultValue() != null) { if (defaultAttributes == null) defaultAttributes = new HashMap(); defaultAttributes.put(list.getName(), list); } } } } catch (IOException ioe) { //System.out.println(ioe); //ioe.printStackTrace(); throw new XMLStreamException(ioe); } } protected void parseCDATA() throws XMLStreamException { // implements XML 1.0 Section 2.7 CDATA Sections // [18] XMLStreamConstants.CDATA ::= CDStart CData CDEnd // [19] CDStart ::= '' Char*)) // [21] CDEnd ::= ']]>' //ASSUMPTION: seen ++at; ch = more(); if(ch == ']') { ++bracketCount; } else { if(ch == '>') { if (bracketCount >= 2) { break; // found end sequence!!!! } bracketCount = 0; } else { bracketCount = 0; if (ch == '\r') { columnNumber = 1; // more() fails to set this skipLfAt = at+1; // to skip trailing \n, if any // Need to replace current char with \n: if (!anySkipped) { // no gaps yet? buf[pos-1] = '\n'; continue; } // If gaps, let's just fall through: ch = '\n'; } else if(ch == '\n') { // part of \r\n? if (skipLfAt == at) { // yes, let's skip anySkipped = true; posEnd = pos-1; // to replace this \n next time continue; } } } } /* Ok, need to add at the end of buffer, if we have * replaced any \r\n combos with \n... or */ if (anySkipped) { buf[posEnd] = ch; ++posEnd; } } if (anySkipped) { // have extra ']]' in there posEnd -= 2; } else { // the whole ']]>' is in input buffer posEnd = pos-3; } } catch(EOFException ex) { // detect EOF and create meaningful error ... throw new XMLStreamException( "CDATA section on line "+curLine+" and column "+curColumn+" was not closed", getLocation(), ex); } } protected void fillBuf() throws XMLStreamException, EOFException { if(reader == null) throw new XMLStreamException( "reader must be set before parsing is started"); // see if we are in compaction area if(bufEnd > bufSoftLimit) { // expand buffer it makes sense!!!! boolean compact = bufStart > bufSoftLimit; boolean expand = false; if(!compact) { //freeSpace if(bufStart < buf.length / 2) { // less then half buffer available for compacting --> expand instead!!! expand = true; } else { // at least half of buffer can be reclaimed --> worthwhile effort!!! compact = true; } } // if buffer almost full then compact it if(compact) { //TODO: look on trashing // //assert bufStart > 0 System.arraycopy(buf, bufStart, buf, 0, bufEnd - bufStart); if(TRACE_SIZING) System.out.println("fillBuf() compacting "+bufStart); } else if(expand) { int newSize = 2 * buf.length; char newBuf[] = new char[ newSize ]; if(TRACE_SIZING) System.out.println("fillBuf() "+buf.length+" => "+newSize); System.arraycopy(buf, bufStart, newBuf, 0, bufEnd - bufStart); buf = newBuf; if(bufLoadFactor > 0) { bufSoftLimit = ( bufLoadFactor * buf.length ) /100; } } else { throw new XMLStreamException("internal error in fillBuffer()"); } bufEnd -= bufStart; pos -= bufStart; posStart -= bufStart; posEnd -= bufStart; bufAbsoluteStart += bufStart; bufStart = 0; } // at least one character must be read or error int room = (buf.length - bufEnd); int len = (room > READ_CHUNK_SIZE) ? READ_CHUNK_SIZE : room; int ret; try { ret = reader.read(buf, bufEnd, len); } catch (IOException ioe) { throw new XMLStreamException(ioe); } if(ret > 0) { bufEnd += ret; return; } if(ret == -1) { throw new EOFException("no more data available"); } else { throw new XMLStreamException("error reading input, returned "+ret); } } protected char more() throws XMLStreamException, EOFException { if(pos >= bufEnd) fillBuf(); char ch = buf[pos++]; //line/columnNumber /* 10-Mar-2006, TSa: Won't work reliably with combinations of * \r and \n... should be improved. */ if(ch == '\n') { ++lineNumber; columnNumber = 1; } else { ++columnNumber; } return ch; } //protected char printable(char ch) { return ch; } protected String printable(char ch) { if(ch == '\n') { return "\\n"; } else if(ch == '\r') { return "\\r"; } else if(ch == '\t') { return "\\t"; } else if(ch == '\'') { return "\\'"; } if(ch > 127 || ch < 32) { return "\\u"+Integer.toHexString((int)ch); } return ""+ch; } protected String printable(String s) { if(s == null) return null; StringBuffer buf = new StringBuffer(); for(int i = 0; i < s.length(); ++i) { buf.append(printable(s.charAt(i))); } s = buf.toString(); return s; } protected void ensurePC(int end) { //assert end >= pc.length; int newSize = end > READ_CHUNK_SIZE ? 2 * end : 2 * READ_CHUNK_SIZE; char[] newPC = new char[ newSize ]; if(TRACE_SIZING) System.out.println("ensurePC() "+pc.length+" ==> "+newSize+" end="+end); System.arraycopy(pc, 0, newPC, 0, pcEnd); pc = newPC; //assert end < pc.length; } protected void joinPC() { //assert usePC == false; //assert posEnd > posStart; int len = posEnd - posStart; int newEnd = pcEnd + len + 1; if(newEnd >= pc.length) ensurePC(newEnd); // add 1 for extra space for one char //assert newEnd < pc.length; System.arraycopy(buf, posStart, pc, pcEnd, len); pcEnd += len; usePC = true; } public Location getLocation() { return this; } public String getPublicId() { return null; } public String getSystemId() { return null; } private ConfigurationContextBase configurationContext; public void setConfigurationContext(ConfigurationContextBase c) { configurationContext = c; boolean isCoalescing = Boolean.TRUE.equals(c.getProperty(XMLInputFactory.IS_COALESCING)); reportCdataEvent = Boolean.TRUE.equals(c.getProperty(ConfigurationContextBase.REPORT_CDATA)); } public ConfigurationContextBase getConfigurationContext() { return configurationContext; } public Object getProperty(String name) { if (name.equals(FEATURE_STAX_ENTITIES)) { if (mDtdIntSubset != null) { Vector v = mDtdIntSubset.getItemsByType(DTDEntity.class); Enumeration e = v.elements(); ArrayList result = new ArrayList(v.size()); while(e.hasMoreElements()) { DTDEntity ent = (DTDEntity) e.nextElement(); Object nd = DTDEvent.createEntityDeclaration(ent); if (nd != null) { result.add(nd); } } return result; } return null; } if (name.equals(FEATURE_STAX_NOTATIONS)) { if (mDtdIntSubset != null) { Vector v = mDtdIntSubset.getItemsByType(DTDNotation.class); Enumeration e = v.elements(); ArrayList result = new ArrayList(v.size()); while(e.hasMoreElements()) { DTDNotation n = (DTDNotation) e.nextElement(); Object ed = DTDEvent.createNotationDeclaration(n); if (ed != null) { result.add(ed); } } return result; } return null; } return configurationContext.getProperty(name); } private String throwIllegalState(int expState) throws IllegalStateException { throw new IllegalStateException("Current state ("+eventTypeDesc(eventType)+") not "+eventTypeDesc(expState)); } private String throwIllegalState(int[] expStates) throws IllegalStateException { StringBuffer sb = new StringBuffer(); sb.append(eventTypeDesc(expStates[0])); int last = expStates.length-1; for (int i = 0; i < last; ++i) { sb.append(", "); sb.append(eventTypeDesc(expStates[i])); } sb.append(" or "); sb.append(eventTypeDesc(expStates[last])); throw new IllegalStateException("Current state ("+eventTypeDesc(eventType)+") not "+sb.toString()); } private void throwNotNameStart(char ch) throws XMLStreamException { throw new XMLStreamException("expected name start character and not "+printable(ch), getLocation()); } } /* * Indiana University Extreme! Lab Software License, Version 1.1.1 * * * Copyright (c) 2002 Extreme! Lab, Indiana University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the Indiana * University Extreme! Lab (http://www.extreme.indiana.edu/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Indiana University" and "Indiana University * Extreme! Lab" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact http://www.extreme.indiana.edu/. * * 5. Products derived from this software may not use "Indiana * University" name nor may "Indiana University" appear in their name, * without prior written permission of the Indiana University. * * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ stax-1.2.0.orig/src/com/bea/xml/stream/XMLEventReaderBase.java0000644000175000017500000001547310444554664024026 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream; import com.bea.xml.stream.util.CircularQueue; import com.bea.xml.stream.util.ElementTypeNames; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.events.Characters; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLEventReader; import javax.xml.stream.util.XMLEventAllocator; import javax.xml.stream.util.XMLEventConsumer; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLInputFactory; /** *

The base reader class.

*/ public class XMLEventReaderBase implements XMLEventReader, XMLEventConsumer { private CircularQueue elementQ = new CircularQueue(); private boolean open = true; protected XMLStreamReader reader; protected XMLEventAllocator allocator; private boolean reachedEOF=false; private ConfigurationContextBase configurationContext; public XMLEventReaderBase(XMLStreamReader reader) throws XMLStreamException { this(reader, new XMLEventAllocatorBase()); } public XMLEventReaderBase(XMLStreamReader reader, XMLEventAllocator alloc) throws XMLStreamException { if (reader==null) throw new IllegalArgumentException("XMLStreamReader may not be null"); if (alloc==null) throw new IllegalArgumentException("XMLEventAllocator may not be null"); this.reader = reader; open = true; // create the allocator this.allocator = alloc; // System.out.println("Allocator->"+allocator); // This check fills the information from the XMLDeclaration // into the startdocument event if (reader.getEventType()==XMLEvent.START_DOCUMENT) { XMLEvent e = allocator.allocate(reader); reader.next(); add(e); } } public void setAllocator(XMLEventAllocator allocator) { if (allocator == null) throw new IllegalArgumentException("XMLEvent Allocator may not be null"); this.allocator = allocator; } public String getElementText() throws XMLStreamException { StringBuffer buf = new StringBuffer(); XMLEvent e = nextEvent(); if (!e.isStartElement()) throw new XMLStreamException("Precondition for readText is nextEvent().getTypeEventType() == START_ELEMENT (got "+e.getEventType()+")"); while(hasNext()) { e = peek(); if(e.isStartElement()) throw new XMLStreamException("Unexpected Element start"); if(e.isCharacters()) buf.append(((Characters) e).getData()); if(e.isEndElement()) return buf.toString(); nextEvent(); } throw new XMLStreamException("Unexpected end of Document"); } public XMLEvent nextTag() throws XMLStreamException { while(hasNext()) { XMLEvent e = nextEvent(); if (e.isCharacters() && !((Characters) e).isWhiteSpace()) throw new XMLStreamException("Unexpected text"); if (e.isStartElement() || e.isEndElement()) return e; } throw new XMLStreamException("Unexpected end of Document"); } public Object next() { try { return nextEvent(); } catch (XMLStreamException e) { return null; } } public XMLEvent nextEvent() throws XMLStreamException { // FIXME cfry throw error if parseSome fails if (needsMore()) { if (!parseSome()) throw new java.util.NoSuchElementException("Attempt to call nextEvent() on a stream with no more elements"); } return get(); } public boolean hasNext() { if (!open) return false; if (!elementQ.isEmpty()) return true; try { if (reader.hasNext()) return true; } catch (XMLStreamException e) { return false; } open = false; return false; } public XMLEvent peek() throws XMLStreamException { if (!elementQ.isEmpty()) return (XMLEvent) elementQ.peek(); if (parseSome()) return (XMLEvent) elementQ.peek(); // Stax specs indicate null should be returned, if no more stuff: return null; } public void add(XMLEvent event) throws XMLStreamException { elementQ.add(event); } protected boolean needsMore() { return elementQ.isEmpty(); } protected XMLEvent get() throws XMLStreamException { return (XMLEvent) elementQ.remove(); } protected boolean isOpen() { return !reachedEOF; } protected void internal_close() { reachedEOF = true; } public void close() throws XMLStreamException { internal_close(); } protected boolean parseSome() throws XMLStreamException { /* 26-Sep-2005, TSa: Should check if we have hit EOF, and if so, * fail to get any more stuff... */ if (reachedEOF) { return false; } // System.out.println("Allocator->"+allocator); allocator.allocate(reader,this); if (reader.hasNext()) reader.next(); if (reader.getEventType() == XMLEvent.END_DOCUMENT) { allocator.allocate(reader,this); reachedEOF = true; } return !needsMore(); } public void setConfigurationContext(ConfigurationContextBase base) { configurationContext = base; } public Object getProperty(String name) { return configurationContext.getProperty(name); } public void remove() { throw new java.lang.UnsupportedOperationException(); } public static void main(String args[]) throws Exception { System.setProperty("javax.xml.stream.XMLInputFactory", "com.bea.xml.stream.MXParserFactory"); System.setProperty("javax.xml.stream.XMLEventFactory", "com.bea.xml.stream.EventFactory"); XMLInputFactory factory = XMLInputFactory.newInstance(); XMLEventReader xmlr = factory.createXMLEventReader(new java.io.FileReader(args[0])); while(xmlr.hasNext()) { XMLEvent e = xmlr.nextEvent(); System.out.println("["+ ElementTypeNames.getEventTypeString(e.getEventType()) +"]["+ e+"]"); } } // public ConfigurationContext getConfigurationContext() { // return new ConfigurationContextBase(); // } } stax-1.2.0.orig/src/com/bea/xml/stream/util/0000755000175000017500000000000010444554664020546 5ustar twernertwernerstax-1.2.0.orig/src/com/bea/xml/stream/util/EmptyIterator.java0000644000175000017500000000171510444554664024225 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream.util; public class EmptyIterator implements java.util.Iterator { public static final EmptyIterator emptyIterator = new EmptyIterator(); public boolean hasNext() { return false; } public Object next() { return null; } public void remove() { throw new UnsupportedOperationException(); } } stax-1.2.0.orig/src/com/bea/xml/stream/util/SymbolTable.java0000644000175000017500000001017510444554664023632 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream.util; import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.Map; import java.util.Iterator; /** * Maintains a table for namespace scope * * * values = map from strings to stacks * [a]->[value1,0],[value2,0] * * table = a stack of bindings */ public class SymbolTable { private int depth; private Stack table; private Map values; public SymbolTable() { depth = 0; table = new Stack(); values = new HashMap(); } public void clear() { depth = 0; table.clear(); values.clear(); } // // Gets the current depth // public int getDepth() { return depth; } public boolean withinElement() { return depth > 0; } // // Adds a name/value pair // public void put (String name, String value) { table.push(new Symbol(name,value,depth)); if (!values.containsKey(name)) { Stack valueStack = new Stack(); valueStack.push(value); values.put(name,valueStack); } else { Stack valueStack = (Stack) values.get(name); valueStack.push(value); } } // // Gets the value for a variable // public String get (String name) { Stack valueStack = (Stack) values.get(name); if (valueStack==null || valueStack.isEmpty()) return null; return (String) valueStack.peek(); } public Set getAll(String name) { HashSet result = new HashSet(); Iterator i = table.iterator(); while (i.hasNext()) { Symbol s = (Symbol) i.next(); if (name.equals(s.getName())) result.add(s.getValue()); } return result; } // // add a new highest level scope to the table // public void openScope() { depth++; } // // remove the highest level scope from the table // public void closeScope() { // Get the top binding Symbol symbol = (Symbol) table.peek(); int symbolDepth = symbol.depth; // check if it needs to be popped of the table while (symbolDepth == depth && !table.isEmpty()) { symbol = (Symbol) table.pop(); // pop its value as well Stack valueStack = (Stack) values.get(symbol.name); valueStack.pop(); // check the next binding if (!table.isEmpty()) { symbol = (Symbol) table.peek(); symbolDepth = symbol.depth; } else break; } depth--; } public String toString() { Iterator i = table.iterator(); String retVal=""; while(i.hasNext()) { Symbol symbol = (Symbol) i.next(); retVal = retVal + symbol + "\n"; } return retVal; } public static void main(String args[]) throws Exception { SymbolTable st = new SymbolTable(); st.openScope(); st.put("x","foo"); st.put("y","bar"); System.out.println("1 x:"+st.get("x")); System.out.println("1 y:"+st.get("y")); st.openScope(); st.put("x","bar"); st.put("y","foo"); st.openScope(); st.put("x","barbie"); st.openScope(); st.closeScope(); System.out.println("3 x:"+st.get("x")); st.closeScope(); System.out.println("2 x:"+st.get("x")); System.out.println("2 y:"+st.get("y")); System.out.print(st); st.closeScope(); System.out.println("1 x:"+st.get("x")); System.out.println("1 y:"+st.get("y")); st.closeScope(); System.out.print(st); } } stax-1.2.0.orig/src/com/bea/xml/stream/util/ElementTypeNames.java0000644000175000017500000000504310444554664024632 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream.util; import javax.xml.stream.events.XMLEvent; public class ElementTypeNames { public final static String getEventTypeString(int eventType) { switch (eventType){ case XMLEvent.START_ELEMENT: return "START_ELEMENT"; case XMLEvent.END_ELEMENT: return "END_ELEMENT"; case XMLEvent.PROCESSING_INSTRUCTION: return "PROCESSING_INSTRUCTION"; case XMLEvent.CHARACTERS: return "CHARACTERS"; case XMLEvent.SPACE: return "SPACE"; case XMLEvent.COMMENT: return "COMMENT"; case XMLEvent.START_DOCUMENT: return "START_DOCUMENT"; case XMLEvent.END_DOCUMENT: return "END_DOCUMENT"; case XMLEvent.ENTITY_REFERENCE: return "ENTITY_REFERENCE"; case XMLEvent.ATTRIBUTE: return "ATTRIBUTE"; case XMLEvent.DTD: return "DTD"; case XMLEvent.CDATA: return "CDATA"; case XMLEvent.NAMESPACE: return "NAMESPACE"; } return "UNKNOWN_EVENT_TYPE"; } public static int getEventType(String val) { if (val.equals ("START_ELEMENT")) return XMLEvent.START_ELEMENT; if (val.equals ("SPACE")) return XMLEvent.SPACE; if (val.equals ("END_ELEMENT")) return XMLEvent.END_ELEMENT; if (val.equals ("PROCESSING_INSTRUCTION")) return XMLEvent.PROCESSING_INSTRUCTION; if (val.equals ("CHARACTERS")) return XMLEvent.CHARACTERS; if (val.equals ("COMMENT")) return XMLEvent.COMMENT; if (val.equals ("START_DOCUMENT")) return XMLEvent.START_DOCUMENT; if (val.equals ("END_DOCUMENT")) return XMLEvent.END_DOCUMENT; if (val.equals("ATTRIBUTE")) return XMLEvent.ATTRIBUTE; if (val.equals("DTD")) return XMLEvent.DTD; if (val.equals("CDATA")) return XMLEvent.CDATA; if (val.equals("NAMESPACE")) return XMLEvent.NAMESPACE; return -1; } } stax-1.2.0.orig/src/com/bea/xml/stream/util/CircularQueue.java0000644000175000017500000001273510444554664024172 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream.util; import java.util.AbstractCollection; import java.util.Arrays; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.NoSuchElementException; public final class CircularQueue extends AbstractCollection { // This is the largest capacity allowed by this implementation private static final int MAX_CAPACITY = 1 << 30; private static final int DEFAULT_CAPACITY = 1 << 8; private int size = 0; private int producerIndex = 0; private int consumerIndex = 0; // capacity must be a power of 2 at all times private int capacity; private int maxCapacity; // we mask with capacity -1. This variable caches that values private int bitmask; private Object[] q; public CircularQueue() { this(DEFAULT_CAPACITY); } // Construct a queue which has at least the specified capacity. If // the value specified is a power of two then the queue will be // exactly the specified size. Otherwise the queue will be the // first power of two which is greater than the specified value. public CircularQueue(int c) { this(c, MAX_CAPACITY); } public CircularQueue(int c, int mc) { if (c > mc) { throw new IllegalArgumentException("Capacity greater than maximum"); } if (mc > MAX_CAPACITY) { throw new IllegalArgumentException("Maximum capacity greater than " + "allowed"); } for (capacity = 1; capacity < c; capacity <<= 1) ; for (maxCapacity = 1; maxCapacity < mc; maxCapacity <<= 1) ; bitmask = capacity - 1; q = new Object[capacity]; } // Constructor used by clone() private CircularQueue(CircularQueue oldQueue) { size = oldQueue.size; producerIndex = oldQueue.producerIndex; consumerIndex = oldQueue.consumerIndex; capacity = oldQueue.capacity; maxCapacity = oldQueue.maxCapacity; bitmask = oldQueue.bitmask; q = new Object[oldQueue.q.length]; System.arraycopy(oldQueue.q, 0, q, 0, q.length); } private boolean expandQueue() { // double the size of the queue // This design assumes that this is a rare case if (capacity == maxCapacity) { return false; } int old_capacity = capacity; Object[] old_q = q; capacity += capacity; bitmask = capacity - 1; q = new Object[capacity]; System.arraycopy(old_q, consumerIndex, q, 0, old_capacity - consumerIndex); if (consumerIndex != 0) { System.arraycopy(old_q, 0, q, old_capacity - consumerIndex, consumerIndex); } consumerIndex = 0; producerIndex = size; return true; } public boolean add(Object obj) { if (size == capacity) { // no room if (!expandQueue()) return false; } size++; q[producerIndex] = obj; producerIndex = (producerIndex + 1) & bitmask; return true; } public Object remove() { Object obj; if (size == 0) return null; size--; obj = q[consumerIndex]; q[consumerIndex] = null; // allow gc to collect consumerIndex = (consumerIndex + 1) & bitmask; return obj; } public boolean isEmpty() { return size == 0; } public int size() { return size; } public int capacity() { return capacity; } public Object peek() { if (size == 0) return null; return q[consumerIndex]; } public void clear() { Arrays.fill(q, null); size = 0; producerIndex = 0; consumerIndex = 0; } public Object clone() { return new CircularQueue(this); } public String toString() { StringBuffer s = new StringBuffer(super.toString() + " - capacity: '" + capacity() + "' size: '" + size() + "'"); if (size > 0) { s.append(" elements:"); for (int i = 0; i < size; ++i) { s.append('\n'); s.append('\t'); s.append(q[consumerIndex + i & bitmask].toString()); } } return s.toString(); } public Iterator iterator() { return new Iterator() { private final int ci = consumerIndex; private final int pi = producerIndex; private int s = size; private int i = ci; public boolean hasNext() { checkForModification(); return s > 0; } public Object next() { checkForModification(); if (s == 0) throw new NoSuchElementException(); s--; Object r = q[i]; i = (i + 1) & bitmask; return r; } public void remove() { throw new UnsupportedOperationException(); } private void checkForModification() { if (ci != consumerIndex) throw new ConcurrentModificationException(); if (pi != producerIndex) throw new ConcurrentModificationException(); } }; } } stax-1.2.0.orig/src/com/bea/xml/stream/util/Symbol.java0000644000175000017500000000211010444554664022650 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream.util; class Symbol { String name; String value; int depth; Symbol(String name, String value, int depth) { this.name = name; this.value = value; this.depth = depth; } public String getName() { return name; } public String getValue() { return value; } public int getDepth() { return depth; } public String toString() { return ("["+depth+"]["+name+"]["+value+"]"); } } stax-1.2.0.orig/src/com/bea/xml/stream/util/Stack.java0000644000175000017500000000520310444554664022456 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream.util; import java.util.AbstractCollection; import java.util.EmptyStackException; import java.util.Iterator; public final class Stack extends AbstractCollection { private Object[] values; private int pointer; public Stack() { this(15); } public Stack(int size) { if (size < 0) throw new IllegalArgumentException(); values = new Object[size]; pointer = 0; } private Stack(Object[] values, int pointer) { this.values = values; this.pointer = pointer; } private void resize() { if (pointer == 0) { values = new Object[1]; return; } Object[] o = new Object[pointer * 2]; System.arraycopy(values, 0, o, 0, pointer); values = o; } public boolean add(Object o) { push(o); return true; } public void clear() { Object[] v = values; while (pointer > 0 ) { v[--pointer] = null; } } public boolean isEmpty() { return pointer == 0; } public Iterator iterator() { Object[] o = new Object[pointer]; System.arraycopy(values, 0, o, 0, pointer); return new ArrayIterator(o); } public Object clone() { Object[] newValues = new Object[pointer]; System.arraycopy(values, 0, newValues, 0, pointer); return new Stack(newValues, pointer); } public int size() { return pointer; } public void push(Object o) { if (pointer == values.length) resize(); values[pointer++] = o; } public Object pop() { try { Object o = values[--pointer]; values[pointer] = null; return o; } catch (ArrayIndexOutOfBoundsException aioobe) { // Make sure the stack continues to be useable even if we popped // too many. if (pointer < 0) pointer = 0; throw new EmptyStackException(); } } public Object peek() { try { return values[pointer - 1]; } catch (ArrayIndexOutOfBoundsException aioobe) { throw new EmptyStackException(); } } } stax-1.2.0.orig/src/com/bea/xml/stream/util/NamespaceContextImpl.java0000644000175000017500000000637710444554664025511 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream.util; import javax.xml.namespace.NamespaceContext; import java.util.ArrayList; import java.util.Iterator; import java.util.Set; import java.util.Iterator; public class NamespaceContextImpl implements NamespaceContext { SymbolTable prefixTable = new SymbolTable(); SymbolTable uriTable = new SymbolTable(); NamespaceContext rootContext; public NamespaceContextImpl() { init(); } public NamespaceContextImpl(NamespaceContext rootContext) { this.rootContext = null; init(); } public void init() { bindNamespace("xml","http://www.w3.org/XML/1998/namespace"); bindNamespace("xmlns","http://www.w3.org/XML/1998/namespace"); } public void openScope() { prefixTable.openScope(); uriTable.openScope(); } public void closeScope() { prefixTable.closeScope(); uriTable.closeScope(); } public void bindNamespace(String prefix, String uri) { prefixTable.put(prefix,uri); uriTable.put(uri,prefix); } public int getDepth() { return prefixTable.getDepth(); } public String getNamespaceURI(String prefix) { String value = prefixTable.get(prefix); if (value == null && rootContext != null) return rootContext.getNamespaceURI(prefix); else return value; } public String getPrefix(String uri) { String value = uriTable.get(uri); if (value == null && rootContext != null) return rootContext.getPrefix(uri); else return value; } public void bindDefaultNameSpace(String uri) { bindNamespace("",uri); } public void unbindDefaultNameSpace() { bindNamespace("",null); } public void unbindNamespace(String prefix, String uri) { prefixTable.put(prefix,null); prefixTable.put(uri,null); } public String getDefaultNameSpace() { return getNamespaceURI(""); } public Iterator getPrefixes(String uri) { return (uriTable.getAll(uri)).iterator(); } public static void main(String args[]) throws Exception { NamespaceContextImpl nci = new NamespaceContextImpl(); nci.openScope(); nci.bindNamespace("a","uri"); nci.bindNamespace("b","uri"); System.out.println("a="+nci.getNamespaceURI("a")); System.out.println("uri="+nci.getPrefix("uri")); Iterator vals = nci.getPrefixes("uri"); while(vals.hasNext()) System.out.println("1 uri->"+vals.next()); nci.openScope(); nci.bindNamespace("a","uri2"); vals = nci.getPrefixes("uri"); while(vals.hasNext()) System.out.println("2 uri->"+vals.next()); nci.closeScope(); nci.closeScope(); } } stax-1.2.0.orig/src/com/bea/xml/stream/util/ArrayIterator.java0000644000175000017500000000277610444554664024215 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream.util; import java.util.Iterator; import java.util.NoSuchElementException; public final class ArrayIterator implements Iterator { private final Object[] array; private final int maxIndex; private int index; public ArrayIterator(Object[] a) { this(a, 0, a.length); } public ArrayIterator(Object[] a, int off, int len) { if (off < 0) throw new IllegalArgumentException(); if (off > a.length) throw new IllegalArgumentException(); if (len > a.length - off) throw new IllegalArgumentException(); array = a; index = off; maxIndex = len + off; } public boolean hasNext() { return index < maxIndex; } public Object next() { if (index >= maxIndex) throw new NoSuchElementException(); return array[index++]; } public void remove() { throw new UnsupportedOperationException(); } } stax-1.2.0.orig/src/com/bea/xml/stream/EventState.java0000644000175000017500000000430410444554664022517 0ustar twernertwernerpackage com.bea.xml.stream; import javax.xml.namespace.QName; import com.bea.xml.stream.util.ElementTypeNames; import java.util.List; import java.util.Iterator; import java.util.ArrayList; public class EventState { private int type; private QName qname; private List attributes; private List namespaces; private String data; private String extraData; public EventState(){} public EventState(int type) { this.type = type; attributes = new ArrayList(); namespaces = new ArrayList(); } public void clear() { qname = null; attributes = new ArrayList(); namespaces = new ArrayList(); data = null; extraData = null; } public void setType(int type) { this.type = type; } public int getType() { return type; } public QName getName() { return qname; } public String getLocalName() { return qname.getLocalPart();} public String getPrefix() { return qname.getPrefix(); } public String getNamespaceURI() { return qname.getNamespaceURI(); } public void setName(QName n) { qname = n; } public void setAttributes(List atts) { attributes = atts; } public void addAttribute(Object obj) { attributes.add(obj); } public void addNamespace(Object obj) { namespaces.add(obj); } public List getAttributes() { return attributes; } public void setNamespaces(List ns) { namespaces = ns; } public List getNamespaces() { return namespaces; } public String getData() { return data; } public void setData(String data) { this.data = data; } public String getExtraData() { return extraData; } public void setExtraData(String d) { this.extraData = d; } public String toString() { StringBuffer b = new StringBuffer(); b.append("["+ElementTypeNames.getEventTypeString(type)+ "]"); if (qname != null) b.append("[name='"+qname+"']"); Iterator i = namespaces.iterator(); while(i.hasNext()) b.append(i.next()+" "); i = attributes.iterator(); while(i.hasNext()) b.append(i.next()+" "); if (data != null) b.append(",data=["+data+"]"); if (extraData != null) b.append(",extradata=["+extraData+"]"); return b.toString(); } } stax-1.2.0.orig/src/com/bea/xml/stream/XMLEventPlayer.java0000644000175000017500000000267610444554664023266 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.events.XMLEvent; /** *

Create events from a file format.

*/ public class XMLEventPlayer extends XMLEventReaderBase { private XMLStreamPlayer player; public XMLEventPlayer(XMLStreamPlayer reader) throws XMLStreamException { super(reader); player = reader; } protected boolean parseSome() throws XMLStreamException { allocator.allocate(reader,this); if (reader.hasNext()) reader.next(); if (isOpen() && reader.getEventType() == XMLEvent.END_DOCUMENT) { if (player.endDocumentIsPresent()) allocator.allocate(reader,this); internal_close(); } return !needsMore(); } } stax-1.2.0.orig/src/com/bea/xml/stream/filters/0000755000175000017500000000000010444554664021241 5ustar twernertwernerstax-1.2.0.orig/src/com/bea/xml/stream/filters/NameFilter.java0000644000175000017500000000331410444554664024133 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream.filters; import javax.xml.namespace.QName; import javax.xml.stream.EventFilter; import javax.xml.stream.StreamFilter; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.XMLEvent; public class NameFilter implements EventFilter, StreamFilter { private QName name; public NameFilter(QName name) { this.name = name; } public boolean accept(XMLEvent e) { if (!e.isStartElement() && !e.isEndElement()) return false; QName eName = null; if (e.isStartElement()) eName = ((StartElement)e).getName(); else eName = ((EndElement)e).getName(); if (name.equals(eName)) return true; return false; } public boolean accept(XMLStreamReader r) { if (!r.isStartElement() && !r.isEndElement()) return false; QName eName = new QName(r.getNamespaceURI(), r.getLocalName()); if (name.equals(eName)) return true; return false; } } stax-1.2.0.orig/src/com/bea/xml/stream/filters/TypeFilter.java0000644000175000017500000000230410444554664024172 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream.filters; import javax.xml.stream.EventFilter; import javax.xml.stream.StreamFilter; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.XMLStreamReader; public class TypeFilter implements EventFilter, StreamFilter { protected boolean[] types= new boolean[20]; public TypeFilter (){} public void addType(int type) { types[type]=true; } public boolean accept(XMLEvent e) { return types[e.getEventType()]; } public boolean accept(XMLStreamReader r) { return types[r.getEventType()]; } } stax-1.2.0.orig/src/com/bea/xml/stream/EventFactory.java0000644000175000017500000002110210444554664023041 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream; import java.util.Iterator; import javax.xml.namespace.QName; import javax.xml.namespace.NamespaceContext; import javax.xml.stream.Location; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.ProcessingInstruction; import javax.xml.stream.events.Comment; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.Namespace; import javax.xml.stream.events.Characters; import javax.xml.stream.events.StartDocument; import javax.xml.stream.events.EndDocument; import javax.xml.stream.events.Namespace; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.EntityReference; import javax.xml.stream.events.EntityDeclaration; import javax.xml.stream.events.DTD; import com.bea.xml.stream.events.StartElementEvent; import com.bea.xml.stream.events.EndElementEvent; import com.bea.xml.stream.events.CharactersEvent; import com.bea.xml.stream.events.StartDocumentEvent; import com.bea.xml.stream.events.EndDocumentEvent; import com.bea.xml.stream.events.ProcessingInstructionEvent; import com.bea.xml.stream.events.CommentEvent; import com.bea.xml.stream.events.EntityReferenceEvent; import com.bea.xml.stream.events.DTDEvent; /** *

The default factory for creating events. */ public class EventFactory extends XMLEventFactory { private Location location; public void setLocation(Location l) { location = l; } public Attribute createAttribute(QName name, String value){ return new AttributeBase(name,value); } public Attribute createAttribute(String localName, String value){ return new AttributeBase("",localName,value); } public Attribute createAttribute(String prefix, String namespaceURI, String localName, String value) { return new AttributeBase(prefix,namespaceURI,localName,value,"CDATA"); } public Namespace createNamespace(String namespaceURI){ return new NamespaceBase(namespaceURI); } public Namespace createNamespace(String prefix, String namespaceUri){ if (prefix == null) throw new NullPointerException("The prefix of a namespace may "+ "not be set to null"); return new NamespaceBase(prefix,namespaceUri); } public StartElement createStartElement(QName name, Iterator attributes, Iterator namespaces){ StartElementEvent e= new StartElementEvent(name); while(attributes != null && attributes.hasNext()) e.addAttribute((Attribute) attributes.next()); while(namespaces != null && namespaces.hasNext()) e.addNamespace((Namespace) namespaces.next()); return e; } public StartElement createStartElement(String prefix, String namespaceUri, String localName){ return new StartElementEvent(new QName(namespaceUri,localName,prefix)); } public static String checkPrefix(String prefix) { if (prefix == null) return ""; return prefix; } public StartElement createStartElement(String prefix, String namespaceUri, String localName, Iterator attributes, Iterator namespaces){ prefix=checkPrefix(prefix); StartElementEvent e= new StartElementEvent(new QName(namespaceUri,localName,prefix)); while(attributes != null && attributes.hasNext()) e.addAttribute((Attribute) attributes.next()); while(namespaces != null && namespaces.hasNext()) e.addNamespace((Namespace) namespaces.next()); return e; } public StartElement createStartElement(String prefix, String namespaceUri, String localName, Iterator attributes, Iterator namespaces, NamespaceContext context){ prefix=checkPrefix(prefix); StartElementEvent e= new StartElementEvent(new QName(namespaceUri,localName,prefix)); while(attributes != null && attributes.hasNext()) e.addAttribute((Attribute)attributes.next()); while(namespaces != null && namespaces.hasNext()) e.addNamespace((Namespace)namespaces.next()); e.setNamespaceContext(context); return e; } public EndElement createEndElement(QName name, Iterator namespaces){ EndElementEvent e = new EndElementEvent(name); while(namespaces != null && namespaces.hasNext()) e.addNamespace((Namespace) namespaces.next()); return e; } public EndElement createEndElement(String prefix, String namespaceUri, String localName){ prefix=checkPrefix(prefix); return new EndElementEvent(new QName(namespaceUri,localName,prefix)); } public EndElement createEndElement(String prefix, String namespaceUri, String localName, Iterator namespaces){ prefix=checkPrefix(prefix); EndElementEvent e = new EndElementEvent(new QName(namespaceUri,localName,prefix)); while(namespaces.hasNext()) e.addNamespace((Namespace) namespaces.next()); return e; } public Characters createCharacters(String content){ return new CharactersEvent(content); } public Characters createCData(String content) { return new CharactersEvent(content,true); } public StartDocument createStartDocument(){ return new StartDocumentEvent(); } public StartDocument createStartDocument(String encoding, String version, boolean standalone){ StartDocumentEvent e = new StartDocumentEvent(); e.setEncoding(encoding); e.setVersion(version); e.setStandalone(standalone); return e; } public StartDocument createStartDocument(String encoding, String version){ StartDocumentEvent e = new StartDocumentEvent(); e.setEncoding(encoding); e.setVersion(version); return e; } public StartDocument createStartDocument(String encoding){ StartDocumentEvent e = new StartDocumentEvent(); e.setEncoding(encoding); return e; } public EndDocument createEndDocument(){ return new EndDocumentEvent(); } /********** public AttributeIterator createAttributeIterator(Iterator iterator){ return new AttributeIteratorImpl(iterator); } public NamespaceIterator createNamespaceIterator(Iterator iterator){ return new NamespaceIteratorImpl(iterator); } **********/ public EntityReference createEntityReference(String name, EntityDeclaration declaration) { return new EntityReferenceEvent(name,declaration); } public Characters createSpace(String content) { CharactersEvent c = new CharactersEvent(content); c.setSpace(true); return c; } public Characters createIgnorableSpace(String content) { CharactersEvent c = new CharactersEvent(content); c.setSpace(true); c.setIgnorable(true); return c; } public Comment createComment(String text) { return new CommentEvent(text); } public ProcessingInstruction createProcessingInstruction(String target, String data) { return new ProcessingInstructionEvent(target,data); } public DTD createDTD(String dtd) { return new DTDEvent(dtd); } } stax-1.2.0.orig/src/com/bea/xml/stream/reader/0000755000175000017500000000000010444554664021033 5ustar twernertwernerstax-1.2.0.orig/src/com/bea/xml/stream/reader/XmlChars.java0000644000175000017500000003343110444554664023423 0ustar twernertwerner/* * $Id: XmlChars.java,v 1.1 2004/08/19 05:30:22 aslom Exp $ * * The Apache Software License, Version 1.1 * * * Copyright (c) 2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Crimson" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * 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) 1999, Sun Microsystems, Inc., * http://www.sun.com. For more information on the Apache Software * Foundation, please see . */ package com.bea.xml.stream.reader; /** * Methods in this class are used to determine whether characters may * appear in certain roles in XML documents. Such methods are used * both to parse and to create such documents. * * @version 1.8 * @author David Brownell */ public class XmlChars { // can't construct instances private XmlChars () { } /** * Returns true if the argument, a UCS-4 character code, is valid in * XML documents. Unicode characters fit into the low sixteen * bits of a UCS-4 character, and pairs of Unicode surrogate * characters can be combined to encode UCS-4 characters in * documents containing only Unicode. (The char datatype * in the Java Programming Language represents Unicode characters, * including unpaired surrogates.) * *

In XML, UCS-4 characters can also be encoded by the use of * character references such as &#x12345678;, which * happens to refer to a character that is disallowed in XML documents. * UCS-4 characters allowed in XML documents can be expressed with * one or two Unicode characters. * * @param ucs4char The 32-bit UCS-4 character being tested. */ static public boolean isChar (int ucs4char) { // [2] Char ::= #x0009 | #x000A | #x000D // | [#x0020-#xD7FF] // ... surrogates excluded! // | [#xE000-#xFFFD] // | [#x10000-#x10ffff] return ((ucs4char >= 0x0020 && ucs4char <= 0xD7FF) || ucs4char == 0x000A || ucs4char == 0x0009 || ucs4char == 0x000D || (ucs4char >= 0xE000 && ucs4char <= 0xFFFD) || (ucs4char >= 0x10000 && ucs4char <= 0x10ffff)); } /** * Returns true if the character is allowed to be a non-initial * character in names according to the XML recommendation. * @see #isNCNameChar * @see #isLetter */ public static boolean isNameChar (char c) { // [4] NameChar ::= Letter | Digit | '.' | '_' | ':' // | CombiningChar | Extender if (isLetter2 (c)) return true; else if (c == '>') return false; else if (c == '.' || c == '-' || c == '_' || c == ':' || isExtender (c)) return true; else return false; } /** * Returns true if the character is allowed to be a non-initial * character in unscoped names according to the rules of the XML * Namespaces proposed recommendation. Except for precluding * the colon (used to separate names from their scopes) these * characters are just as allowed by the XML recommendation. * @see #isNameChar * @see #isLetter */ public static boolean isNCNameChar (char c) { // [NC 5] NCNameChar ::= Letter | Digit | '.' | '_' // | CombiningChar | Extender return c != ':' && isNameChar (c); } /** * Returns true if the character is allowed where XML supports * whitespace characters, false otherwise. */ public static boolean isSpace (char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r'; } /* * NOTE: java.lang.Character.getType() values are: * * UNASSIGNED = 0, * * UPPERCASE_LETTER = 1, // Lu * LOWERCASE_LETTER = 2, // Ll * TITLECASE_LETTER = 3, // Lt * MODIFIER_LETTER = 4, // Lm * OTHER_LETTER = 5, // Lo * NON_SPACING_MARK = 6, // Mn * ENCLOSING_MARK = 7, // Me * COMBINING_SPACING_MARK = 8, // Mc * DECIMAL_DIGIT_NUMBER = 9, // Nd * LETTER_NUMBER = 10, // Nl * OTHER_NUMBER = 11, // No * SPACE_SEPARATOR = 12, // Zs * LINE_SEPARATOR = 13, // Zl * PARAGRAPH_SEPARATOR = 14, // Zp * CONTROL = 15, // Cc * FORMAT = 16, // Cf * // 17 reserved for proposed Ci category * PRIVATE_USE = 18, // Co * SURROGATE = 19, // Cs * DASH_PUNCTUATION = 20, // Pd * START_PUNCTUATION = 21, // Ps * END_PUNCTUATION = 22, // Pe * CONNECTOR_PUNCTUATION = 23, // Pc * OTHER_PUNCTUATION = 24, // Po * MATH_SYMBOL = 25, // Sm * CURRENCY_SYMBOL = 26, // Sc * MODIFIER_SYMBOL = 27, // Sk * OTHER_SYMBOL = 28; // So */ /** * Returns true if the character is an XML "letter". XML Names must * start with Letters or a few other characters, but other characters * in names must only satisfy the isNameChar predicate. * * @see #isNameChar * @see #isNCNameChar */ public static boolean isLetter (char c) { // [84] Letter ::= BaseChar | Ideographic // [85] BaseChar ::= ... too much to repeat // [86] Ideographic ::= ... too much to repeat // // Optimize the typical case. // if (c >= 'a' && c <= 'z') return true; if (c == '/') return false; if (c >= 'A' && c <= 'Z') return true; // // Since the tables are too ridiculous to use in code, // we're using the footnotes here to drive this test. // switch (Character.getType (c)) { // app. B footnote says these are 'name start' // chars' ... case Character.LOWERCASE_LETTER: // Ll case Character.UPPERCASE_LETTER: // Lu case Character.OTHER_LETTER: // Lo case Character.TITLECASE_LETTER: // Lt case Character.LETTER_NUMBER: // Nl // OK, here we just have some exceptions to check... return !isCompatibilityChar (c) // per "5.14 of Unicode", rule out some combiners && !(c >= 0x20dd && c <= 0x20e0); default: // check for some exceptions: these are "alphabetic" return ((c >= 0x02bb && c <= 0x02c1) || c == 0x0559 || c == 0x06e5 || c == 0x06e6); } } // // XML 1.0 discourages "compatibility" characters in names; these // were defined to permit passing through some information stored in // older non-Unicode character sets. These always have alternative // representations in Unicode, e.g. using combining chars. // private static boolean isCompatibilityChar (char c) { // the numerous comparisions here seem unavoidable, // but the switch can reduce the number which must // actually be executed. switch ((c >> 8) & 0x0ff) { case 0x00: // ISO Latin/1 has a few compatibility characters return c == 0x00aa || c == 0x00b5 || c == 0x00ba; case 0x01: // as do Latin Extended A and (parts of) B return (c >= 0x0132 && c <= 0x0133) || (c >= 0x013f && c <= 0x0140) || c == 0x0149 || c == 0x017f || (c >= 0x01c4 && c <= 0x01cc) || (c >= 0x01f1 && c <= 0x01f3) ; case 0x02: // some spacing modifiers return (c >= 0x02b0 && c <= 0x02b8) || (c >= 0x02e0 && c <= 0x02e4); case 0x03: return c == 0x037a; // Greek case 0x05: return c == 0x0587; // Armenian case 0x0e: return c >= 0x0edc && c <= 0x0edd; // Laotian case 0x11: // big chunks of Hangul Jamo are all "compatibility" return c == 0x1101 || c == 0x1104 || c == 0x1108 || c == 0x110a || c == 0x110d || (c >= 0x1113 && c <= 0x113b) || c == 0x113d || c == 0x113f || (c >= 0x1141 && c <= 0x114b) || c == 0x114d || c == 0x114f || (c >= 0x1151 && c <= 0x1153) || (c >= 0x1156 && c <= 0x1158) || c == 0x1162 || c == 0x1164 || c == 0x1166 || c == 0x1168 || (c >= 0x116a && c <= 0x116c) || (c >= 0x116f && c <= 0x1171) || c == 0x1174 || (c >= 0x1176 && c <= 0x119d) || (c >= 0x119f && c <= 0x11a2) || (c >= 0x11a9 && c <= 0x11aa) || (c >= 0x11ac && c <= 0x11ad) || (c >= 0x11b0 && c <= 0x11b6) || c == 0x11b9 || c == 0x11bb || (c >= 0x11c3 && c <= 0x11ea) || (c >= 0x11ec && c <= 0x11ef) || (c >= 0x11f1 && c <= 0x11f8) ; case 0x20: return c == 0x207f; // superscript case 0x21: return // various letterlike symbols c == 0x2102 || c == 0x2107 || (c >= 0x210a && c <= 0x2113) || c == 0x2115 || (c >= 0x2118 && c <= 0x211d) || c == 0x2124 || c == 0x2128 || (c >= 0x212c && c <= 0x212d) || (c >= 0x212f && c <= 0x2138) // most Roman numerals (less 1K, 5K, 10K) || (c >= 0x2160 && c <= 0x217f) ; case 0x30: // some Hiragana return c >= 0x309b && c <= 0x309c; case 0x31: // all Hangul Compatibility Jamo return c >= 0x3131 && c <= 0x318e; case 0xf9: case 0xfa: case 0xfb: case 0xfc: case 0xfd: case 0xfe: case 0xff: // the whole "compatibility" area is for that purpose! return true; default: // most of Unicode isn't flagged as being for compatibility return false; } } // guts of isNameChar/isNCNameChar private static boolean isLetter2 (char c) { // [84] Letter ::= BaseChar | Ideographic // [85] BaseChar ::= ... too much to repeat // [86] Ideographic ::= ... too much to repeat // [87] CombiningChar ::= ... too much to repeat // // Optimize the typical case. // if (c >= 'a' && c <= 'z') return true; if (c == '>') return false; if (c >= 'A' && c <= 'Z') return true; // // Since the tables are too ridiculous to use in code, // we're using the footnotes here to drive this test. // switch (Character.getType (c)) { // app. B footnote says these are 'name start' // chars' ... case Character.LOWERCASE_LETTER: // Ll case Character.UPPERCASE_LETTER: // Lu case Character.OTHER_LETTER: // Lo case Character.TITLECASE_LETTER: // Lt case Character.LETTER_NUMBER: // Nl // ... and these are name characters 'other // than name start characters' case Character.COMBINING_SPACING_MARK: // Mc case Character.ENCLOSING_MARK: // Me case Character.NON_SPACING_MARK: // Mn case Character.MODIFIER_LETTER: // Lm case Character.DECIMAL_DIGIT_NUMBER: // Nd // OK, here we just have some exceptions to check... return !isCompatibilityChar (c) // per "5.14 of Unicode", rule out some combiners && !(c >= 0x20dd && c <= 0x20e0); default: // added a character ... return c == 0x0387; } } private static boolean isDigit (char c) { // [88] Digit ::= ... // // java.lang.Character.isDigit is correct from the XML point // of view except that it allows "fullwidth" digits. // return Character.isDigit (c) && ! ( (c >= 0xff10) && (c <= 0xff19)); } private static boolean isExtender (char c) { // [89] Extender ::= ... return c == 0x00b7 || c == 0x02d0 || c == 0x02d1 || c == 0x0387 || c == 0x0640 || c == 0x0e46 || c == 0x0ec6 || c == 0x3005 || (c >= 0x3031 && c <= 0x3035) || (c >= 0x309d && c <= 0x309e) || (c >= 0x30fc && c <= 0x30fe) ; } } stax-1.2.0.orig/src/com/bea/xml/stream/reader/XmlReader.java0000644000175000017500000006615110444554664023572 0ustar twernertwerner/* * $Id: XmlReader.java,v 1.1 2004/08/19 05:30:22 aslom Exp $ * * The Apache Software License, Version 1.1 * * * Copyright (c) 2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Crimson" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * 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) 1999, Sun Microsystems, Inc., * http://www.sun.com. For more information on the Apache Software * Foundation, please see . */ package com.bea.xml.stream.reader; import java.io.*; import java.util.Hashtable; /** * This handles several XML-related tasks that normal java.io Readers * don't support, inluding use of IETF standard encoding names and * automatic detection of most XML encodings. The former is needed * for interoperability; the latter is needed to conform with the XML * spec. This class also optimizes reading some common encodings by * providing low-overhead unsynchronized Reader support. * *

Note that the autodetection facility should be used only on * data streams which have an unknown character encoding. For example, * it should never be used on MIME text/xml entities. * *

Note that XML processors are only required to support UTF-8 and * UTF-16 character encodings. Autodetection permits the underlying Java * implementation to provide support for many other encodings, such as * US-ASCII, ISO-8859-5, Shift_JIS, EUC-JP, and ISO-2022-JP. * * @author David Brownell * @version $Revision: 1.1 $ */ final public class XmlReader extends Reader { private static final int MAXPUSHBACK = 512; private Reader in; private String assignedEncoding; private boolean closed; // // This class always delegates I/O to a reader, which gets // its data from the very beginning of the XML text. It needs // to use a pushback stream since (a) autodetection can read // partial UTF-8 characters which need to be fully processed, // (b) the "Unicode" readers swallow characters that they think // are byte order marks, so tests fail if they don't see the // real byte order mark. // // It's got do this efficiently: character I/O is solidly on the // critical path. (So keep buffer length over 2 Kbytes to avoid // excess buffering. Many URL handlers stuff a BufferedInputStream // between here and the real data source, and larger buffers keep // that from slowing you down.) // /** * Constructs the reader from an input stream, autodetecting * the encoding to use according to the heuristic specified * in the XML 1.0 recommendation. * * @param in the input stream from which the reader is constructed * @exception IOException on error, such as unrecognized encoding */ public static Reader createReader (InputStream in) throws IOException { return new XmlReader (in); } /** * Creates a reader supporting the given encoding, mapping * from standard encoding names to ones that understood by * Java where necessary. * * @param in the input stream from which the reader is constructed * @param encoding the IETF standard name of the encoding to use; * if null, autodetection is used. * @exception IOException on error, including unrecognized encoding */ public static Reader createReader (InputStream in, String encoding) throws IOException { if (encoding == null) { return new XmlReader(in); } if ("UTF-8".equalsIgnoreCase (encoding) || "UTF8".equalsIgnoreCase (encoding)) { return new Utf8Reader (in); } if ("US-ASCII".equalsIgnoreCase (encoding) || "ASCII".equalsIgnoreCase (encoding)) { return new AsciiReader (in); } if ("ISO-8859-1".equalsIgnoreCase (encoding) // plus numerous aliases ... ) { return new Iso8859_1Reader (in); } // What we really want is an administerable resource mapping // encoding names/aliases to classnames. For example a property // file resource, "readers/mapping.props", holding and a set // of readers in that (sub)package... defaulting to this call // only if no better choice is available. // return new InputStreamReader (in, std2java (encoding)); } // JDK doesn't know all of the standard encoding names, and // in particular none of the EBCDIC ones IANA defines (and // which IBM encourages). static private final Hashtable charsets = new Hashtable (31); static { charsets.put ("UTF-16", "Unicode"); charsets.put ("ISO-10646-UCS-2", "Unicode"); // NOTE: no support for ISO-10646-UCS-4 yet. charsets.put ("EBCDIC-CP-US", "cp037"); charsets.put ("EBCDIC-CP-CA", "cp037"); charsets.put ("EBCDIC-CP-NL", "cp037"); charsets.put ("EBCDIC-CP-WT", "cp037"); charsets.put ("EBCDIC-CP-DK", "cp277"); charsets.put ("EBCDIC-CP-NO", "cp277"); charsets.put ("EBCDIC-CP-FI", "cp278"); charsets.put ("EBCDIC-CP-SE", "cp278"); charsets.put ("EBCDIC-CP-IT", "cp280"); charsets.put ("EBCDIC-CP-ES", "cp284"); charsets.put ("EBCDIC-CP-GB", "cp285"); charsets.put ("EBCDIC-CP-FR", "cp297"); charsets.put ("EBCDIC-CP-AR1", "cp420"); charsets.put ("EBCDIC-CP-HE", "cp424"); charsets.put ("EBCDIC-CP-BE", "cp500"); charsets.put ("EBCDIC-CP-CH", "cp500"); charsets.put ("EBCDIC-CP-ROECE", "cp870"); charsets.put ("EBCDIC-CP-YU", "cp870"); charsets.put ("EBCDIC-CP-IS", "cp871"); charsets.put ("EBCDIC-CP-AR2", "cp918"); // IANA also defines two that JDK 1.2 doesn't handle: // EBCDIC-CP-GR --> CP423 // EBCDIC-CP-TR --> CP905 } // returns an encoding name supported by JDK >= 1.1.6 // for some cases required by the XML spec private static String std2java (String encoding) { String temp = encoding.toUpperCase (); temp = (String) charsets.get (temp); return (temp != null) ? temp : encoding; } /** Returns the standard name of the encoding in use */ public String getEncoding () { return assignedEncoding; } private XmlReader (InputStream stream) throws IOException { super (stream); PushbackInputStream pb; byte buf []; int len; /*if (stream instanceof PushbackInputStream) pb = (PushbackInputStream) stream; else*/ /** * Commented out the above code to make sure it works when the * document is accessed using http. URL connection in the code uses * a PushbackInputStream with size 7 and when we try to push back * MAX which default value is set to 512 we get and exception. So * that's why we need to wrap the stream irrespective of what type * of stream we start off with. */ pb = new PushbackInputStream (stream, MAXPUSHBACK); // // See if we can figure out the character encoding used // in this file by peeking at the first few bytes. // buf = new byte [4]; len = pb.read (buf); if (len > 0) pb.unread (buf, 0, len); if (len == 4) switch (buf [0] & 0x0ff) { case 0: // 00 3c 00 3f == illegal UTF-16 big-endian if (buf [1] == 0x3c && buf [2] == 0x00 && buf [3] == 0x3f) { setEncoding (pb, "UnicodeBig"); return; } // else it's probably UCS-4 break; case '<': // 0x3c: the most common cases! switch (buf [1] & 0x0ff) { // First character is '<'; could be XML without // an XML directive such as "", ""); 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()+"'"); } } stax-1.2.0.orig/src/com/bea/xml/stream/samples/Parse.java0000644000175000017500000001000510444554664023146 0ustar twernertwernerpackage com.bea.xml.stream.samples; import com.bea.xml.stream.util.ElementTypeNames; import java.io.FileReader; import java.util.Iterator; import javax.xml.stream.*; import javax.xml.stream.events.*; /** * @author Copyright (c) 2002 by BEA Systems. All Rights Reserved. */ public class Parse { private static String filename = null; private static void printUsage() { System.out.println("usage: java com.bea.xml.stream.samples.Parse "); } public static void main(String[] args) throws Exception { try { filename = args[0]; } catch (ArrayIndexOutOfBoundsException aioobe){ printUsage(); System.exit(0); } System.setProperty("javax.xml.stream.XMLInputFactory", "com.bea.xml.stream.MXParserFactory"); XMLInputFactory xmlif = XMLInputFactory.newInstance(); System.out.println("FACTORY: " + xmlif); XMLStreamReader xmlr = xmlif.createXMLStreamReader(new FileReader(filename)); System.out.println("READER: " + xmlr + "\n"); int eventType = xmlr.getEventType(); System.out.println("PARSER STATE BEFORE FIRST next(): "); printEventType(eventType); printName(xmlr); printValue(xmlr); System.out.println("-----------------------------"); while(xmlr.hasNext()){ eventType = xmlr.next(); printEventType(eventType); printName(xmlr); printValue(xmlr); if(xmlr.isStartElement()){ printAttributes(xmlr); printNamespaces(xmlr); } System.out.println("-----------------------------"); } } public final static String getEventTypeString(int eventType) { return ElementTypeNames.getEventTypeString(eventType); } 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()){ System.out.println("HAS NAME: " + xmlr.getLocalName()); } else { System.out.println("HAS NO NAME"); } } 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){ System.out.println("\nHAS ATTRIBUTES: "); Iterator ai = com.bea.xml.stream.XMLEventAllocatorBase.getAttributes(xmlr); while(ai.hasNext()){ Attribute a = (Attribute) ai.next(); System.out.println(""); printAttribute((Attribute) a); } } else { System.out.println("HAS NO ATTRIBUTES"); } } private static void printAttribute(Attribute a) { System.out.println("PREFIX: " + a.getName().getPrefix()); System.out.println("NAMESP: " + a.getName().getNamespaceURI()); System.out.println("NAME: " + a.getName().getLocalPart()); System.out.println("VALUE: " + a.getValue()); System.out.println("TYPE: " + a.getDTDType()); } private static void printNamespaces(XMLStreamReader xmlr){ if(xmlr.getNamespaceCount()>0){ System.out.println("\nHAS NAMESPACES: "); Iterator ni = com.bea.xml.stream.XMLEventAllocatorBase.getNamespaces(xmlr); while(ni.hasNext()){ Namespace n = (Namespace) ni.next(); System.out.println(""); printNamespace((Namespace)n); } } else { System.out.println("HAS NO NAMESPACES"); } } private static void printNamespace(Namespace a) { System.out.println("PREFIX: " + a.getName().getPrefix()); System.out.println("NAMESP: " + a.getName().getNamespaceURI()); System.out.println("NAME: " + a.getName().getLocalPart()); System.out.println("VALUE: " + a.getValue()); System.out.println("TYPE: " + a.getDTDType()); } } stax-1.2.0.orig/src/com/bea/xml/stream/samples/NoAllocEventParser.java0000644000175000017500000000254210444554664025611 0ustar twernertwernerpackage com.bea.xml.stream.samples; import com.bea.xml.stream.StaticAllocator; import java.io.FileReader; import javax.xml.stream.*; import javax.xml.stream.events.*; import javax.xml.stream.util.*; import javax.xml.namespace.QName; /** * @author Copyright (c) 2002 by BEA Systems. All Rights Reserved. */ public class NoAllocEventParser { private static String filename = null; private static void printUsage() { System.out.println("usage: java com.bea.xml.stream.samples.EventParse "); } public static void main(String[] args) throws Exception { try { filename = args[0]; } catch (ArrayIndexOutOfBoundsException aioobe){ printUsage(); System.exit(0); } System.setProperty("javax.xml.stream.XMLInputFactory", "com.bea.xml.stream.MXParserFactory"); System.setProperty("javax.xml.stream.XMLEventFactory", "com.bea.xml.stream.EventFactory"); XMLInputFactory factory = XMLInputFactory.newInstance(); XMLEventAllocator allocator = new StaticAllocator(); factory.setEventAllocator(allocator); XMLEventReader r = factory.createXMLEventReader(new FileReader(filename)); while(r.hasNext()) { XMLEvent e = r.nextEvent(); System.out.println("ID:"+e.hashCode()+"["+e+"]"); } } } stax-1.2.0.orig/src/com/bea/xml/stream/samples/AllocEventParser.java0000644000175000017500000000277110444554664025320 0ustar twernertwernerpackage com.bea.xml.stream.samples; import com.bea.xml.stream.StaticAllocator; import java.io.FileReader; import javax.xml.stream.*; import javax.xml.stream.events.*; import javax.xml.stream.util.*; import javax.xml.namespace.QName; /** * @author Copyright (c) 2002 by BEA Systems. All Rights Reserved. */ public class AllocEventParser { private static String filename = null; private static void printUsage() { System.out.println("usage: java com.bea.xml.stream.samples.AllocEventParse "); } public static void main(String[] args) throws Exception { try { filename = args[0]; } catch (ArrayIndexOutOfBoundsException aioobe){ printUsage(); System.exit(0); } System.setProperty("javax.xml.stream.XMLInputFactory", "com.bea.xml.stream.MXParserFactory"); System.setProperty("javax.xml.stream.XMLOutputFactory", "com.bea.xml.stream.XMLOutputFactoryBase"); System.setProperty("javax.xml.stream.XMLEventFactory", "com.bea.xml.stream.EventFactory"); XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.FALSE); XMLEventReader r = factory.createXMLEventReader(new FileReader(filename)); while(r.hasNext()) { XMLEvent e = r.nextEvent(); System.out.println("ID:"+e.hashCode()+"["+e+"]"); } } } stax-1.2.0.orig/src/com/bea/xml/stream/StreamReaderFilter.java0000644000175000017500000000612110444554664024160 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream; import com.bea.xml.stream.filters.TypeFilter; import com.bea.xml.stream.filters.NameFilter; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.StreamFilter; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.StreamFilter; /** *

Apply a filter to the StreamReader

*/ public class StreamReaderFilter extends ReaderDelegate { private StreamFilter filter; public StreamReaderFilter(XMLStreamReader reader) { super(reader); } public StreamReaderFilter(XMLStreamReader reader, StreamFilter filter) { super(reader); setFilter(filter); } public void setFilter(StreamFilter filter) { this.filter = filter; } public int next() throws XMLStreamException { if (hasNext()) return super.next(); throw new IllegalStateException("next() may not be called "+ " when there are no more "+ " items to return"); } public boolean hasNext() throws XMLStreamException { while (super.hasNext()) { if (filter.accept(getDelegate())) return true; super.next(); } return false; } public static void main(String args[]) throws Exception { System.setProperty("javax.xml.stream.XMLInputFactory", "com.bea.xml.stream.MXParserFactory"); XMLInputFactory factory = XMLInputFactory.newInstance(); TypeFilter f = new com.bea.xml.stream.filters.TypeFilter(); f.addType(XMLEvent.START_ELEMENT); f.addType(XMLEvent.END_ELEMENT); XMLStreamReader reader = factory.createFilteredReader( factory.createXMLStreamReader(new java.io.FileReader(args[0])),(StreamFilter)f); while(reader.hasNext()) { System.out.println(reader.getLocalName()); reader.next(); } NameFilter nf = new NameFilter(new QName("banana","B")); XMLStreamReader reader2 = factory.createFilteredReader( factory.createXMLStreamReader(new java.io.FileReader(args[0])),(StreamFilter)nf); XMLStreamRecorder r = new XMLStreamRecorder(new java.io.OutputStreamWriter(new java.io.FileOutputStream("out.stream"))); while(reader2.hasNext()) { r.write(reader2); reader2.next(); } r.flush(); } } stax-1.2.0.orig/src/com/bea/xml/stream/ReaderToWriter.java0000644000175000017500000001016210444554664023336 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream; import javax.xml.stream.XMLStreamWriter; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; /** *

Automatically write a reader.

*/ public class ReaderToWriter { private XMLStreamWriter writer; public ReaderToWriter(){} public ReaderToWriter(XMLStreamWriter xmlw) { writer = xmlw; } public void setStreamWriter(XMLStreamWriter xmlw) { writer = xmlw; } public void write(XMLStreamReader xmlr) throws XMLStreamException { System.out.println("wrote event"); switch (xmlr.getEventType()) { case XMLEvent.START_ELEMENT: String prefix = xmlr.getPrefix(); String namespaceURI = xmlr.getNamespaceURI(); if (namespaceURI != null) { if(prefix != null) writer.writeStartElement(xmlr.getPrefix(), xmlr.getLocalName(), xmlr.getNamespaceURI()); else writer.writeStartElement(xmlr.getNamespaceURI(), xmlr.getLocalName()); } else { writer.writeStartElement(xmlr.getLocalName()); } for (int i =0; i < xmlr.getNamespaceCount(); i++) { writer.writeNamespace(xmlr.getNamespacePrefix(i), xmlr.getNamespaceURI(i)); } break; case XMLEvent.END_ELEMENT: writer.writeEndElement(); break; case XMLEvent.SPACE: case XMLEvent.CHARACTERS: writer.writeCharacters(xmlr.getTextCharacters(), xmlr.getTextStart(), xmlr.getTextLength()); break; case XMLEvent.PROCESSING_INSTRUCTION: writer.writeProcessingInstruction(xmlr.getPITarget(), xmlr.getPIData()); break; case XMLEvent.CDATA: writer.writeCData(xmlr.getText()); break; case XMLEvent.COMMENT: writer.writeComment(xmlr.getText()); break; case XMLEvent.ENTITY_REFERENCE: writer.writeEntityRef(xmlr.getLocalName()); break; case XMLEvent.START_DOCUMENT: String encoding = xmlr.getCharacterEncodingScheme(); String version = xmlr.getVersion(); if (encoding != null && version != null) writer.writeStartDocument(encoding, version); else if (version != null) writer.writeStartDocument(xmlr.getVersion()); break; case XMLEvent.END_DOCUMENT: writer.writeEndDocument(); break; case XMLEvent.DTD: writer.writeDTD(xmlr.getText()); break; } } public XMLStreamWriter writeAll(XMLStreamReader xmlr) throws XMLStreamException { while (xmlr.hasNext()) { write(xmlr); xmlr.next(); } writer.flush(); return writer; } public static void main(String args[]) throws Exception { XMLInputFactory xmlif = XMLInputFactory.newInstance(); XMLOutputFactory xmlof = XMLOutputFactory.newInstance(); XMLStreamReader xmlr = xmlif.createXMLStreamReader(new java.io.FileReader(args[0])); XMLStreamWriter xmlw = xmlof.createXMLStreamWriter(System.out); ReaderToWriter rtow = new ReaderToWriter(xmlw); while (xmlr.hasNext()) { rtow.write(xmlr); xmlr.next(); } xmlw.flush(); } } stax-1.2.0.orig/src/com/bea/xml/stream/EventScanner.java0000644000175000017500000002361410444554664023035 0ustar twernertwerner/* Copyright 2004 BEA Systems, Inc. * * 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. */ package com.bea.xml.stream; import javax.xml.namespace.QName; import javax.xml.stream.events.XMLEvent; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.Namespace; import com.bea.xml.stream.util.ElementTypeNames; import com.bea.xml.stream.AttributeBase; import com.bea.xml.stream.NamespaceBase; import java.io.Reader; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.io.FileReader; /** *

This class replays events from a simple non-xml file format

* */ public class EventScanner { protected Reader reader; protected char currentChar; protected int currentLine=0; private boolean readEndDocument = false; public EventScanner(){} public EventScanner(Reader reader) throws IOException { setReader(reader); } public void setReader(Reader reader) throws IOException { this.reader = reader; read(); skipSpace(); } protected String readString(char delim) throws IOException, XMLStreamException { StringBuffer buf = new StringBuffer(); while(getChar()!=delim) { if (getChar() == '[' && delim ==']') { read(); buf.append('['); if (getChar() != ']') buf.append(readString(']')); buf.append(']'); read(']'); } else { buf.append(getChar()); read(); } } return buf.toString(); } protected char getChar() { return currentChar; } protected void skipSpace() throws IOException { while (currentChar == ' ' | currentChar == '\n' | currentChar == '\t' | currentChar =='\r') read(); } protected char read() throws IOException { currentChar = (char) reader.read(); if (currentChar == '\n') currentLine++; return currentChar; } protected char read(char c) throws XMLStreamException, IOException { if (currentChar == c) return read(); else throw new XMLStreamException("Unexpected character '"+currentChar+"' , expected '"+c+"' at line "+currentLine); } protected void read(String s) throws XMLStreamException, IOException { for (int i=0; i < s.length(); i++) read(s.charAt(i)); } protected int readType() throws XMLStreamException, IOException { read('['); String typeName = readString(']'); int type= ElementTypeNames.getEventType(typeName); read(']'); return type; } public EventState readStartElement() throws XMLStreamException, IOException { EventState state = new EventState(XMLEvent.START_ELEMENT); read('['); state.setName(readName()); if (getChar()=='[') { List atts = readAttributes(); Iterator i = atts.iterator(); while(i.hasNext()) { Object obj = i.next(); if (obj instanceof Namespace) state.addNamespace(obj); else state.addAttribute(obj); } } read(']'); return state; } public EventState readEndElement() throws XMLStreamException, IOException { EventState state = new EventState(XMLEvent.END_ELEMENT); read('['); state.setName(readName()); read(']'); return state; } public EventState readProcessingInstruction() throws XMLStreamException, IOException { EventState state = new EventState(XMLEvent.PROCESSING_INSTRUCTION); read('['); String name = readString(']'); read(']'); String s = null; if (getChar() == ',') { read(",["); s = readString(']'); read(']'); } state.setData(name); state.setExtraData(s); return state; } public EventState readCharacterData() throws XMLStreamException, IOException { EventState state = new EventState(XMLEvent.CHARACTERS); read('['); state.setData(readString(']')); read(']'); return state; } public EventState readCDATA() throws XMLStreamException, IOException { EventState state = new EventState(XMLEvent.CDATA); read('['); readString(']'); read(']'); return state; } public EventState readStartDocument() throws XMLStreamException, IOException { EventState state = new EventState(XMLEvent.START_DOCUMENT); if (getChar() != ';') { read('['); read('['); String version = readString(']'); read(']'); read(','); read('['); String encoding = readString(']'); read(']'); read(']'); state.setData(version); state.setExtraData(encoding); } return state; } public EventState readDTD() throws XMLStreamException, IOException { EventState state = new EventState(XMLEvent.DTD); read('['); String dtd = readString(']'); read(']'); state.setData(dtd); return state; } public EventState readEndDocument() throws XMLStreamException { EventState state = new EventState(XMLEvent.END_DOCUMENT); return state; } public EventState readComment() throws XMLStreamException, IOException { EventState state = new EventState(XMLEvent.COMMENT); read('['); state.setData(readString(']')); read(']'); return state; } public String getPrefix(String name) { int index = name.indexOf(':'); if (index == -1) return null; return name.substring(0,index); } public String getName(String name) { int index = name.indexOf(':'); if (index == -1) return name; return name.substring(index+1); } public QName readName() throws XMLStreamException, IOException { read('['); QName n = readName(']'); read(']'); return n; } public QName readName(char delim) throws XMLStreamException, IOException { String uri = ""; String prefix = ""; if (getChar() == '\'') { read('\''); uri=readString('\''); read('\''); read(':'); } String name = readString(delim); prefix=getPrefix(name); if (prefix == null) prefix = ""; String localName = getName(name); return new QName(uri,localName,prefix); } public List readAttributes() throws XMLStreamException, IOException { List attributes = new ArrayList(); while(getChar() == '[') { attributes.add(readAttribute()); } return attributes; } public Attribute readAttribute() throws XMLStreamException, IOException { read('['); read('['); String type=readString(']'); read(']'); QName n = readName(); read("=["); String value=readString(']'); read(']'); read(']'); if (type.equals("ATTRIBUTE")) return new AttributeBase(n,value); if (type.equals("DEFAULT")) return new NamespaceBase(value); if (type.equals("NAMESPACE")) return (new NamespaceBase(n.getLocalPart(), value)); throw new XMLStreamException("Parser Error expected (ATTRIBUTE|"+ "|DEFAULT|NAMESPACE"); } public EventState readEntityReference () throws XMLStreamException, IOException { EventState state = new EventState(XMLEvent.ENTITY_REFERENCE); read('['); state.setData(readString(']')); read(']'); return state; } public EventState readSpace() throws XMLStreamException, IOException { EventState state = new EventState(XMLEvent.SPACE); read('['); String content = readString(']'); read(']'); state.setData(content); return state; } public EventState readElement() throws XMLStreamException, IOException { int type = readType(); EventState state; switch(type) { case XMLEvent.START_ELEMENT: state=readStartElement();break; case XMLEvent.END_ELEMENT: state=readEndElement();break; case XMLEvent.PROCESSING_INSTRUCTION: state=readProcessingInstruction();break; case XMLEvent.CHARACTERS: state=readCharacterData();break; case XMLEvent.COMMENT: state=readComment();break; case XMLEvent.START_DOCUMENT: state=readStartDocument();break; case XMLEvent.END_DOCUMENT: readEndDocument = true; state=readEndDocument();break; case XMLEvent.ENTITY_REFERENCE: state=readEntityReference() ;break; case XMLEvent.SPACE: state=readSpace();break; case XMLEvent.DTD: state=readDTD();break; case XMLEvent.CDATA: state=readCDATA();break; default: throw new XMLStreamException("Attempt to read unknown element ["+type+"]"); } read(';'); skipSpace(); return state; } public boolean endDocumentIsPresent() { return readEndDocument; } public boolean hasNext() throws IOException { return (reader.ready() && !readEndDocument); } public static void main(String args[]) throws Exception { EventScanner reader = new EventScanner(new FileReader(args[0])); while(reader.hasNext()) System.out.println(reader.readElement()); } } stax-1.2.0.orig/src/com/wutka/0000755000175000017500000000000010444554664016102 5ustar twernertwernerstax-1.2.0.orig/src/com/wutka/dtd/0000755000175000017500000000000010444554664016655 5ustar twernertwernerstax-1.2.0.orig/src/com/wutka/dtd/DTDDecl.java0000644000175000017500000000257510444554664020734 0ustar twernertwernerpackage com.wutka.dtd; import java.io.*; /** Represents the possible values for an attribute declaration * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public class DTDDecl implements DTDOutput { public static final DTDDecl FIXED = new DTDDecl(0, "FIXED"); public static final DTDDecl REQUIRED = new DTDDecl(1, "REQUIRED"); public static final DTDDecl IMPLIED = new DTDDecl(2, "IMPLIED"); public static final DTDDecl VALUE = new DTDDecl(3, "VALUE"); public int type; public String name; public DTDDecl(int aType, String aName) { type = aType; name = aName; } public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof DTDDecl)) return false; DTDDecl other = (DTDDecl) ob; if (other.type == type) return true; return false; } public void write(PrintWriter out) throws IOException { if (this == FIXED) { out.print(" #FIXED"); } else if (this == REQUIRED) { out.print(" #REQUIRED"); } else if (this == IMPLIED) { out.print(" #IMPLIED"); } // Don't do anything for value since there is no associated DTD keyword } } stax-1.2.0.orig/src/com/wutka/dtd/DTDNotationList.java0000644000175000017500000000455710444554664022516 0ustar twernertwernerpackage com.wutka.dtd; import java.util.*; import java.io.*; /** Represents a notation declaration for an attribute * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public class DTDNotationList implements DTDOutput { protected Vector items; /** Creates a new notation */ public DTDNotationList() { items = new Vector(); } /** Adds a item to the list of notation values */ public void add(String item) { items.addElement(item); } /** Removes an item from the list of notation values */ public void remove(String item) { items.removeElement(item); } /** Returns the list of notation values as an array */ public String[] getItems() { String[] retval = new String[items.size()]; items.copyInto(retval); return retval; } /** Returns the list of notation values as a vector */ public Vector getItemsVec() { return items; } /** Writes a declaration for this notation */ public void write(PrintWriter out) throws IOException { out.print("NOTATION ( "); Enumeration e = getItemsVec().elements(); boolean isFirst = true; while (e.hasMoreElements()) { if (!isFirst) out.print(" | "); isFirst = false; out.print(e.nextElement()); } out.print(")"); } public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof DTDNotationList)) return false; DTDNotationList other = (DTDNotationList) ob; return items.equals(other.items); } /** Returns the items in the notation list */ public String[] getItem() { return getItems(); } /** Sets the items in the notation list */ public void setItem(String[] newItems) { items = new Vector(newItems.length); for (int i=0; i < newItems.length; i++) { items.addElement(newItems[i]); } } /** Stores an item in the notation list */ public void setItem(String item, int i) { items.setElementAt(item, i); } /** Retrieves an item from the notation list */ public String getItem(int i) { return (String) items.elementAt(i); } } stax-1.2.0.orig/src/com/wutka/dtd/DTDEnumeration.java0000644000175000017500000000447610444554664022355 0ustar twernertwernerpackage com.wutka.dtd; import java.util.*; import java.io.*; /** Represents an enumeration of attribute values * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public class DTDEnumeration implements DTDOutput { protected Vector items; /** Creates a new enumeration */ public DTDEnumeration() { items = new Vector(); } /** Adds a new value to the list of values */ public void add(String item) { items.addElement(item); } /** Removes a value from the list of values */ public void remove(String item) { items.removeElement(item); } /** Returns the values as an array */ public String[] getItems() { String[] retval = new String[items.size()]; items.copyInto(retval); return retval; } /** Returns the values as a vector (not a clone!) */ public Vector getItemsVec() { return items; } /** Writes out a declaration for this enumeration */ public void write(PrintWriter out) throws IOException { out.print("( "); Enumeration e = getItemsVec().elements(); boolean isFirst = true; while (e.hasMoreElements()) { if (!isFirst) out.print(" | "); isFirst = false; out.print(e.nextElement()); } out.print(")"); } public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof DTDEnumeration)) return false; DTDEnumeration other = (DTDEnumeration) ob; return items.equals(other.items); } /** Returns the items in the enumeration */ public String[] getItem() { return getItems(); } /** Sets the items in the enumeration */ public void setItem(String[] newItems) { items = new Vector(newItems.length); for (int i=0; i < newItems.length; i++) { items.addElement(newItems[i]); } } /** Stores an item in the enumeration */ public void setItem(String item, int i) { items.setElementAt(item, i); } /** Retrieves an item from the enumeration */ public String getItem(int i) { return (String) items.elementAt(i); } } stax-1.2.0.orig/src/com/wutka/dtd/DTDAttribute.java0000644000175000017500000000747410444554664022033 0ustar twernertwernerpackage com.wutka.dtd; import java.io.*; /** Represents a DTD Attribute in an ATTLIST declaration * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public class DTDAttribute implements DTDOutput { /** The name of the attribute */ public String name; /** The type of the attribute (either String, DTDEnumeration or DTDNotationList) */ public Object type; /** The attribute's declaration (required, fixed, implied) */ public DTDDecl decl; /** The attribute's default value (null if not declared) */ public String defaultValue; public DTDAttribute() { } public DTDAttribute(String aName) { name = aName; } /** Writes this attribute to an output stream */ public void write(PrintWriter out) throws IOException { out.print(name+" "); if (type instanceof String) { out.print(type); } else if (type instanceof DTDEnumeration) { DTDEnumeration dtdEnum = (DTDEnumeration) type; dtdEnum.write(out); } else if (type instanceof DTDNotationList) { DTDNotationList dtdnl = (DTDNotationList) type; dtdnl.write(out); } if (decl != null) { decl.write(out); } if (defaultValue != null) { out.print(" \""); out.print(defaultValue); out.print("\""); } //out.println(">"); Bug! } public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof DTDAttribute)) return false; DTDAttribute other = (DTDAttribute) ob; if (name == null) { if (other.name != null) return false; } else { if (!name.equals(other.name)) return false; } if (type == null) { if (other.type != null) return false; } else { if (!type.equals(other.type)) return false; } if (decl == null) { if (other.decl != null) return false; } else { if (!decl.equals(other.decl)) return false; } if (defaultValue == null) { if (other.defaultValue != null) return false; } else { if (!defaultValue.equals(other.defaultValue)) return false; } return true; } /** Sets the name of the attribute */ public void setName(String aName) { name = aName; } /** Returns the attribute name */ public String getName() { return name; } /** Sets the type of the attribute */ public void setType(Object aType) { if (!(aType instanceof String) && !(aType instanceof DTDEnumeration) && !(aType instanceof DTDNotationList)) { throw new IllegalArgumentException( "Must be String, DTDEnumeration or DTDNotationList"); } type = aType; } /** Gets the type of the attribute */ public Object getType() { return type; } /** Sets the declaration (fixed, required, implied) */ public void setDecl(DTDDecl aDecl) { decl = aDecl; } /** Returns the declaration */ public DTDDecl getDecl() { return decl; } /** Sets the default value */ public void setDefaultValue(String aDefaultValue) { defaultValue = aDefaultValue; } /** Returns the default value */ public String getDefaultValue() { return defaultValue; } } stax-1.2.0.orig/src/com/wutka/dtd/DTDChoice.java0000644000175000017500000000206710444554664021253 0ustar twernertwernerpackage com.wutka.dtd; import java.io.*; import java.util.*; /** Represents a choice of items. * A choice in a DTD looks like (option1 | option2 | option3) * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public class DTDChoice extends DTDContainer { public DTDChoice() { } /** Writes out the possible choices to a PrintWriter */ public void write(PrintWriter out) throws IOException { out.print("("); Enumeration e = getItemsVec().elements(); boolean isFirst = true; while (e.hasMoreElements()) { if (!isFirst) out.print(" | "); isFirst = false; DTDItem item = (DTDItem) e.nextElement(); item.write(out); } out.print(")"); cardinal.write(out); } public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof DTDChoice)) return false; return super.equals(ob); } } stax-1.2.0.orig/src/com/wutka/dtd/DTDEmpty.java0000644000175000017500000000123110444554664021147 0ustar twernertwernerpackage com.wutka.dtd; import java.io.*; /** Represents the EMPTY keyword in an Element's content spec * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public class DTDEmpty extends DTDItem { public DTDEmpty() { } /** Writes out the keyword "EMPTY" */ public void write(PrintWriter out) throws IOException { out.print("EMPTY"); cardinal.write(out); } public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof DTDEmpty)) return false; return super.equals(ob); } } stax-1.2.0.orig/src/com/wutka/dtd/DTDCardinal.java0000644000175000017500000000367510444554664021604 0ustar twernertwernerpackage com.wutka.dtd; import java.io.*; /** Represents the various cardinality values for a DTD item. * *
  • NONE indicates no cardinality
  • *
  • OPTIONAL indicates an optional value (specified by ?)
  • *
  • ZEROMANY indicates zero-to-many values (specified by *)
  • *
  • ONEMANY indicates an one-to-many values (specified by +)
  • *
    * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public class DTDCardinal implements DTDOutput { /** Indicates no cardinality (implies a single object) */ public static final DTDCardinal NONE = new DTDCardinal(0, "NONE"); /** Indicates that an item is optional (zero-to-one) */ public static final DTDCardinal OPTIONAL = new DTDCardinal(1, "OPTIONAL"); /** Indicates that there can be zero-to-many occurrances of an item */ public static final DTDCardinal ZEROMANY = new DTDCardinal(2, "ZEROMANY"); /** Indicates that there can be one-to-many occurrances of an item */ public static final DTDCardinal ONEMANY = new DTDCardinal(3, "ONEMANY"); public int type; public String name; public DTDCardinal(int aType, String aName) { type = aType; name = aName; } public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof DTDCardinal)) return false; DTDCardinal other = (DTDCardinal) ob; if (other.type == type) return true; return false; } /** Writes the notation for this cardinality value */ public void write(PrintWriter out) throws IOException { if (this == NONE) return; if (this == OPTIONAL) { out.print("?"); } else if (this == ZEROMANY) { out.print("*"); } else if (this == ONEMANY) { out.print("+"); } } } stax-1.2.0.orig/src/com/wutka/dtd/DTDName.java0000644000175000017500000000231610444554664020736 0ustar twernertwernerpackage com.wutka.dtd; import java.io.*; /** Represents a named item in the DTD * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public class DTDName extends DTDItem { public String value; public DTDName() { } public DTDName(String aValue) { value = aValue; } /** Writes out the value of this name */ public void write(PrintWriter out) throws IOException { out.print(value); cardinal.write(out); } public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof DTDName)) return false; if (!super.equals(ob)) return false; DTDName other = (DTDName) ob; if (value == null) { if (other.value != null) return false; } else { if (!value.equals(other.value)) return false; } return true; } /** Sets the name value */ public void setValue(String aValue) { value = aValue; } /** Retrieves the name value */ public String getValue() { return value; } } stax-1.2.0.orig/src/com/wutka/dtd/DTDElement.java0000644000175000017500000000646210444554664021455 0ustar twernertwernerpackage com.wutka.dtd; import java.util.*; import java.io.*; /** Represents an element defined with the ELEMENT DTD tag * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public class DTDElement implements DTDOutput { /** The name of the element */ public String name; /** The element's attributes */ public Hashtable attributes; /** The element's content */ public DTDItem content; public DTDElement() { attributes = new Hashtable(); } public DTDElement(String aName) { name = aName; attributes = new Hashtable(); } /** Writes out an element declaration and an attlist declaration (if necessary) for this element */ public void write(PrintWriter out) throws IOException { out.print(""); out.println(); /* if (attributes.size() > 0) { out.print(""); } } */ } public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof DTDElement)) return false; DTDElement other = (DTDElement) ob; if (name == null) { if (other.name != null) return false; } else { if (!name.equals(other.name)) return false; } if (attributes == null) { if (other.attributes != null) return false; } else { if (!attributes.equals(other.attributes)) return false; } if (content == null) { if (other.content != null) return false; } else { if (!content.equals(other.content)) return false; } return true; } /** Sets the name of this element */ public void setName(String aName) { name = aName; } /** Returns the name of this element */ public String getName() { return name; } /** Stores an attribute in this element */ public void setAttribute(String attrName, DTDAttribute attr) { attributes.put(attrName, attr); } /** Gets an attribute for this element */ public DTDAttribute getAttribute(String attrName) { return (DTDAttribute) attributes.get(attrName); } /** Sets the content type of this element */ public void setContent(DTDItem theContent) { content = theContent; } /** Returns the content type of this element */ public DTDItem getContent() { return content; } } stax-1.2.0.orig/src/com/wutka/dtd/DTDProcessingInstruction.java0000644000175000017500000000257110444554664024437 0ustar twernertwernerpackage com.wutka.dtd; import java.io.*; /** Represents a processing instruction in the DTD * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public class DTDProcessingInstruction implements DTDOutput { /** The processing instruction text */ public String text; public DTDProcessingInstruction() { } public DTDProcessingInstruction(String theText) { text = theText; } public String toString() { return text; } public void write(PrintWriter out) throws IOException { out.print(""); } public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof DTDProcessingInstruction)) return false; DTDProcessingInstruction other = (DTDProcessingInstruction) ob; if (text == null) { if (other.text != null) return false; } else { if (!text.equals(other.text)) return false; } return true; } /** Sets the instruction text */ public void setText(String theText) { text = theText; } /** Retrieves the instruction text */ public String getText() { return text; } } stax-1.2.0.orig/src/com/wutka/dtd/DTDItem.java0000644000175000017500000000244110444554664020753 0ustar twernertwernerpackage com.wutka.dtd; import java.io.*; /** Represents any item in the DTD * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public abstract class DTDItem implements DTDOutput { /** Indicates how often the item may occur */ public DTDCardinal cardinal; public DTDItem() { cardinal = DTDCardinal.NONE; } public DTDItem(DTDCardinal aCardinal) { cardinal = aCardinal; } /** Writes out a declaration for this item */ public abstract void write(PrintWriter out) throws IOException; public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof DTDItem)) return false; DTDItem other = (DTDItem) ob; if (cardinal == null) { if (other.cardinal != null) return false; } else { if (!cardinal.equals(other.cardinal)) return false; } return true; } /** Sets the cardinality of the item */ public void setCardinal(DTDCardinal aCardinal) { cardinal = aCardinal; } /** Retrieves the cardinality of the item */ public DTDCardinal getCardinal() { return cardinal; } } stax-1.2.0.orig/src/com/wutka/dtd/DTDAttlist.java0000644000175000017500000000560410444554664021505 0ustar twernertwernerpackage com.wutka.dtd; import java.util.*; import java.io.*; /** Represents an ATTLIST declaration in the DTD. Although attributes are * associated with elements, the ATTLIST is here to allow the DTD object * to write out the DTD in roughly the original form. Because the ATTLIST * may appear somewhere other than immediately after the ELEMENT, this object * is used to keep track of where it is. * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public class DTDAttlist implements DTDOutput { /** The name of the element */ public String name; /** The attlist's attributes */ public Vector attributes; public DTDAttlist() { attributes = new Vector(); } public DTDAttlist(String aName) { name = aName; attributes = new Vector(); } /** Writes out an ATTLIST declaration */ public void write(PrintWriter out) throws IOException { out.print(""); } } } public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof DTDAttlist)) return false; DTDAttlist other = (DTDAttlist) ob; if ((name == null) && (other.name != null)) return false; if ((name != null) && !name.equals(other.name)) return false; return attributes.equals(other.attributes); } /** Returns the entity name of this attlist */ public String getName() { return name; } /** Sets the entity name of this attlist */ public void setName(String aName) { name = aName; } /** Returns the attributes in this list */ public DTDAttribute[] getAttribute() { DTDAttribute attrs[] = new DTDAttribute[attributes.size()]; attributes.copyInto(attrs); return attrs; } /** Sets the list of attributes */ public void setAttribute(DTDAttribute[] attrs) { attributes = new Vector(attrs.length); for (int i=0; i < attrs.length; i++) { attributes.addElement(attrs[i]); } } /** Returns a specific attribute from the list */ public DTDAttribute getAttribute(int i) { return (DTDAttribute) attributes.elementAt(i); } /** Sets a specific attribute in the list */ public void setAttribute(DTDAttribute attr, int i) { attributes.setElementAt(attr, i); } } stax-1.2.0.orig/src/com/wutka/dtd/Tokenize.java0000644000175000017500000001676110444554664021323 0ustar twernertwernerpackage com.wutka.dtd; import java.io.*; import java.util.*; import java.net.URL; /** Example program to read a DTD and print out its object model * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:24 $ by $Author: aslom $ */ class Tokenize { public static void main(String[] args) { try { DTDParser parser = null; // MAW Version 1.17 // If it looks like the filename may be a URL, use the URL class if (args[0].indexOf("://") > 0) { parser = new DTDParser(new URL(args[0]), true); } else { parser = new DTDParser(new File(args[0]), true); } // Parse the DTD and ask the parser to guess the root element DTD dtd = parser.parse(true); if (dtd.rootElement != null) { System.out.println("Root element is probably: "+ dtd.rootElement.name); } Enumeration e = dtd.elements.elements(); while (e.hasMoreElements()) { DTDElement elem = (DTDElement) e.nextElement(); System.out.println("Element: "+elem.name); System.out.print(" Content: "); dumpDTDItem(elem.content); System.out.println(); if (elem.attributes.size() > 0) { System.out.println(" Attributes: "); Enumeration attrs = elem.attributes.elements(); while (attrs.hasMoreElements()) { System.out.print(" "); DTDAttribute attr = (DTDAttribute) attrs.nextElement(); dumpAttribute(attr); } System.out.println(); } } e = dtd.entities.elements(); while (e.hasMoreElements()) { DTDEntity entity = (DTDEntity) e.nextElement(); if (entity.isParsed) System.out.print("Parsed "); System.out.println("Entity: "+entity.name); if (entity.value != null) { System.out.println(" Value: "+entity.value); } if (entity.externalID != null) { if (entity.externalID instanceof DTDSystem) { System.out.println(" System: "+ entity.externalID.system); } else { DTDPublic pub = (DTDPublic) entity.externalID; System.out.println(" Public: "+ pub.pub+" "+pub.system); } } if (entity.ndata != null) { System.out.println(" NDATA "+entity.ndata); } } e = dtd.notations.elements(); while (e.hasMoreElements()) { DTDNotation notation = (DTDNotation) e.nextElement(); System.out.println("Notation: "+notation.name); if (notation.externalID != null) { if (notation.externalID instanceof DTDSystem) { System.out.println(" System: "+ notation.externalID.system); } else { DTDPublic pub = (DTDPublic) notation.externalID; System.out.print(" Public: "+ pub.pub+" "); if (pub.system != null) { System.out.println(pub.system); } else { System.out.println(); } } } } } catch (Exception exc) { exc.printStackTrace(System.out); } } public static void dumpDTDItem(DTDItem item) { if (item == null) return; if (item instanceof DTDAny) { System.out.print("Any"); } else if (item instanceof DTDEmpty) { System.out.print("Empty"); } else if (item instanceof DTDName) { System.out.print(((DTDName) item).value); } else if (item instanceof DTDChoice) { System.out.print("("); DTDItem[] items = ((DTDChoice) item).getItems(); for (int i=0; i < items.length; i++) { if (i > 0) System.out.print("|"); dumpDTDItem(items[i]); } System.out.print(")"); } else if (item instanceof DTDSequence) { System.out.print("("); DTDItem[] items = ((DTDSequence) item).getItems(); for (int i=0; i < items.length; i++) { if (i > 0) System.out.print(","); dumpDTDItem(items[i]); } System.out.print(")"); } else if (item instanceof DTDMixed) { System.out.print("("); DTDItem[] items = ((DTDMixed) item).getItems(); for (int i=0; i < items.length; i++) { if (i > 0) System.out.print(","); dumpDTDItem(items[i]); } System.out.print(")"); } else if (item instanceof DTDPCData) { System.out.print("#PCDATA"); } if (item.cardinal == DTDCardinal.OPTIONAL) { System.out.print("?"); } else if (item.cardinal == DTDCardinal.ZEROMANY) { System.out.print("*"); } else if (item.cardinal == DTDCardinal.ONEMANY) { System.out.print("+"); } } public static void dumpAttribute(DTDAttribute attr) { System.out.print(attr.name+" "); if (attr.type instanceof String) { System.out.print(attr.type); } else if (attr.type instanceof DTDEnumeration) { System.out.print("("); String[] items = ((DTDEnumeration) attr.type).getItems(); for (int i=0; i < items.length; i++) { if (i > 0) System.out.print(","); System.out.print(items[i]); } System.out.print(")"); } else if (attr.type instanceof DTDNotationList) { System.out.print("Notation ("); String[] items = ((DTDNotationList) attr.type).getItems(); for (int i=0; i < items.length; i++) { if (i > 0) System.out.print(","); System.out.print(items[i]); } System.out.print(")"); } if (attr.decl != null) { System.out.print(" "+attr.decl.name); } if (attr.defaultValue != null) { System.out.print(" "+attr.defaultValue); } System.out.println(); } } stax-1.2.0.orig/src/com/wutka/dtd/DTDOutput.java0000644000175000017500000000050610444554664021355 0ustar twernertwernerpackage com.wutka.dtd; import java.io.*; /** Defines the method used for writing DTD information to a PrintWriter * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public interface DTDOutput { public void write(PrintWriter out) throws IOException; } stax-1.2.0.orig/src/com/wutka/dtd/DTDEntity.java0000644000175000017500000001332210444554664021331 0ustar twernertwernerpackage com.wutka.dtd; import java.io.*; import java.net.*; /** Represents an Entity defined in a DTD * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public class DTDEntity implements DTDOutput { public String name; public boolean isParsed; public String value; public DTDExternalID externalID; public String ndata; public Object defaultLocation; public DTDEntity() { } public DTDEntity(String aName) { name = aName; } public DTDEntity(String aName, Object aDefaultLocation) { name = aName; defaultLocation = aDefaultLocation; } /** Writes out an entity declaration for this entity */ public void write(PrintWriter out) throws IOException { out.print("= 0) quoteChar='\''; out.print(quoteChar); out.print(value); out.print(quoteChar); } else { externalID.write(out); if (ndata != null) { out.print(" NDATA "); out.print(ndata); } } out.println(">"); } public String getExternalId() { return(externalID.system); } public Reader getReader() throws IOException { // MAW Ver 1.19 - Added check for externalID == null if (externalID == null) { return null; } Reader rd = getReader(externalID.system); return rd; } public Reader getReader(String entityName) { try { if (defaultLocation != null) { if (defaultLocation instanceof File) { File loc = (File) defaultLocation; BufferedReader in = new BufferedReader( new FileReader(new File(loc, entityName))); return in; } else if (defaultLocation instanceof URL) { // MAW Version 1.17 // Changed to construct new URL based on default // location plus the entity name just like is done // with the File-based name. This allows parsing of // a URL-based DTD file that references other files either // relatively or absolutely. URL url = new URL((URL) defaultLocation, entityName); BufferedReader in = new BufferedReader( new InputStreamReader(url.openStream())); return in; } } BufferedReader in = new BufferedReader( new FileReader(entityName)); return in; } catch (Exception ignore) { } try { URL url = new URL(entityName); InputStream inStream = url.openStream(); BufferedReader in = new BufferedReader( new InputStreamReader(inStream)); return in; } catch (Exception ignore) { } return null; } public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof DTDEntity)) return false; DTDEntity other = (DTDEntity) ob; if (name == null) { if (other.name != null) return false; } else { if (!name.equals(other.name)) return false; } if (isParsed != other.isParsed) return false; if (value == null) { if (other.value != null) return false; } else { if (!value.equals(other.value)) return false; } if (externalID == null) { if (other.externalID != null) return false; } else { if (!externalID.equals(other.externalID)) return false; } if (ndata == null) { if (other.ndata != null) return false; } else { if (!ndata.equals(other.ndata)) return false; } return true; } /** Sets the name of this entity */ public void setName(String aName) { name = aName; } /** Returns the name of this entity */ public String getName() { return name; } /** Sets the isParsed flag */ public void setIsParsed(boolean flag) { isParsed = flag; } /** Returns the isParsed flag */ public boolean isParsed() { return isParsed; } /** Sets the entity value */ public void setValue(String aValue) { value = aValue; } /** Returns the entity value */ public String getValue() { return value; } /** Sets the external ID for the entity */ public void setExternalID(DTDExternalID anExternalID) { externalID = anExternalID; } /** Returns the external ID for the entity */ public DTDExternalID getExternalID() { return externalID; } /** Sets the entity ndata */ public void setNdata(String anNdata) { ndata = anNdata; } /** Returns the entity ndata */ public String getNdata() { return ndata; } } stax-1.2.0.orig/src/com/wutka/dtd/DTDMixed.java0000644000175000017500000000220110444554664021115 0ustar twernertwernerpackage com.wutka.dtd; import java.io.*; import java.util.*; /** Represents a mixed Element content (PCDATA + choice/sequence). * Mixed Element can contain #PCDATA, or it can contain * #PCDATA followed by a list of pipe-separated names. * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public class DTDMixed extends DTDContainer { public DTDMixed() { } /** Writes out a declaration for mixed content */ public void write(PrintWriter out) throws IOException { out.print("("); Enumeration e = getItemsVec().elements(); boolean isFirst = true; while (e.hasMoreElements()) { if (!isFirst) out.print(" | "); isFirst = false; DTDItem item = (DTDItem) e.nextElement(); item.write(out); } out.print(")"); cardinal.write(out); } public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof DTDMixed)) return false; return super.equals(ob); } } stax-1.2.0.orig/src/com/wutka/dtd/DTDSystem.java0000644000175000017500000000136210444554664021342 0ustar twernertwernerpackage com.wutka.dtd; import java.io.*; /** Represents an external System ID in an entity declaration * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public class DTDSystem extends DTDExternalID { public DTDSystem() { } /** Writes out a declaration for this SYSTEM ID */ public void write(PrintWriter out) { if (system != null) { out.print("SYSTEM \""); out.print(system); out.print("\""); } } public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof DTDSystem)) return false; return super.equals(ob); } } stax-1.2.0.orig/src/com/wutka/dtd/DTD.java0000644000175000017500000000573710444554664020147 0ustar twernertwernerpackage com.wutka.dtd; import java.util.*; import java.io.*; /** Represents a parsed Document Type Definition * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public class DTD implements DTDOutput { /** Contains all the elements defined in the DTD */ public Hashtable elements; /** Contains all the entities defined in the DTD */ public Hashtable entities; /** Contains all the notations defined in the DTD */ public Hashtable notations; /** Contains parsed DTD's for any external entity DTD declarations */ public Hashtable externalDTDs; /** Contains all the items defined in the DTD in their original order */ public Vector items; /** Contains the element that is most likely the root element or null if the root element can't be determined. */ public DTDElement rootElement; /** Creates a new DTD */ public DTD() { elements = new Hashtable(); entities = new Hashtable(); notations = new Hashtable(); externalDTDs = new Hashtable(); items = new Vector(); } /** Writes the DTD to an output writer in standard DTD format (the format * the parser normally reads). * @param outWriter The writer where the DTD will be written */ public void write(PrintWriter outWriter) throws IOException { Enumeration e = items.elements(); while (e.hasMoreElements()) { DTDOutput item = (DTDOutput) e.nextElement(); item.write(outWriter); } } /** Returns true if this object is equal to another */ public boolean equals(Object ob) { if (this == ob) return true; if (!(ob instanceof DTD)) return false; DTD otherDTD = (DTD) ob; return items.equals(otherDTD.items); } /** Stores an array of items in the items array */ public void setItems(Object[] newItems) { items = new Vector(newItems.length); for (int i=0; i < newItems.length; i++) { items.addElement(newItems[i]); } } /** Returns the items as an array */ public Object[] getItems() { return items.toArray(); } /** Stores an item in the items array */ public void setItem(Object item, int i) { items.setElementAt(item, i); } /** Retrieves an item from the items array */ public Object getItem(int i) { return items.elementAt(i); } /** Retrieves a list of items of a particular type */ public Vector getItemsByType(Class itemType) { Vector results = new Vector(); Enumeration e = items.elements(); while (e.hasMoreElements()) { Object ob = e.nextElement(); if (itemType.isAssignableFrom(ob.getClass())) { results.addElement(ob); } } return results; } } stax-1.2.0.orig/src/com/wutka/dtd/TokenType.java0000644000175000017500000000116510444554664021445 0ustar twernertwernerpackage com.wutka.dtd; /** Enumerated value representing the type of a token * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:24 $ by $Author: aslom $ */ class TokenType { public int value; public String name; public TokenType(int aValue, String aName) { value = aValue; name = aName; } public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof TokenType)) return false; TokenType other = (TokenType) o; if (other.value == value) return true; return false; } public int hashCode() { return name.hashCode(); } } stax-1.2.0.orig/src/com/wutka/dtd/DTDAny.java0000644000175000017500000000122110444554664020577 0ustar twernertwernerpackage com.wutka.dtd; import java.io.*; /** Represents the ANY keyword in an Element's content spec * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public class DTDAny extends DTDItem { public DTDAny() { } /** Writes "ANY" to a print writer */ public void write(PrintWriter out) throws IOException { out.print("ANY"); cardinal.write(out); } public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof DTDAny)) return false; return super.equals(ob); } } stax-1.2.0.orig/src/com/wutka/dtd/DTDExternalID.java0000644000175000017500000000215610444554664022057 0ustar twernertwernerpackage com.wutka.dtd; import java.io.*; /** Represents an external ID in an entity declaration * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public abstract class DTDExternalID implements DTDOutput { public String system; public DTDExternalID() { } /** Writes out a declaration for this external ID */ public abstract void write(PrintWriter out) throws IOException; public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof DTDExternalID)) return false; DTDExternalID other = (DTDExternalID) ob; if (system == null) { if (other.system != null) return false; } else { if (!system.equals(other.system)) return false; } return true; } /** Sets the system ID */ public void setSystem(String aSystem) { system = aSystem; } /** Retrieves the system ID */ public String getSystem() { return system; } } stax-1.2.0.orig/src/com/wutka/dtd/DTDSequence.java0000644000175000017500000000211410444554664021622 0ustar twernertwernerpackage com.wutka.dtd; import java.io.*; import java.util.*; /** Represents a sequence in an element's content. * A sequence is declared in the DTD as (value1,value2,value3,etc.) * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public class DTDSequence extends DTDContainer { public DTDSequence() { } /** Writes out a declaration for this sequence */ public void write(PrintWriter out) throws IOException { out.print("("); Enumeration e = getItemsVec().elements(); boolean isFirst = true; while (e.hasMoreElements()) { if (!isFirst) out.print(","); isFirst = false; DTDItem item = (DTDItem) e.nextElement(); item.write(out); } out.print(")"); cardinal.write(out); } public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof DTDSequence)) return false; return super.equals(ob); } } stax-1.2.0.orig/src/com/wutka/dtd/DTDParser.java0000644000175000017500000007247710444554664021331 0ustar twernertwernerpackage com.wutka.dtd; import java.util.*; import java.io.*; import java.net.*; /** Parses a DTD file and returns a DTD object * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public class DTDParser implements EntityExpansion { protected Scanner scanner; protected DTD dtd; protected Object defaultLocation; /** Creates a parser that will read from the specified Reader object */ public DTDParser(Reader in) { scanner = new Scanner(in, false, this); dtd = new DTD(); } /** Creates a parser that will read from the specified Reader object * @param in The input stream to read * @param trace True if the parser should print out tokens as it reads them * (used for debugging the parser) */ public DTDParser(Reader in, boolean trace) { scanner = new Scanner(in, trace, this); dtd = new DTD(); } /** Creates a parser that will read from the specified File object */ public DTDParser(File in) throws IOException { defaultLocation = in.getParentFile(); scanner = new Scanner(new BufferedReader(new FileReader(in)), false, this); dtd = new DTD(); } /** Creates a parser that will read from the specified File object * @param in The file to read * @param trace True if the parser should print out tokens as it reads them * (used for debugging the parser) */ public DTDParser(File in, boolean trace) throws IOException { defaultLocation = in.getParentFile(); scanner = new Scanner(new BufferedReader(new FileReader(in)), trace, this); dtd = new DTD(); } /** Creates a parser that will read from the specified URL object */ public DTDParser(URL in) throws IOException { //LAM: we need to set the defaultLocation to the directory where //the dtd is found so that we don't run into problems parsing any //relative external files referenced by the dtd. String file = in.getFile(); defaultLocation = new URL(in.getProtocol(), in.getHost(), in.getPort(), file.substring(0, file.lastIndexOf('/') + 1)); scanner = new Scanner(new BufferedReader( new InputStreamReader(in.openStream())), false, this); dtd = new DTD(); } /** Creates a parser that will read from the specified URL object * @param in The URL to read * @param trace True if the parser should print out tokens as it reads them * (used for debugging the parser) */ public DTDParser(URL in, boolean trace) throws IOException { //LAM: we need to set the defaultLocation to the directory where //the dtd is found so that we don't run into problems parsing any //relative external files referenced by the dtd. String file = in.getFile(); defaultLocation = new URL(in.getProtocol(), in.getHost(), in.getPort(), file.substring(0, file.lastIndexOf('/') + 1)); scanner = new Scanner(new BufferedReader( new InputStreamReader(in.openStream())), trace, this); dtd = new DTD(); } /** Parses the DTD file and returns a DTD object describing the DTD. This invocation of parse does not try to guess the root element (for efficiency reasons) */ public DTD parse() throws IOException { return parse(false); } /** Parses the DTD file and returns a DTD object describing the DTD. * @param guessRootElement If true, tells the parser to try to guess the root element of the document by process of elimination */ public DTD parse(boolean guessRootElement) throws IOException { Token token; for (;;) { token = scanner.peek(); if (token.type == Scanner.EOF) break; parseTopLevelElement(); } if (guessRootElement) { Hashtable roots = new Hashtable(); Enumeration e = dtd.elements.elements(); while (e.hasMoreElements()) { DTDElement element = (DTDElement) e.nextElement(); roots.put(element.name, element); } e = dtd.elements.elements(); while (e.hasMoreElements()) { DTDElement element = (DTDElement) e.nextElement(); if (!(element.content instanceof DTDContainer)) continue; Enumeration items = ((DTDContainer) element.content). getItemsVec(). elements(); while (items.hasMoreElements()) { removeElements(roots, dtd, (DTDItem) items.nextElement()); } } if (roots.size() == 1) { e = roots.elements(); dtd.rootElement = (DTDElement) e.nextElement(); } else { dtd.rootElement = null; } } else { dtd.rootElement = null; } return dtd; } protected void removeElements(Hashtable h, DTD dtd, DTDItem item) { if (item instanceof DTDName) { h.remove(((DTDName) item).value); } else if (item instanceof DTDContainer) { Enumeration e = ((DTDContainer) item).getItemsVec().elements(); while (e.hasMoreElements()) { removeElements(h, dtd, (DTDItem) e.nextElement()); } } } protected void parseTopLevelElement() throws IOException { Token token = scanner.get(); // Is even valid in a DTD? I'll ignore it just in case it's there if (token.type == Scanner.LTQUES) { StringBuffer textBuffer = new StringBuffer(); for (;;) { String text = scanner.getUntil('?'); textBuffer.append(text); token = scanner.peek(); if (token.type == Scanner.GT) { scanner.get(); break; } textBuffer.append('?'); } DTDProcessingInstruction instruct = new DTDProcessingInstruction(textBuffer.toString()); dtd.items.addElement(instruct); return; } else if (token.type == Scanner.CONDITIONAL) { token = expect(Scanner.IDENTIFIER); if (token.value.equals("IGNORE")) { scanner.skipConditional(); } else { if (token.value.equals("INCLUDE")) { scanner.skipUntil('['); } else { throw new DTDParseException(scanner.getUriId(), "Invalid token in conditional: "+token.value, scanner.getLineNumber(), scanner.getColumn()); } } } else if (token.type == Scanner.ENDCONDITIONAL) { // Don't need to do anything for this token } else if (token.type == Scanner.COMMENT) { dtd.items.addElement( new DTDComment(token.value)); } else if (token.type == Scanner.LTBANG) { token = expect(Scanner.IDENTIFIER); if (token.value.equals("ELEMENT")) { parseElement(); } else if (token.value.equals("ATTLIST")) { parseAttlist(); } else if (token.value.equals("ENTITY")) { parseEntity(); } else if (token.value.equals("NOTATION")) { parseNotation(); } else { skipUntil(Scanner.GT); } } else { // MAW Version 1.17 // Previously, the parser would skip over unexpected tokens at the // upper level. Some invalid DTDs would still show up as valid. throw new DTDParseException(scanner.getUriId(), "Unexpected token: "+ token.type.name+"("+token.value+")", scanner.getLineNumber(), scanner.getColumn()); } } protected void skipUntil(TokenType stopToken) throws IOException { Token token = scanner.get(); while (token.type != stopToken) { token = scanner.get(); } } protected Token expect(TokenType expected) throws IOException { Token token = scanner.get(); if (token.type != expected) { if (token.value == null) { throw new DTDParseException(scanner.getUriId(), "Expected "+expected.name+" instead of "+token.type.name, scanner.getLineNumber(), scanner.getColumn()); } else { throw new DTDParseException(scanner.getUriId(), "Expected "+expected.name+ " instead of "+ token.type.name+"("+token.value+")", scanner.getLineNumber(), scanner.getColumn()); } } return token; } protected void parseElement() throws IOException { Token name = expect(Scanner.IDENTIFIER); DTDElement element = (DTDElement) dtd.elements.get(name.value); if (element == null) { element = new DTDElement(name.value); dtd.elements.put(element.name, element); } else if (element.content != null) { // 070501 MAW: Since the ATTLIST tag can also cause an element to be created, // only throw this exception if the element has content defined, which // won't happen when you just create an ATTLIST. Thanks to // Jags Krishnamurthy of Object Edge for pointing out this problem - // originally the parser would let you define an element more than once. throw new DTDParseException(scanner.getUriId(), "Found second definition of element: "+name.value, scanner.getLineNumber(), scanner.getColumn()); } dtd.items.addElement(element); parseContentSpec(scanner, element); expect(Scanner.GT); } protected void parseContentSpec(Scanner scanner, DTDElement element) throws IOException { Token token = scanner.get(); if (token.type == Scanner.IDENTIFIER) { if (token.value.equals("EMPTY")) { element.content = new DTDEmpty(); } else if (token.value.equals("ANY")) { element.content = new DTDAny(); } else { throw new DTDParseException(scanner.getUriId(), "Invalid token in entity content spec "+ token.value, scanner.getLineNumber(), scanner.getColumn()); } } else if (token.type == Scanner.LPAREN) { token = scanner.peek(); if (token.type == Scanner.IDENTIFIER) { if (token.value.equals("#PCDATA")) { parseMixed(element); } else { parseChildren(element); } } else if (token.type == Scanner.LPAREN) { parseChildren(element); } } } protected void parseMixed(DTDElement element) throws IOException { // MAW Version 1.19 // Keep track of whether the mixed is #PCDATA only // Don't allow * after (#PCDATA), but allow after // (#PCDATA|foo|bar|baz)* boolean isPcdataOnly = true; DTDMixed mixed = new DTDMixed(); mixed.add(new DTDPCData()); scanner.get(); element.content = mixed; for (;;) { Token token = scanner.get(); if (token.type == Scanner.RPAREN) { token = scanner.peek(); if (token.type == Scanner.ASTERISK) { scanner.get(); mixed.cardinal = DTDCardinal.ZEROMANY; } else { if (!isPcdataOnly) { throw new DTDParseException(scanner.getUriId(), "Invalid token in Mixed content type, '*' required after (#PCDATA|xx ...): "+ token.type.name, scanner.getLineNumber(), scanner.getColumn()); } mixed.cardinal = DTDCardinal.NONE; } return; } else if (token.type == Scanner.PIPE) { token = scanner.get(); mixed.add(new DTDName(token.value)); // MAW Ver. 1.19 isPcdataOnly = false; } else { throw new DTDParseException(scanner.getUriId(), "Invalid token in Mixed content type: "+ token.type.name, scanner.getLineNumber(), scanner.getColumn()); } } } protected void parseChildren(DTDElement element) throws IOException { DTDContainer choiceSeq = parseChoiceSequence(); Token token = scanner.peek(); choiceSeq.cardinal = parseCardinality(); if (token.type == Scanner.QUES) { choiceSeq.cardinal = DTDCardinal.OPTIONAL; } else if (token.type == Scanner.ASTERISK) { choiceSeq.cardinal = DTDCardinal.ZEROMANY; } else if (token.type == Scanner.PLUS) { choiceSeq.cardinal = DTDCardinal.ONEMANY; } else { choiceSeq.cardinal = DTDCardinal.NONE; } element.content = choiceSeq; } protected DTDContainer parseChoiceSequence() throws IOException { TokenType separator = null; DTDContainer cs = null; for (;;) { DTDItem item = parseCP(); Token token = scanner.get(); if ((token.type == Scanner.PIPE) || (token.type == Scanner.COMMA)) { if ((separator != null) && (separator != token.type)) { throw new DTDParseException(scanner.getUriId(), "Can't mix separators in a choice/sequence", scanner.getLineNumber(), scanner.getColumn()); } separator = token.type; if (cs == null) { if (token.type == Scanner.PIPE) { cs = new DTDChoice(); } else { cs = new DTDSequence(); } } cs.add(item); } else if (token.type == Scanner.RPAREN) { if (cs == null) { cs = new DTDSequence(); } cs.add(item); return cs; } else { throw new DTDParseException(scanner.getUriId(), "Found invalid token in sequence: "+ token.type.name, scanner.getLineNumber(), scanner.getColumn()); } } } protected DTDItem parseCP() throws IOException { Token token = scanner.get(); DTDItem item = null; if (token.type == Scanner.IDENTIFIER) { item = new DTDName(token.value); } else if (token.type == Scanner.LPAREN) { item = parseChoiceSequence(); } else { throw new DTDParseException(scanner.getUriId(), "Found invalid token in sequence: "+ token.type.name, scanner.getLineNumber(), scanner.getColumn()); } item.cardinal = parseCardinality(); return item; } protected DTDCardinal parseCardinality() throws IOException { Token token = scanner.peek(); if (token.type == Scanner.QUES) { scanner.get(); return DTDCardinal.OPTIONAL; } else if (token.type == Scanner.ASTERISK) { scanner.get(); return DTDCardinal.ZEROMANY; } else if (token.type == Scanner.PLUS) { scanner.get(); return DTDCardinal.ONEMANY; } else { return DTDCardinal.NONE; } } protected void parseAttlist() throws IOException { Token token = expect(Scanner.IDENTIFIER); DTDElement element = (DTDElement) dtd.elements.get(token.value); DTDAttlist attlist = new DTDAttlist(token.value); dtd.items.addElement(attlist); if (element == null) { element = new DTDElement(token.value); dtd.elements.put(token.value, element); } token = scanner.peek(); while (token.type != Scanner.GT) { parseAttdef(scanner, element, attlist); token = scanner.peek(); } // MAW Version 1.17 // Prior to this version, the parser didn't actually consume the > at the // end of the ATTLIST definition. Because the parser ignored unexpected tokens // at the top level, it was ignoring the >. In parsing DOCBOOK, however, there // were two unexpected tokens, bringing this error to light. expect(Scanner.GT); } protected void parseAttdef(Scanner scanner, DTDElement element, DTDAttlist attlist) throws IOException { Token token = expect(Scanner.IDENTIFIER); DTDAttribute attr = new DTDAttribute(token.value); attlist.attributes.addElement(attr); element.attributes.put(token.value, attr); token = scanner.get(); if (token.type == Scanner.IDENTIFIER) { if (token.value.equals("NOTATION")) { attr.type = parseNotationList(); } else { attr.type = token.value; } } else if (token.type == Scanner.LPAREN) { attr.type = parseEnumeration(); } token = scanner.peek(); if (token.type == Scanner.IDENTIFIER) { scanner.get(); if (token.value.equals("#FIXED")) { attr.decl = DTDDecl.FIXED; token = scanner.get(); attr.defaultValue = token.value; } else if (token.value.equals("#REQUIRED")) { attr.decl = DTDDecl.REQUIRED; } else if (token.value.equals("#IMPLIED")) { attr.decl = DTDDecl.IMPLIED; } else { throw new DTDParseException(scanner.getUriId(), "Invalid token in attribute declaration: "+ token.value, scanner.getLineNumber(), scanner.getColumn()); } } else if (token.type == Scanner.STRING) { scanner.get(); attr.decl = DTDDecl.VALUE; attr.defaultValue = token.value; } } protected DTDNotationList parseNotationList() throws IOException { DTDNotationList notation = new DTDNotationList(); Token token = scanner.get(); if (token.type != Scanner.LPAREN) { throw new DTDParseException(scanner.getUriId(), "Invalid token in notation: "+ token.type.name, scanner.getLineNumber(), scanner.getColumn()); } for (;;) { token = scanner.get(); if (token.type != Scanner.IDENTIFIER) { throw new DTDParseException(scanner.getUriId(), "Invalid token in notation: "+ token.type.name, scanner.getLineNumber(), scanner.getColumn()); } notation.add(token.value); token = scanner.peek(); if (token.type == Scanner.RPAREN) { scanner.get(); return notation; } else if (token.type != Scanner.PIPE) { throw new DTDParseException(scanner.getUriId(), "Invalid token in notation: "+ token.type.name, scanner.getLineNumber(), scanner.getColumn()); } scanner.get(); // eat the pipe } } protected DTDEnumeration parseEnumeration() throws IOException { DTDEnumeration enumeration = new DTDEnumeration(); for (;;) { Token token = scanner.get(); if ((token.type != Scanner.IDENTIFIER) && (token.type != Scanner.NMTOKEN)) { throw new DTDParseException(scanner.getUriId(), "Invalid token in enumeration: "+ token.type.name, scanner.getLineNumber(), scanner.getColumn()); } enumeration.add(token.value); token = scanner.peek(); if (token.type == Scanner.RPAREN) { scanner.get(); return enumeration; } else if (token.type != Scanner.PIPE) { throw new DTDParseException(scanner.getUriId(), "Invalid token in enumeration: "+ token.type.name, scanner.getLineNumber(), scanner.getColumn()); } scanner.get(); // eat the pipe } } protected void parseEntity() throws IOException { boolean isParsed = false; Token name = scanner.get(); if (name.type == Scanner.PERCENT) { isParsed = true; name = expect(Scanner.IDENTIFIER); } else if (name.type != Scanner.IDENTIFIER) { throw new DTDParseException(scanner.getUriId(), "Invalid entity declaration", scanner.getLineNumber(), scanner.getColumn()); } DTDEntity entity = (DTDEntity) dtd.entities.get(name.value); boolean skip = false; if (entity == null) { entity = new DTDEntity(name.value, defaultLocation); dtd.entities.put(entity.name, entity); } else { // 070501 MAW: If the entity already exists, create a dummy entity - this way // you keep the original definition. Thanks to Jags Krishnamurthy of Object // Edge for pointing out this problem and for pointing out the solution entity = new DTDEntity(name.value, defaultLocation); skip = true; } dtd.items.addElement(entity); entity.isParsed = isParsed; parseEntityDef(entity); if (entity.isParsed && (entity.value != null) && !skip) { scanner.addEntity(entity.name, entity.value); } } protected void parseEntityDef(DTDEntity entity) throws IOException { Token token = scanner.get(); if (token.type == Scanner.STRING) { // Only set the entity value if it hasn't been set yet // XML 1.0 spec says that you use the first value of // an entity, not the most recent. if (entity.value == null) { entity.value = token.value; } } else if (token.type == Scanner.IDENTIFIER) { if (token.value.equals("SYSTEM")) { DTDSystem sys = new DTDSystem(); token = expect(Scanner.STRING); sys.system = token.value; entity.externalID = sys; } else if (token.value.equals("PUBLIC")) { DTDPublic pub = new DTDPublic(); token = expect(Scanner.STRING); pub.pub = token.value; token = expect(Scanner.STRING); pub.system = token.value; entity.externalID = pub; } else { throw new DTDParseException(scanner.getUriId(), "Invalid External ID specification", scanner.getLineNumber(), scanner.getColumn()); } // ISSUE: isParsed is set to TRUE if this is a Parameter Entity // Reference (assuming this is because Parameter Entity // external references are parsed, whereas General Entity // external references are irrelevant for this product). // However, NDATA is only valid if this is // a General Entity Reference. So, "if" conditional should // be (!entity.isParsed) rather than (entity.isParsed). // //Entity Declaration // [70] EntityDecl ::= GEDecl | PEDecl // [71] GEDecl ::= '' // [72] PEDecl ::= '' // [73] EntityDef ::= EntityValue | (ExternalID NDataDecl?) // [74] PEDef ::= EntityValue | ExternalID //External Entity Declaration // [75] ExternalID ::= 'SYSTEM' S SystemLiteral // | 'PUBLIC' S PubidLiteral S SystemLiteral // [76] NDataDecl ::= S 'NDATA' S Name [ VC: Notation Declared ] if (!entity.isParsed) // CHANGE 1 { token = scanner.peek(); if (token.type == Scanner.IDENTIFIER) { if (!token.value.equals("NDATA")) { throw new DTDParseException(scanner.getUriId(), "Invalid NData declaration", scanner.getLineNumber(), scanner.getColumn()); } // CHANGE 2: Add call to scanner.get. // This gets "NDATA" IDENTIFIER. token = scanner.get(); // Get the NDATA "Name" IDENTIFIER. token = expect(Scanner.IDENTIFIER); // Save the ndata value entity.ndata = token.value; } } } else { throw new DTDParseException(scanner.getUriId(), "Invalid entity definition", scanner.getLineNumber(), scanner.getColumn()); } expect(Scanner.GT); } protected void parseNotation() throws java.io.IOException { DTDNotation notation = new DTDNotation(); Token token = expect(Scanner.IDENTIFIER); notation.name = token.value; dtd.notations.put(notation.name, notation); dtd.items.addElement(notation); token = expect(Scanner.IDENTIFIER); if (token.value.equals("SYSTEM")) { DTDSystem sys = new DTDSystem(); token = expect(Scanner.STRING); sys.system = token.value; notation.externalID = sys; } else if (token.value.equals("PUBLIC")) { DTDPublic pub = new DTDPublic(); token = expect(Scanner.STRING); pub.pub = token.value; pub.system = null; // For , you can have PUBLIC PubidLiteral without // a SystemLiteral token = scanner.peek(); if (token.type == Scanner.STRING) { token = scanner.get(); pub.system = token.value; } notation.externalID = pub; } expect(Scanner.GT); } public DTDEntity expandEntity(String name) { return (DTDEntity) dtd.entities.get(name); } } stax-1.2.0.orig/src/com/wutka/dtd/DTDComment.java0000644000175000017500000000230710444554664021460 0ustar twernertwernerpackage com.wutka.dtd; import java.io.*; /** Represents a comment in the DTD * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public class DTDComment implements DTDOutput { /** The comment text */ public String text; public DTDComment() { } public DTDComment(String theText) { text = theText; } public String toString() { return text; } public void write(PrintWriter out) throws IOException { out.print(""); } public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof DTDComment)) return false; DTDComment other = (DTDComment) ob; if ((text == null) && (other.text != null)) return false; if ((text != null) && !text.equals(other.text)) return false; return true; } /** Sets the comment text */ public void setText(String theText) { text = theText; } /** Returns the comment text */ public String getText() { return text; } } stax-1.2.0.orig/src/com/wutka/dtd/DTDPublic.java0000644000175000017500000000253410444554664021276 0ustar twernertwernerpackage com.wutka.dtd; import java.io.*; /** Represents an external Public ID in an entity declaration * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public class DTDPublic extends DTDExternalID { public String pub; public DTDPublic() { } /** Writes out a public external ID declaration */ public void write(PrintWriter out) throws IOException { out.print("PUBLIC \""); out.print(pub); out.print("\""); if (system != null) { out.print(" \""); out.print(system); out.print("\""); } } public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof DTDPublic)) return false; if (!super.equals(ob)) return false; DTDPublic other = (DTDPublic) ob; if (pub == null) { if (other.pub != null) return false; } else { if (!pub.equals(other.pub)) return false; } return true; } /** Sets the public identifier */ public void setPub(String aPub) { pub = aPub; } /** Retrieves the public identifier */ public String getPub() { return pub; } } stax-1.2.0.orig/src/com/wutka/dtd/DTDPCData.java0000644000175000017500000000124210444554664021147 0ustar twernertwernerpackage com.wutka.dtd; import java.io.*; /** Represents the #PCDATA keyword in an Element's content spec * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public class DTDPCData extends DTDItem { public DTDPCData() { } /** Writes out the #PCDATA keyword */ public void write(PrintWriter out) throws IOException { out.print("#PCDATA"); cardinal.write(out); } public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof DTDPCData)) return false; return super.equals(ob); } } stax-1.2.0.orig/src/com/wutka/dtd/EntityExpansion.java0000644000175000017500000000016310444554664022661 0ustar twernertwernerpackage com.wutka.dtd; public interface EntityExpansion { public DTDEntity expandEntity(String name); } stax-1.2.0.orig/src/com/wutka/dtd/Scanner.java0000644000175000017500000007065010444554664021121 0ustar twernertwernerpackage com.wutka.dtd; import java.io.*; import java.util.*; /** Lexical scanner for DTD's * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ class Scanner { public static final TokenType LTQUES = new TokenType(0, "LTQUES"); public static final TokenType IDENTIFIER = new TokenType(1, "IDENTIFIER"); public static final TokenType EQUAL = new TokenType(2, "EQUAL"); public static final TokenType LPAREN = new TokenType(3, "LPAREN"); public static final TokenType RPAREN = new TokenType(4, "RPAREN"); public static final TokenType COMMA = new TokenType(5, "COMMA"); public static final TokenType STRING = new TokenType(6, "STRING"); public static final TokenType QUESGT = new TokenType(7, "QUESGT"); public static final TokenType LTBANG = new TokenType(8, "LTBANG"); public static final TokenType GT = new TokenType(9, "GT"); public static final TokenType PIPE = new TokenType(10, "PIPE"); public static final TokenType QUES = new TokenType(11, "QUES"); public static final TokenType PLUS = new TokenType(12, "PLUS"); public static final TokenType ASTERISK = new TokenType(13, "ASTERISK"); public static final TokenType LT = new TokenType(14, "LT"); public static final TokenType EOF = new TokenType(15, "EOF"); public static final TokenType COMMENT = new TokenType(16, "COMMENT"); public static final TokenType PERCENT = new TokenType(17, "PERCENT"); public static final TokenType CONDITIONAL = new TokenType(18, "CONDITIONAL"); public static final TokenType ENDCONDITIONAL = new TokenType(19, "ENDCONDITIONAL"); public static final TokenType NMTOKEN = new TokenType(20, "NMTOKEN"); protected class StreamInfo { String id; Reader in; int lineNumber = 1; int column = 1; StreamInfo(String id, Reader in) { this.id = id; this.in = in; } }; protected StreamInfo in; protected Stack inputStreams; protected Token nextToken; protected int nextChar; protected boolean atEOF; protected boolean trace; protected char[] expandBuffer; protected int expandPos; protected Hashtable entityExpansion; protected EntityExpansion expander; public Scanner(Reader inReader, EntityExpansion anExpander) { this(inReader, false, anExpander); } public Scanner(Reader inReader, boolean doTrace, EntityExpansion anExpander) { in = new StreamInfo("", inReader); atEOF = false; trace = doTrace; expandBuffer = null; entityExpansion = new Hashtable(); expander = anExpander; } public Token peek() throws IOException { if (nextToken == null) { nextToken = readNextToken(); } return nextToken; } public Token get() throws IOException { if (nextToken == null) { nextToken = readNextToken(); } Token retval = nextToken; nextToken = null; return retval; } protected int readNextChar() throws IOException { int ch = in.in.read(); if (ch < 0) { if ((inputStreams != null) && (!inputStreams.empty())) { in.in.close(); in = (StreamInfo) inputStreams.pop(); return readNextChar(); } } return ch; } protected int peekChar() throws IOException { if (expandBuffer != null) { return (int) expandBuffer[expandPos]; } if (nextChar == 0) { nextChar = readNextChar(); in.column++; if (nextChar == '\n') { in.lineNumber++; in.column=1; } } return nextChar; } protected int read() throws IOException { if (expandBuffer != null) { int expNextChar = expandBuffer[expandPos++]; if (expandPos >= expandBuffer.length) { expandPos = -1; expandBuffer = null; } if (trace) { System.out.print((char) expNextChar); } return expNextChar; } if (nextChar == 0) { peekChar(); } int retval = nextChar; nextChar = 0; if (trace) { System.out.print((char) retval); } return retval; } public String getUntil(char stopChar) throws IOException { StringBuffer out = new StringBuffer(); int ch; while ((ch = read()) >= 0) { if (ch == stopChar) { return out.toString(); } out.append((char) ch); } return out.toString(); } public void skipUntil(char stopChar) throws IOException { int ch; while ((ch = read()) >= 0) { if (ch == stopChar) { return; } } return; } protected Token readNextToken() throws IOException { for (;;) { int ch = read(); if (ch == '<') { ch = peekChar(); if (ch == '!') { read(); if (peekChar() == '[') { read(); return new Token(CONDITIONAL); } if (peekChar() != '-') { return new Token(LTBANG); } else { read(); if (peekChar() != '-') { throw new DTDParseException(getUriId(), "Invalid character sequence ') { throw new DTDParseException(getUriId(), "Invalid character sequence --"+ read(), getLineNumber(), getColumn()); } read(); return new Token(COMMENT, buff.toString()); } else { buff.append('-'); } } } } } else if (ch == '?') { read(); return new Token(LTQUES); } else { return new Token(LT); } } else if (ch == '?') { // Need to treat ?> as two separate tokens because // needs the ? as a QUES, not QUESGT /* ch = peekChar(); if (ch == '>') { read(); return new Token(QUESGT); } else { return new Token(QUES); }*/ return new Token(QUES); } else if ((ch == '"') || (ch == '\'')) { int quoteChar = ch; StringBuffer buff = new StringBuffer(); while (peekChar() != quoteChar) { ch = read(); if (ch == '\\') { buff.append((char) read()); } else if (ch < 0) { break; // IF EOF before getting end quote } else { buff.append((char) ch); } } read(); return new Token(STRING, buff.toString()); } else if (ch == '(') { return new Token(LPAREN); } else if (ch == ')') { return new Token(RPAREN); } else if (ch == '|') { return new Token(PIPE); } else if (ch == '>') { return new Token(GT); } else if (ch == '=') { return new Token(EQUAL); } else if (ch == '*') { return new Token(ASTERISK); } else if (ch == ']') { if (read() != ']') { throw new DTDParseException(getUriId(), "Illegal character in input stream: "+ch, getLineNumber(), getColumn()); } if (read() != '>') { throw new DTDParseException(getUriId(), "Illegal character in input stream: "+ch, getLineNumber(), getColumn()); } return new Token(ENDCONDITIONAL); } else if (ch == '#') { StringBuffer buff = new StringBuffer(); buff.append((char) ch); if (isIdentifierChar((char) peekChar())) { buff.append((char) read()); while (isNameChar((char) peekChar())) { buff.append((char) read()); } } return new Token(IDENTIFIER, buff.toString()); } else if ((ch == '&') || (ch == '%')) { if ((ch == '%') && Character.isWhitespace((char)peekChar())) { return new Token(PERCENT); } boolean peRef = (ch == '%'); StringBuffer buff = new StringBuffer(); buff.append((char) ch); if (isIdentifierChar((char) peekChar())) { buff.append((char) read()); while (isNameChar((char) peekChar())) { buff.append((char) read()); } } if (read() != ';') { throw new DTDParseException(getUriId(), "Expected ';' after reference "+ buff.toString()+", found '"+ch+"'", getLineNumber(), getColumn()); } buff.append(';'); if (peRef) { if (expandEntity(buff.toString())) { continue; } else { // MAW: Added version 1.17 // If the entity can't be expanded, don't return it, skip it continue; } } return new Token(IDENTIFIER, buff.toString()); } else if (ch == '+') { return new Token(PLUS); } else if (ch == ',') { return new Token(COMMA); } else if (isIdentifierChar((char) ch)) { StringBuffer buff = new StringBuffer(); buff.append((char) ch); while (isNameChar((char) peekChar())) { buff.append((char) read()); } return new Token(IDENTIFIER, buff.toString()); } else if (isNameChar((char) ch)) { StringBuffer buff = new StringBuffer(); buff.append((char) ch); while (isNameChar((char) peekChar())) { buff.append((char) read()); } return new Token(NMTOKEN, buff.toString()); } else if (ch < 0) { if (atEOF) { throw new IOException("Read past EOF"); } atEOF = true; return new Token(EOF); } else if (Character.isWhitespace((char) ch)) { continue; } else { throw new DTDParseException(getUriId(), "Illegal character in input stream: "+ch, getLineNumber(), getColumn()); } } } public void skipConditional() throws IOException { // 070401 MAW: Fix for nested conditionals provided by Noah Fike // BEGIN CHANGE int ch = 0; int nestingDepth = 0; // Add nestingDepth parameter // Everything is ignored within an ignored section, except the // sub-section delimiters ''. These must be balanced, // but no section keyword is required: // Conditional Section //[61] conditionalSect ::=  includeSect | ignoreSect //[62] includeSect ::=  '' //[63] ignoreSect ::=  '' //[64] ignoreSectContents ::=  Ignore ('' Ignore)* //[65] Ignore ::=  Char* - (Char* ('') Char*) for (;;) { if ( ch != ']' ) { ch = read(); } if (ch == ']') { ch = read(); if (ch == ']') { ch = read(); if (ch == '>') { if ( nestingDepth == 0) { // The end of the IGNORE conditional section // has been found.  Break out of for loop. break; } else { // We are within an ignoreSectContents section. Decrement // the nesting depth to represent that this section has // been ended. nestingDepth--; } } } } // See if this is the first character of the beginning of a new section. if (ch == '<') { ch = read(); if ( ch == '!' ) { ch = read(); if ( ch == '[' ) { // The beginning of a new ignoreSectContents section // has been found.  Increment nesting depth. nestingDepth++; } } } } // END CHANGE } public String getUriId() { return(in.id); } public int getLineNumber() { return in.lineNumber; } public int getColumn() { return in.column; } public boolean isIdentifierChar(char ch) { if (isLetter(ch) || (ch == '_') || (ch == ':')) { return true; } return false; } public boolean isNameChar(char ch) { if (isLetter(ch) || isDigit(ch) || (ch == '-') || (ch == '_') || (ch == '.') || (ch == ':') || isCombiningChar(ch) || isExtender(ch)) { return true; } return false; } public boolean isLetter(char ch) { return isBaseChar(ch) || isIdeographic(ch); } public boolean isBaseChar(char ch) { for (int i=0; i < letterRanges.length; i++) { if (ch < letterRanges[i][0]) return false; if ((ch >= letterRanges[i][0]) && (ch <= letterRanges[i][1])) return true; } return false; } public boolean isIdeographic(char ch) { if (ch < 0x4e00) return false; if ((ch >= 0x4e00) && (ch <= 0x9fa5)) return true; if (ch == 0x3007) return true; if ((ch >= 0x3021) && (ch <= 0x3029)) return true; return false; } public boolean isDigit(char ch) { if ((ch >= 0x0030) && (ch <= 0x0039)) return true; if (ch < 0x0660) return false; if ((ch >= 0x0660) && (ch <= 0x0669)) return true; if (ch < 0x06f0) return false; if ((ch >= 0x06f0) && (ch <= 0x06f9)) return true; if (ch < 0x0966) return false; if ((ch >= 0x0966) && (ch <= 0x096f)) return true; if (ch < 0x09e6) return false; if ((ch >= 0x09e6) && (ch <= 0x09ef)) return true; if (ch < 0x0a66) return false; if ((ch >= 0x0a66) && (ch <= 0x0a6f)) return true; if (ch < 0x0ae6) return false; if ((ch >= 0x0ae6) && (ch <= 0x0aef)) return true; if (ch < 0x0b66) return false; if ((ch >= 0x0b66) && (ch <= 0x0b6f)) return true; if (ch < 0x0be7) return false; if ((ch >= 0x0be7) && (ch <= 0x0bef)) return true; if (ch < 0x0c66) return false; if ((ch >= 0x0c66) && (ch <= 0x0c6f)) return true; if (ch < 0x0ce6) return false; if ((ch >= 0x0ce6) && (ch <= 0x0cef)) return true; if (ch < 0x0d66) return false; if ((ch >= 0x0d66) && (ch <= 0x0d6f)) return true; if (ch < 0x0e50) return false; if ((ch >= 0x0e50) && (ch <= 0x0e59)) return true; if (ch < 0x0ed0) return false; if ((ch >= 0x0ed0) && (ch <= 0x0ed9)) return true; if (ch < 0x0f20) return false; if ((ch >= 0x0f20) && (ch <= 0x0f29)) return true; return false; } public boolean isCombiningChar(char ch) { if (ch < 0x0300) return false; if ((ch >= 0x0300) && (ch <= 0x0345)) return true; if ((ch >= 0x0360) && (ch <= 0x0361)) return true; if ((ch >= 0x0483) && (ch <= 0x0486)) return true; if ((ch >= 0x0591) && (ch <= 0x05a1)) return true; if ((ch >= 0x05a3) && (ch <= 0x05b9)) return true; if ((ch >= 0x05bb) && (ch <= 0x05bd)) return true; if (ch == 0x05bf) return true; if ((ch >= 0x05c1) && (ch <= 0x05c2)) return true; if (ch == 0x05c4) return true; if ((ch >= 0x064b) && (ch <= 0x0652)) return true; if (ch == 0x0670) return true; if ((ch >= 0x06d6) && (ch <= 0x06dc)) return true; if ((ch >= 0x06dd) && (ch <= 0x06df)) return true; if ((ch >= 0x06e0) && (ch <= 0x06e4)) return true; if ((ch >= 0x06e7) && (ch <= 0x06e8)) return true; if ((ch >= 0x06ea) && (ch <= 0x06ed)) return true; if ((ch >= 0x0901) && (ch <= 0x0903)) return true; if (ch == 0x093c) return true; if ((ch >= 0x093e) && (ch <= 0x094c)) return true; if (ch == 0x094d) return true; if ((ch >= 0x0951) && (ch <= 0x0954)) return true; if ((ch >= 0x0962) && (ch <= 0x0963)) return true; if ((ch >= 0x0981) && (ch <= 0x0983)) return true; if (ch == 0x09bc) return true; if (ch == 0x09be) return true; if (ch == 0x09bf) return true; if ((ch >= 0x09c0) && (ch <= 0x09c4)) return true; if ((ch >= 0x09c7) && (ch <= 0x09c8)) return true; if ((ch >= 0x09cb) && (ch <= 0x09cd)) return true; if (ch == 0x09d7) return true; if ((ch >= 0x09e2) && (ch <= 0x09e3)) return true; if (ch == 0x0a02) return true; if (ch == 0x0a3c) return true; if (ch == 0x0a3e) return true; if (ch == 0x0a3f) return true; if ((ch >= 0x0a40) && (ch <= 0x0a42)) return true; if ((ch >= 0x0a47) && (ch <= 0x0a48)) return true; if ((ch >= 0x0a4b) && (ch <= 0x0a4d)) return true; if ((ch >= 0x0a70) && (ch <= 0x0a71)) return true; if ((ch >= 0x0a81) && (ch <= 0x0a83)) return true; if (ch == 0x0abc) return true; if ((ch >= 0x0abe) && (ch <= 0x0ac5)) return true; if ((ch >= 0x0ac7) && (ch <= 0x0ac9)) return true; if ((ch >= 0x0acb) && (ch <= 0x0acd)) return true; if ((ch >= 0x0b01) && (ch <= 0x0b03)) return true; if (ch == 0x0b3c) return true; if ((ch >= 0x0b3e) && (ch <= 0x0b43)) return true; if ((ch >= 0x0b47) && (ch <= 0x0b48)) return true; if ((ch >= 0x0b4b) && (ch <= 0x0b4d)) return true; if ((ch >= 0x0b56) && (ch <= 0x0b57)) return true; if ((ch >= 0x0b82) && (ch <= 0x0b83)) return true; if ((ch >= 0x0bbe) && (ch <= 0x0bc2)) return true; if ((ch >= 0x0bc6) && (ch <= 0x0bc8)) return true; if ((ch >= 0x0bca) && (ch <= 0x0bcd)) return true; if (ch == 0x0bd7) return true; if ((ch >= 0x0c01) && (ch <= 0x0c03)) return true; if ((ch >= 0x0c3e) && (ch <= 0x0c44)) return true; if ((ch >= 0x0c46) && (ch <= 0x0c48)) return true; if ((ch >= 0x0c4a) && (ch <= 0x0c4d)) return true; if ((ch >= 0x0c55) && (ch <= 0x0c56)) return true; if ((ch >= 0x0c82) && (ch <= 0x0c83)) return true; if ((ch >= 0x0cbe) && (ch <= 0x0cc4)) return true; if ((ch >= 0x0cc6) && (ch <= 0x0cc8)) return true; if ((ch >= 0x0cca) && (ch <= 0x0ccd)) return true; if ((ch >= 0x0cd5) && (ch <= 0x0cd6)) return true; if ((ch >= 0x0d02) && (ch <= 0x0d03)) return true; if ((ch >= 0x0d3e) && (ch <= 0x0d43)) return true; if ((ch >= 0x0d46) && (ch <= 0x0d48)) return true; if ((ch >= 0x0d4a) && (ch <= 0x0d4d)) return true; if (ch == 0x0d57) return true; if (ch == 0x0e31) return true; if ((ch >= 0x0e34) && (ch <= 0x0e3a)) return true; if ((ch >= 0x0e47) && (ch <= 0x0e4e)) return true; if (ch == 0x0eb1) return true; if ((ch >= 0x0eb4) && (ch <= 0x0eb9)) return true; if ((ch >= 0x0ebb) && (ch <= 0x0ebc)) return true; if ((ch >= 0x0ec8) && (ch <= 0x0ecd)) return true; if ((ch >= 0x0f18) && (ch <= 0x0f19)) return true; if (ch == 0x0f35) return true; if (ch == 0x0f37) return true; if (ch == 0x0f39) return true; if (ch == 0x0f3e) return true; if (ch == 0x0f3f) return true; if ((ch >= 0x0f71) && (ch <= 0x0f84)) return true; if ((ch >= 0x0f86) && (ch <= 0x0f8b)) return true; if ((ch >= 0x0f90) && (ch <= 0x0f95)) return true; if (ch == 0x0f97) return true; if ((ch >= 0x0f99) && (ch <= 0x0fad)) return true; if ((ch >= 0x0fb1) && (ch <= 0x0fb7)) return true; if (ch == 0x0fb9) return true; if ((ch >= 0x20d0) && (ch <= 0x20dc)) return true; if (ch == 0x20e1) return true; if ((ch >= 0x302a) && (ch <= 0x302f)) return true; if (ch == 0x3099) return true; if (ch == 0x309a) return true; return false; } public boolean isExtender(char ch) { if (ch < 0x00b7) return false; if ((ch == 0x00b7) || (ch == 0x02d0) || (ch == 0x02d1) || (ch == 0x0387) || (ch == 0x0640) || (ch == 0x0e46) || ((ch >= 0x3031) && (ch <= 0x3035)) || ((ch >= 0x309d) && (ch <= 0x309e)) || ((ch >= 0x30fc) && (ch <= 0x30fe))) return true; return false; } public boolean expandEntity(String entityName) throws IOException { String entity = (String) entityExpansion.get(entityName); if (entity != null) { expand(entity.toCharArray()); return true; } entityName = entityName.substring(1, entityName.length()-1); //System.out.println("Trying to expand: "+entityName); DTDEntity realEntity = expander.expandEntity(entityName); if (realEntity != null) { //System.out.println("Expanded: "+entityName); Reader entityIn = realEntity.getReader(); if (entityIn != null) { if (inputStreams == null) { inputStreams = new Stack(); } inputStreams.push(in); in = new StreamInfo(realEntity.getExternalId(), entityIn); return true; } } return false; } public void expand(char[] expandChars) { if (expandBuffer != null) { int oldCharsLeft = expandBuffer.length - expandPos; char[] newExp = new char[oldCharsLeft + expandChars.length]; System.arraycopy(expandChars, 0, newExp, 0, expandChars.length); System.arraycopy(expandBuffer, expandPos, newExp, expandChars.length, oldCharsLeft); expandPos = 0; expandBuffer = newExp; if (expandBuffer.length == 0) { expandBuffer = null; expandPos = -1; } } else { expandBuffer = expandChars; expandPos = 0; if (expandBuffer.length == 0) { expandBuffer = null; expandPos = -1; } } } public void addEntity(String entityName, String entityValue) { entityExpansion.put("%"+entityName+";", entityValue); } public static char letterRanges[][] = { { 0x0041, 0x005A }, { 0x0061, 0x007A }, { 0x00C0, 0x00D6 }, { 0x00D8, 0x00F6 }, { 0x00F8, 0x00FF }, { 0x0100, 0x0131 }, { 0x0134, 0x013E }, { 0x0141, 0x0148 }, { 0x014A, 0x017E }, { 0x0180, 0x01C3 }, { 0x01CD, 0x01F0 }, { 0x01F4, 0x01F5 }, { 0x01FA, 0x0217 }, { 0x0250, 0x02A8 }, { 0x02BB, 0x02C1 }, { 0x0386, 0x0386 }, { 0x0388, 0x038A }, { 0x038C, 0x038C }, { 0x038E, 0x03A1 }, { 0x03A3, 0x03CE }, { 0x03D0, 0x03D6 }, { 0x03DA, 0x03DA }, { 0x03DC, 0x03DC }, { 0x03DE, 0x03DE }, { 0x03E0, 0x03E0 }, { 0x03E2, 0x03F3 }, { 0x0401, 0x040C }, { 0x040E, 0x044F }, { 0x0451, 0x045C }, { 0x045E, 0x0481 }, { 0x0490, 0x04C4 }, { 0x04C7, 0x04C8 }, { 0x04CB, 0x04CC }, { 0x04D0, 0x04EB }, { 0x04EE, 0x04F5 }, { 0x04F8, 0x04F9 }, { 0x0531, 0x0556 }, { 0x0559, 0x0559 }, { 0x0561, 0x0586 }, { 0x05D0, 0x05EA }, { 0x05F0, 0x05F2 }, { 0x0621, 0x063A }, { 0x0641, 0x064A }, { 0x0671, 0x06B7 }, { 0x06BA, 0x06BE }, { 0x06C0, 0x06CE }, { 0x06D0, 0x06D3 }, { 0x06D5, 0x06D5 }, { 0x06E5, 0x06E6 }, { 0x0905, 0x0939 }, { 0x093D, 0x093D }, { 0x0958, 0x0961 }, { 0x0985, 0x098C }, { 0x098F, 0x0990 }, { 0x0993, 0x09A8 }, { 0x09AA, 0x09B0 }, { 0x09B2, 0x09B2 }, { 0x09B6, 0x09B9 }, { 0x09DC, 0x09DD }, { 0x09DF, 0x09E1 }, { 0x09F0, 0x09F1 }, { 0x0A05, 0x0A0A }, { 0x0A0F, 0x0A10 }, { 0x0A13, 0x0A28 }, { 0x0A2A, 0x0A30 }, { 0x0A32, 0x0A33 }, { 0x0A35, 0x0A36 }, { 0x0A38, 0x0A39 }, { 0x0A59, 0x0A5C }, { 0x0A5E, 0x0A5E }, { 0x0A72, 0x0A74 }, { 0x0A85, 0x0A8B }, { 0x0A8D, 0x0A8D }, { 0x0A8F, 0x0A91 }, { 0x0A93, 0x0AA8 }, { 0x0AAA, 0x0AB0 }, { 0x0AB2, 0x0AB3 }, { 0x0AB5, 0x0AB9 }, { 0x0ABD, 0x0ABD }, { 0x0AE0, 0x0AE0 }, { 0x0B05, 0x0B0C }, { 0x0B0F, 0x0B10 }, { 0x0B13, 0x0B28 }, { 0x0B2A, 0x0B30 }, { 0x0B32, 0x0B33 }, { 0x0B36, 0x0B39 }, { 0x0B3D, 0x0B3D }, { 0x0B5C, 0x0B5D }, { 0x0B5F, 0x0B61 }, { 0x0B85, 0x0B8A }, { 0x0B8E, 0x0B90 }, { 0x0B92, 0x0B95 }, { 0x0B99, 0x0B9A }, { 0x0B9C, 0x0B9C }, { 0x0B9E, 0x0B9F }, { 0x0BA3, 0x0BA4 }, { 0x0BA8, 0x0BAA }, { 0x0BAE, 0x0BB5 }, { 0x0BB7, 0x0BB9 }, { 0x0C05, 0x0C0C }, { 0x0C0E, 0x0C10 }, { 0x0C12, 0x0C28 }, { 0x0C2A, 0x0C33 }, { 0x0C35, 0x0C39 }, { 0x0C60, 0x0C61 }, { 0x0C85, 0x0C8C }, { 0x0C8E, 0x0C90 }, { 0x0C92, 0x0CA8 }, { 0x0CAA, 0x0CB3 }, { 0x0CB5, 0x0CB9 }, { 0x0CDE, 0x0CDE }, { 0x0CE0, 0x0CE1 }, { 0x0D05, 0x0D0C }, { 0x0D0E, 0x0D10 }, { 0x0D12, 0x0D28 }, { 0x0D2A, 0x0D39 }, { 0x0D60, 0x0D61 }, { 0x0E01, 0x0E2E }, { 0x0E30, 0x0E30 }, { 0x0E32, 0x0E33 }, { 0x0E40, 0x0E45 }, { 0x0E81, 0x0E82 }, { 0x0E84, 0x0E84 }, { 0x0E87, 0x0E88 }, { 0x0E8A, 0x0E8A }, { 0x0E8D, 0x0E8D }, { 0x0E94, 0x0E97 }, { 0x0E99, 0x0E9F }, { 0x0EA1, 0x0EA3 }, { 0x0EA5, 0x0EA5 }, { 0x0EA7, 0x0EA7 }, { 0x0EAA, 0x0EAB }, { 0x0EAD, 0x0EAE }, { 0x0EB0, 0x0EB0 }, { 0x0EB2, 0x0EB3 }, { 0x0EBD, 0x0EBD }, { 0x0EC0, 0x0EC4 }, { 0x0F40, 0x0F47 }, { 0x0F49, 0x0F69 }, { 0x10A0, 0x10C5 }, { 0x10D0, 0x10F6 }, { 0x1100, 0x1100 }, { 0x1102, 0x1103 }, { 0x1105, 0x1107 }, { 0x1109, 0x1109 }, { 0x110B, 0x110C }, { 0x110E, 0x1112 }, { 0x113C, 0x113C }, { 0x113E, 0x113E }, { 0x1140, 0x1140 }, { 0x114C, 0x114C }, { 0x114E, 0x114E }, { 0x1150, 0x1150 }, { 0x1154, 0x1155 }, { 0x1159, 0x1159 }, { 0x115F, 0x1161 }, { 0x1163, 0x1163 }, { 0x1165, 0x1165 }, { 0x1167, 0x1167 }, { 0x1169, 0x1169 }, { 0x116D, 0x116E }, { 0x1172, 0x1173 }, { 0x1175, 0x1175 }, { 0x119E, 0x119E }, { 0x11A8, 0x11A8 }, { 0x11AB, 0x11AB }, { 0x11AE, 0x11AF }, { 0x11B7, 0x11B8 }, { 0x11BA, 0x11BA }, { 0x11BC, 0x11C2 }, { 0x11EB, 0x11EB }, { 0x11F0, 0x11F0 }, { 0x11F9, 0x11F9 }, { 0x1E00, 0x1E9B }, { 0x1EA0, 0x1EF9 }, { 0x1F00, 0x1F15 }, { 0x1F18, 0x1F1D }, { 0x1F20, 0x1F45 }, { 0x1F48, 0x1F4D }, { 0x1F50, 0x1F57 }, { 0x1F59, 0x1F59 }, { 0x1F5B, 0x1F5B }, { 0x1F5D, 0x1F5D }, { 0x1F5F, 0x1F7D }, { 0x1F80, 0x1FB4 }, { 0x1FB6, 0x1FBC }, { 0x1FBE, 0x1FBE }, { 0x1FC2, 0x1FC4 }, { 0x1FC6, 0x1FCC }, { 0x1FD0, 0x1FD3 }, { 0x1FD6, 0x1FDB }, { 0x1FE0, 0x1FEC }, { 0x1FF2, 0x1FF4 }, { 0x1FF6, 0x1FFC }, { 0x2126, 0x2126 }, { 0x212A, 0x212B }, { 0x212E, 0x212E }, { 0x2180, 0x2182 }, { 0x3041, 0x3094 }, { 0x30A1, 0x30FA }, { 0x3105, 0x312C }, { 0xAC00, 0xD7A3 } }; } stax-1.2.0.orig/src/com/wutka/dtd/Token.java0000644000175000017500000000064010444554664020600 0ustar twernertwernerpackage com.wutka.dtd; /** Token returned by the lexical scanner * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ class Token { public TokenType type; public String value; public Token(TokenType aType) { type = aType; value = null; } public Token(TokenType aType, String aValue) { type = aType; value = aValue; } } stax-1.2.0.orig/src/com/wutka/dtd/DTDContainer.java0000644000175000017500000000422610444554664022002 0ustar twernertwernerpackage com.wutka.dtd; import java.io.*; import java.util.*; /** Represents an item that may contain other items (such as a * DTDChoice or a DTDSequence) * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public abstract class DTDContainer extends DTDItem { protected Vector items; /** Creates a new DTDContainer */ public DTDContainer() { items = new Vector(); } /** Adds an element to the container */ public void add(DTDItem item) { items.addElement(item); } /** Removes an element from the container */ public void remove(DTDItem item) { items.removeElement(item); } /** Returns the elements as a vector (not a clone!) */ public Vector getItemsVec() { return items; } /** Returns the elements as an array of items */ public DTDItem[] getItems() { DTDItem[] retval = new DTDItem[items.size()]; items.copyInto(retval); return retval; } public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof DTDContainer)) return false; if (!super.equals(ob)) return false; DTDContainer other = (DTDContainer) ob; return items.equals(other.items); } /** Stores items in the container */ public void setItem(DTDItem[] newItems) { items = new Vector(newItems.length); for (int i=0; i < newItems.length; i++) { items.addElement(newItems[i]); } } /** Retrieves the items in the container */ public DTDItem[] getItem() { DTDItem[] retval = new DTDItem[items.size()]; items.copyInto(retval); return retval; } /** Stores an item in the container */ public void setItem(DTDItem anItem, int i) { items.setElementAt(anItem, i); } /** Retrieves an item from the container */ public DTDItem getItem(int i) { return (DTDItem) items.elementAt(i); } public abstract void write(PrintWriter out) throws IOException; } stax-1.2.0.orig/src/com/wutka/dtd/DTDParseException.java0000644000175000017500000000210210444554664023000 0ustar twernertwernerpackage com.wutka.dtd; public class DTDParseException extends java.io.IOException { public String uriID = ""; public int lineNumber; public int column; public DTDParseException() { lineNumber=-1; column=-1; } public DTDParseException(String message) { super(message); lineNumber=-1; column=-1; } public DTDParseException(String message, int line, int col) { super("At line "+line+", column "+col+": "+message); lineNumber = line; column = col; } public DTDParseException(String id, String message, int line, int col) { super(((null != id && id.length() > 0) ? "URI " + id + " at " : "At ") + "line " + line + ", column " + col + ": " + message); if (null != id) uriID = id; lineNumber = line; column = col; } public String getId() { return(uriID); } public int getLineNumber() { return lineNumber; } public int getColumn() { return column; } } stax-1.2.0.orig/src/com/wutka/dtd/DTDNotation.java0000644000175000017500000000344310444554664021653 0ustar twernertwernerpackage com.wutka.dtd; import java.io.*; /** Represents a Notation defined in a DTD * * @author Mark Wutka * @version $Revision: 1.1 $ $Date: 2004/08/19 05:30:23 $ by $Author: aslom $ */ public class DTDNotation implements DTDOutput { public String name; public DTDExternalID externalID; public DTDNotation() { } public DTDNotation(String aName) { name = aName; } /** Writes out a declaration for this notation */ public void write(PrintWriter out) throws IOException { out.print(""); } public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof DTDNotation)) return false; DTDNotation other = (DTDNotation) ob; if (name == null) { if (other.name != null) return false; } else { if (!name.equals(other.name)) return false; } if (externalID == null) { if (other.externalID != null) return false; } else { if (!externalID.equals(other.externalID)) return false; } return true; } /** Sets the notation name */ public void setName(String aName) { name = aName; } /** Retrieves the notation name */ public String getName() { return name; } /** Sets the external ID */ public void setExternalID(DTDExternalID theExternalID) { externalID = theExternalID; } /** Retrieves the external ID */ public DTDExternalID getExternalID() { return externalID; } } stax-1.2.0.orig/META-INF/0000755000175000017500000000000010445570060014527 5ustar twernertwernerstax-1.2.0.orig/META-INF/MANIFEST.MF0000644000175000017500000000015210445570056016164 0ustar twernertwernerManifest-Version: 1.0 Ant-Version: Apache Ant 1.6.5 Created-By: 1.5.0_05-b05 (Sun Microsystems Inc.) stax-1.2.0.orig/ASF2.0.txt0000644000175000017500000002644610444554664015010 0ustar twernertwerner Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. stax-1.2.0.orig/build.xml0000644000175000017500000002542410444554664015232 0ustar twernertwerner