KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > nu > xom > tests > BuilderTest


1 /* Copyright 2002-2004 Elliotte Rusty Harold
2    
3    This library is free software; you can redistribute it and/or modify
4    it under the terms of version 2.1 of the GNU Lesser General Public
5    License as published by the Free Software Foundation.
6    
7    This library is distributed in the hope that it will be useful,
8    but WITHOUT ANY WARRANTY; without even the implied warranty of
9    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10    GNU Lesser General Public License for more details.
11    
12    You should have received a copy of the GNU Lesser General Public
13    License along with this library; if not, write to the
14    Free Software Foundation, Inc., 59 Temple Place, Suite 330,
15    Boston, MA 02111-1307 USA
16    
17    You can contact Elliotte Rusty Harold by sending e-mail to
18    elharo@metalab.unc.edu. Please include the word "XOM" in the
19    subject line. The XOM home page is located at http://www.xom.nu/
20 */

21
22 package nu.xom.tests;
23
24 import java.io.ByteArrayOutputStream JavaDoc;
25 import java.io.CharConversionException JavaDoc;
26 import java.io.File JavaDoc;
27 import java.io.FileNotFoundException JavaDoc;
28 import java.io.FileOutputStream JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.io.OutputStreamWriter JavaDoc;
31 import java.io.PrintStream JavaDoc;
32 import java.io.Reader JavaDoc;
33 import java.io.StringReader JavaDoc;
34 import java.io.ByteArrayInputStream JavaDoc;
35 import java.io.InputStream JavaDoc;
36 import java.io.UTFDataFormatException JavaDoc;
37 import java.io.Writer JavaDoc;
38 import java.lang.reflect.Constructor JavaDoc;
39 import java.lang.reflect.InvocationTargetException JavaDoc;
40
41 import org.xml.sax.Attributes JavaDoc;
42 import org.xml.sax.ContentHandler JavaDoc;
43 import org.xml.sax.DTDHandler JavaDoc;
44 import org.xml.sax.EntityResolver JavaDoc;
45 import org.xml.sax.ErrorHandler JavaDoc;
46 import org.xml.sax.InputSource JavaDoc;
47 import org.xml.sax.Locator JavaDoc;
48 import org.xml.sax.SAXException JavaDoc;
49 import org.xml.sax.SAXNotRecognizedException JavaDoc;
50 import org.xml.sax.SAXNotSupportedException JavaDoc;
51 import org.xml.sax.SAXParseException JavaDoc;
52 import org.xml.sax.XMLFilter JavaDoc;
53 import org.xml.sax.XMLReader JavaDoc;
54 import org.xml.sax.helpers.AttributesImpl JavaDoc;
55 import org.xml.sax.helpers.LocatorImpl JavaDoc;
56 import org.xml.sax.helpers.XMLFilterImpl JavaDoc;
57 import org.xml.sax.helpers.XMLReaderFactory JavaDoc;
58
59 import nu.xom.Attribute;
60 import nu.xom.Builder;
61 import nu.xom.Comment;
62 import nu.xom.DocType;
63 import nu.xom.Document;
64 import nu.xom.Element;
65 import nu.xom.IllegalNameException;
66 import nu.xom.NodeFactory;
67 import nu.xom.ParsingException;
68 import nu.xom.ProcessingInstruction;
69 import nu.xom.ValidityException;
70 import nu.xom.XMLException;
71
72
73 /**
74  * <p>
75  * Tests building documents from streams, strings, files,
76  * and other input sources.
77  * </p>
78  *
79  * @author Elliotte Rusty Harold
80  * @version 1.0
81  *
82  */

83 public class BuilderTest extends XOMTestCase {
84
85     
86     private File JavaDoc inputDir = new File JavaDoc("data");
87
88     // Custom parser to test what happens when parser supplies
89
// malformed data
90
private static class CustomReader implements XMLReader JavaDoc {
91         
92         private ContentHandler JavaDoc handler;
93      
94         public void parse(String JavaDoc data) throws SAXException JavaDoc {
95             handler.startDocument();
96             handler.startElement("87", "87", "87", new AttributesImpl JavaDoc());
97             handler.endElement("87", "87", "87");
98             handler.endDocument();
99         }
100
101         public boolean getFeature(String JavaDoc uri) {
102             return false;
103         }
104
105         public void setFeature(String JavaDoc uri, boolean value) {}
106         
107         public ContentHandler JavaDoc getContentHandler() {
108             return handler;
109         }
110
111         public void setContentHandler(ContentHandler JavaDoc handler) {
112             this.handler = handler;
113         }
114         
115         public DTDHandler JavaDoc getDTDHandler() {
116             return null;
117         }
118
119         public void setDTDHandler(DTDHandler JavaDoc handler) {
120         }
121
122         public EntityResolver JavaDoc getEntityResolver() {
123             return null;
124         }
125         
126         public void setEntityResolver(EntityResolver JavaDoc resolver) {}
127
128         public ErrorHandler JavaDoc getErrorHandler() {
129             return null;
130         }
131
132         public void setErrorHandler(ErrorHandler JavaDoc handler) {}
133
134         public void parse(InputSource JavaDoc arg0) throws IOException JavaDoc,
135                 SAXException JavaDoc {}
136
137         public Object JavaDoc getProperty(String JavaDoc uri) {
138             return null;
139         }
140
141         public void setProperty(String JavaDoc uri, Object JavaDoc value) {}
142         
143     }
144     
145
146     public BuilderTest(String JavaDoc name) {
147         super(name);
148     }
149     
150     
151     // This class tests error conditions, which Xerces
152
// annoyingly logs to System.err. This hides System.err
153
// before each test and restores it after each test.
154
private PrintStream JavaDoc systemErr = System.err;
155     
156     protected void setUp() {
157         System.setErr(new PrintStream JavaDoc(new ByteArrayOutputStream JavaDoc()));
158     }
159     
160     
161     protected void tearDown() {
162         System.setErr(systemErr);
163     }
164     
165
166     
167     
168     // flag to turn on and off tests based on
169
// http://nagoya.apache.org/bugzilla/show_bug.cgi?id=24124
170
private boolean xercesBroken = false;
171     
172     private String JavaDoc elementDeclaration = "<!ELEMENT root (#PCDATA)>";
173     private String JavaDoc defaultAttributeDeclaration
174       = "<!ATTLIST test name CDATA \"value\">";
175     private String JavaDoc attributeDeclaration
176       = "<!ATTLIST root anattribute CDATA #REQUIRED>";
177     private String JavaDoc attributeDeclaration2
178       = "<!ATTLIST root anotherattribute CDATA \"value\">";
179     private String JavaDoc unparsedEntityDeclaration
180       = "<!ENTITY hatch-pic SYSTEM " +
181         "\"http://www.example.com/images/cup.gif\" NDATA gif>";
182     private String JavaDoc unparsedEntityDeclarationPublic
183       = "<!ENTITY public-pic PUBLIC \"public ID\" " +
184         "\"http://www.example.com/images/cup.gif\" NDATA gif>";
185     private String JavaDoc internalEntityDeclaration
186       = "<!ENTITY Pub-Status \"" +
187         "This is a pre-release of the specification.\">";
188     private String JavaDoc externalEntityDeclarationPublic =
189       "<!ENTITY open-hatch "
190       + "PUBLIC \"-//Textuality//TEXT Standard " +
191         "open-hatch boilerplate//EN\" "
192       + "\"http://www.textuality.com/boilerplate/OpenHatch.xml\">";
193     private String JavaDoc externalEntityDeclarationSystem =
194       "<!ENTITY test SYSTEM " +
195       "\"http://www.textuality.com/boilerplate/OpenHatch.xml\">";
196     private String JavaDoc notationDeclarationSystem
197      = "<!NOTATION ISODATE SYSTEM "
198      + "\"http://www.iso.ch/cate/d15903.html\">";
199     private String JavaDoc notationDeclarationPublicAndSystem
200      = "<!NOTATION DATE PUBLIC \"DATE PUBLIC ID\" "
201      + "\"http://www.iso.ch/cate/d15903.html\">";
202     private String JavaDoc notationDeclarationPublic = "<!NOTATION gif PUBLIC "
203     + "\"-//Textuality//TEXT Standard open-hatch boilerplate//EN\">";
204
205     private String JavaDoc source = "<!DOCTYPE test [\r\n"
206      + elementDeclaration + "\n"
207      + attributeDeclaration + "\n"
208      + defaultAttributeDeclaration + "\n"
209      + attributeDeclaration2 + "\n"
210      + internalEntityDeclaration + "\n"
211      + externalEntityDeclarationPublic + "\n"
212      + externalEntityDeclarationSystem + "\n"
213      + unparsedEntityDeclaration + "\n"
214      + unparsedEntityDeclarationPublic + "\n"
215      + notationDeclarationPublic + "\n"
216      + notationDeclarationSystem + "\n"
217      + notationDeclarationPublicAndSystem + "\n"
218      + "]>\r\n"
219      + "<?xml-stylesheet HREF=\"file.css\" type=\"text/css\"?>"
220      + "<!-- test -->"
221      + "<test xmlns:xlink='http://www.w3.org/TR/1999/xlink'>Hello dear"
222      + "\r\n<em id=\"p1\" xmlns:none=\"http://www.example.com\">"
223      + "very important</em>"
224      + "<span xlink:type='simple'>here&apos;s the link</span>\r\n"
225      + "<svg:svg xmlns:svg='http://www.w3.org/TR/2000/svg'>"
226      + "<svg:text>text in a namespace</svg:text></svg:svg>\r\n"
227      + "<svg xmlns='http://www.w3.org/TR/2000/svg'><text>text in a "
228      + "namespace</text></svg></test>\r\n<!--epilog-->";
229      
230     private String JavaDoc validDoc = "<!DOCTYPE test [\r\n"
231      + "<!ELEMENT test (#PCDATA)>\n"
232      + "]>\r\n"
233      + "<?xml-stylesheet HREF=\"file.css\" type=\"text/css\"?>"
234      + "<!-- test -->"
235      + "<test>Hello dear</test>"
236      + "<!--epilog-->";
237      
238     private Builder builder = new Builder();
239     private Builder validator = new Builder(true);
240     private String JavaDoc base = "http://www.example.com/";
241
242     private String JavaDoc attributeDoc = "<!DOCTYPE test [\n"
243      + "<!ELEMENT test (#PCDATA)>\n"
244      + "<!NOTATION GIF SYSTEM \"text/gif\">\n"
245      + "<!ENTITY data SYSTEM \"http://www.example.org/cup.gif\">\n"
246      + "<!ATTLIST test notationatt NOTATION (GIF) \"GIF\">\n"
247      + "<!ATTLIST test cdataatt CDATA \"GIF\">\n"
248      + "<!ATTLIST test entityatt ENTITY \"data\">\n"
249      + "<!ATTLIST test entitiesatt ENTITIES \"data\">\n"
250      + "<!ATTLIST test nmtokenatt NMTOKEN \" 1 \">\n"
251      + "<!ATTLIST test nmtokensatt NMTOKENS \" 1 2 3 \">\n"
252      + "<!ATTLIST test idatt ID \" p1 \">\n"
253      + "<!ATTLIST test idrefatt IDREF \" p1 \">\n"
254      + "<!ATTLIST test idrefsatt IDREFS \" p1 p2 \">\n"
255      + "]>\r\n"
256      + "<test>Hello dear</test>";
257
258
259     public void testNotationAttributeType()
260       throws IOException JavaDoc, ParsingException {
261         
262         Reader JavaDoc reader = new StringReader JavaDoc(attributeDoc);
263         Document document = builder.build(reader);
264         Element root = document.getRootElement();
265         Attribute att = root.getAttribute("notationatt");
266         assertEquals(Attribute.Type.NOTATION, att.getType());
267         
268     }
269     
270     
271     public void testBuildInternalDTDSubsetWithFixedDefaultAttributeValue()
272       throws ParsingException, IOException JavaDoc {
273         
274         String JavaDoc doctype = "<!DOCTYPE xsl:stylesheet [\n"
275             + "<!ATTLIST a b CDATA #FIXED \"c\">]>";
276         String JavaDoc document = doctype + "\n<root/>";
277         Builder builder = new Builder();
278         Document doc = builder.build(document, null);
279         DocType dt = doc.getDocType();
280         String JavaDoc internalDTDSubset = dt.getInternalDTDSubset();
281         assertTrue(internalDTDSubset.indexOf("#FIXED \"c\"") > 0);
282         
283     }
284     
285     
286     public void testCDATAAttributeType()
287       throws IOException JavaDoc, ParsingException {
288         
289         Reader JavaDoc reader = new StringReader JavaDoc(attributeDoc);
290         Document document = builder.build(reader);
291         Element root = document.getRootElement();
292         Attribute att = root.getAttribute("cdataatt");
293         assertEquals(Attribute.Type.CDATA, att.getType());
294         
295     }
296     
297     
298     public void testEntityAttributeType()
299       throws IOException JavaDoc, ParsingException {
300         
301         Reader JavaDoc reader = new StringReader JavaDoc(attributeDoc);
302         Document document = builder.build(reader);
303         Element root = document.getRootElement();
304         Attribute att = root.getAttribute("entityatt");
305         assertEquals(Attribute.Type.ENTITY, att.getType());
306         
307     }
308     
309     
310     public void testEntitiesAttributeType()
311       throws IOException JavaDoc, ParsingException {
312         
313         Reader JavaDoc reader = new StringReader JavaDoc(attributeDoc);
314         Document document = builder.build(reader);
315         Element root = document.getRootElement();
316         Attribute att = root.getAttribute("entitiesatt");
317         assertEquals(Attribute.Type.ENTITIES, att.getType());
318
319     }
320     
321     
322     public void testNameTokenAttributeType()
323       throws IOException JavaDoc, ParsingException {
324         
325         Reader JavaDoc reader = new StringReader JavaDoc(attributeDoc);
326         Document document = builder.build(reader);
327         Element root = document.getRootElement();
328         Attribute att = root.getAttribute("nmtokenatt");
329         assertEquals(Attribute.Type.NMTOKEN, att.getType());
330         assertEquals("1", att.getValue());
331
332     }
333     
334     
335     // I'm specifically worried about a Xerces runtime MalformedURIException here
336
public void testIllegalSystemIDThrowsRightException() {
337         
338         String JavaDoc document = "<!DOCTYPE root SYSTEM \"This is not a URI\"><root/>";
339         try{
340             builder.build(document, null);
341         }
342         catch (Exception JavaDoc ex) {
343             assertTrue(ex instanceof ParsingException);
344         }
345             
346     }
347     
348     
349     public void testNameTokensAttributeType()
350       throws IOException JavaDoc, ParsingException {
351         
352         Reader JavaDoc reader = new StringReader JavaDoc(attributeDoc);
353         Document document = builder.build(reader);
354         Element root = document.getRootElement();
355         Attribute att = root.getAttribute("nmtokensatt");
356         assertEquals(Attribute.Type.NMTOKENS, att.getType());
357         assertEquals("1 2 3", att.getValue());
358         
359     }
360     
361     
362     // verify that XML 1.1 is not supported
363
public void testXML11() throws IOException JavaDoc {
364         
365         String JavaDoc data = "<?xml version='1.1'?><root/>";
366         try {
367             builder.build(data, "http://www.example.com");
368             fail("XML 1.1 allowed");
369         }
370         catch (ParsingException ex) {
371             assertNotNull(ex.getMessage());
372         }
373         
374     }
375     
376     
377     // verify that XML 1.2 is not supported
378
public void testXML12() throws IOException JavaDoc {
379         
380         String JavaDoc data = "<?xml version='1.2'?><root/>";
381         try {
382             builder.build(data, "http://www.example.com");
383             fail("XML 1.2 allowed");
384         }
385         catch (ParsingException ex) {
386             assertNotNull(ex.getMessage());
387         }
388         
389     }
390     
391     
392     // verify that XML 2.0 is not supported
393
public void testXML20() throws IOException JavaDoc {
394         
395         String JavaDoc data = "<?xml version='2.0'?><root/>";
396         try {
397             builder.build(data, "http://www.example.com");
398             fail("XML 2.0 allowed");
399         }
400         catch (ParsingException ex) {
401             assertNotNull(ex.getMessage());
402         }
403         
404     }
405     
406     
407     public void testIDAttributeType()
408       throws IOException JavaDoc, ParsingException {
409         
410         Reader JavaDoc reader = new StringReader JavaDoc(attributeDoc);
411         Document document = builder.build(reader);
412         Element root = document.getRootElement();
413         Attribute att = root.getAttribute("idatt");
414         assertEquals(Attribute.Type.ID, att.getType());
415         assertEquals("p1", att.getValue());
416
417     }
418     
419     
420     public void testIDREFAttributeType()
421       throws IOException JavaDoc, ParsingException {
422         
423         Reader JavaDoc reader = new StringReader JavaDoc(attributeDoc);
424         Document document = builder.build(reader);
425         Element root = document.getRootElement();
426         Attribute att = root.getAttribute("idrefatt");
427         assertEquals(Attribute.Type.IDREF, att.getType());
428         assertEquals("p1", att.getValue());
429
430     }
431     
432     
433     public void testIDREFSAttributeType()
434       throws IOException JavaDoc, ParsingException {
435         
436         Reader JavaDoc reader = new StringReader JavaDoc(attributeDoc);
437         Document document = builder.build(reader);
438         Element root = document.getRootElement();
439         Attribute att = root.getAttribute("idrefsatt");
440         assertEquals(Attribute.Type.IDREFS, att.getType());
441         assertEquals("p1 p2", att.getValue());
442         
443     }
444
445     
446     public void testBuildFromReader()
447       throws IOException JavaDoc, ParsingException {
448         
449         Reader JavaDoc reader = new StringReader JavaDoc(source);
450         Document document = builder.build(reader);
451         verify(document);
452         assertEquals("", document.getBaseURI());
453         
454     }
455     
456     
457     public void testBuildFromReaderWithBase()
458       throws IOException JavaDoc, ParsingException {
459         
460         Reader JavaDoc reader = new StringReader JavaDoc(source);
461         Document document = builder.build(reader, base);
462         verify(document);
463         assertEquals(base, document.getBaseURI());
464         
465     }
466
467  
468     private static class NoLocator extends XMLFilterImpl JavaDoc {
469
470         public NoLocator(XMLReader JavaDoc reader) {
471             super(reader);
472         }
473         
474         public void setDocumentLocator(Locator JavaDoc locator) {}
475         
476     }
477     
478     
479     public void testBuildWithoutLocator()
480       throws IOException JavaDoc, ParsingException, SAXException JavaDoc {
481         
482         XMLReader JavaDoc xerces = XMLReaderFactory.createXMLReader(
483           "org.apache.xerces.parsers.SAXParser");
484         XMLReader JavaDoc filter = new NoLocator(xerces);
485         
486         Builder builder = new Builder(filter);
487         Document document = builder.build(source, "http://www.example.org/");
488         verify(document);
489         assertEquals("http://www.example.org/", document.getBaseURI());
490         
491     }
492
493     
494     private static class WeirdAttributeTypes extends XMLFilterImpl JavaDoc {
495
496         public WeirdAttributeTypes(XMLReader JavaDoc reader) {
497             super(reader);
498         }
499         
500         public void startElement(String JavaDoc uri, String JavaDoc localName,
501           String JavaDoc qualifiedName, Attributes JavaDoc atts) throws SAXException JavaDoc {
502             
503             AttributesImpl JavaDoc newAtts = new AttributesImpl JavaDoc(atts);
504             for (int i = 0; i < newAtts.getLength(); i++) {
505                 newAtts.setType(i, "WEIRD");
506             }
507             
508             super.startElement(uri, localName, qualifiedName, newAtts);
509             
510         }
511         
512     }
513
514     
515     public void testWeirdAttributeTypes()
516       throws IOException JavaDoc, ParsingException, SAXException JavaDoc {
517         
518         XMLReader JavaDoc xerces = XMLReaderFactory.createXMLReader(
519           "org.apache.xerces.parsers.SAXParser");
520         XMLReader JavaDoc filter = new WeirdAttributeTypes(xerces);
521         
522         Builder builder = new Builder(filter);
523         Document document = builder.build(attributeDoc, "http://www.example.org/");
524         Element root = document.getRootElement();
525         assertTrue(root.getAttributeCount() > 0);
526         for (int i = 0; i < root.getAttributeCount(); i++) {
527             assertEquals(Attribute.Type.UNDECLARED, root.getAttribute(i).getType());
528         }
529         
530     }
531     
532     
533     // Here we're faking the non-standard behavior of some older parsers
534
private static class ParenthesizedEnumeratedAttributeTypes extends XMLFilterImpl JavaDoc {
535
536         public ParenthesizedEnumeratedAttributeTypes(XMLReader JavaDoc reader) {
537             super(reader);
538         }
539         
540         public void startElement(String JavaDoc uri, String JavaDoc localName,
541           String JavaDoc qualifiedName, Attributes JavaDoc atts) throws SAXException JavaDoc {
542             
543             AttributesImpl JavaDoc newAtts = new AttributesImpl JavaDoc(atts);
544             for (int i = 0; i < newAtts.getLength(); i++) {
545                 newAtts.setType(i, "(test, data, value)");
546             }
547             
548             super.startElement(uri, localName, qualifiedName, newAtts);
549             
550         }
551         
552     }
553
554     
555     public void testParenthesizedEnumeratedAttributeTypes()
556       throws IOException JavaDoc, ParsingException, SAXException JavaDoc {
557         
558         XMLReader JavaDoc xerces = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
559         XMLReader JavaDoc filter = new ParenthesizedEnumeratedAttributeTypes(xerces);
560         
561         Builder builder = new Builder(filter);
562         Document document = builder.build(attributeDoc, "http://www.example.org/");
563         Element root = document.getRootElement();
564         assertTrue(root.getAttributeCount() > 0);
565         for (int i = 0; i < root.getAttributeCount(); i++) {
566             assertEquals(Attribute.Type.ENUMERATION, root.getAttribute(i).getType());
567         }
568         
569     }
570     
571     
572     public void testBuildFromInputStreamWithBase()
573       throws IOException JavaDoc, ParsingException {
574         InputStream JavaDoc in = new ByteArrayInputStream JavaDoc(source.getBytes("UTF-8"));
575         Document document = builder.build(in, base);
576         verify(document);
577         assertEquals(base, document.getBaseURI());
578     }
579     
580     
581     public void testBuildFromInputStreamWithoutBase()
582       throws IOException JavaDoc, ParsingException {
583         InputStream JavaDoc in = new ByteArrayInputStream JavaDoc(source.getBytes("UTF-8"));
584         Document document = builder.build(in);
585         verify(document);
586         assertEquals("", document.getBaseURI());
587     }
588
589     
590     public void testBuildFromStringWithBase()
591       throws IOException JavaDoc, ParsingException {
592         Document document = builder.build(source, base);
593         verify(document);
594         assertEquals(base, document.getBaseURI());
595     }
596     
597     
598     public void testBuildFromInvalidDoc()
599       throws IOException JavaDoc, ParsingException {
600         
601         try {
602             validator.build(source, base);
603             fail("Built invalid doc");
604         }
605         catch (ValidityException ex) {
606             Document document = ex.getDocument();
607             // Can't do a full verify just yet due to bugs in Xerces
608
// verify(ex.getDocument());
609
assertTrue(document.getChild(1) instanceof ProcessingInstruction);
610             assertTrue(document.getChild(2) instanceof Comment);
611             DocType doctype = document.getDocType();
612             Element root = document.getRootElement();
613     
614             // assertEquals(1, root.getAttributeCount());
615
// assertEquals("value", root.getAttributeValue("name"));
616
assertEquals("test", root.getQualifiedName());
617             assertEquals("test", root.getLocalName());
618             assertEquals("", root.getNamespaceURI());
619             
620             assertTrue(doctype != null);
621             assertTrue(document.getChild(0) instanceof DocType);
622             assertTrue(document.getChild(4) instanceof Comment);
623             assertTrue(document.getChild(2) instanceof Comment);
624             assertEquals(" test ", document.getChild(2).getValue());
625             assertEquals("epilog", document.getChild(4).getValue());
626             assertTrue(document.getChild(1) instanceof ProcessingInstruction);
627             assertEquals("test", doctype.getRootElementName());
628             assertNull(doctype.getPublicID());
629             assertNull(doctype.getSystemID());
630             
631             String JavaDoc internalDTDSubset = doctype.getInternalDTDSubset();
632             assertTrue(
633               internalDTDSubset,
634               internalDTDSubset.indexOf(elementDeclaration) > 0
635             );
636             assertTrue(
637               internalDTDSubset,
638               internalDTDSubset.indexOf(attributeDeclaration) > 0
639             );
640             assertTrue(
641               internalDTDSubset,
642               internalDTDSubset.indexOf(attributeDeclaration2) > 0
643             );
644             assertTrue(
645               internalDTDSubset,
646               internalDTDSubset.indexOf(internalEntityDeclaration) > 0
647             );
648             assertTrue(
649               internalDTDSubset,
650               internalDTDSubset.indexOf(externalEntityDeclarationPublic) > 0
651             );
652             assertTrue(
653               internalDTDSubset,
654               internalDTDSubset.indexOf(externalEntityDeclarationSystem) > 0
655             );
656             assertTrue(
657               internalDTDSubset,
658               internalDTDSubset.indexOf(unparsedEntityDeclaration) > 0
659             );
660             assertTrue(
661               internalDTDSubset,
662               internalDTDSubset.indexOf(unparsedEntityDeclarationPublic) > 0
663             );
664             assertTrue(
665               internalDTDSubset,
666               internalDTDSubset.indexOf(notationDeclarationPublic) > 0
667             );
668             assertTrue(
669               internalDTDSubset,
670               internalDTDSubset.indexOf(notationDeclarationSystem) > 0
671             );
672             assertTrue(
673               internalDTDSubset,
674               internalDTDSubset.indexOf(notationDeclarationPublicAndSystem) > 0
675             );
676             
677         }
678         
679     }
680     
681     
682     public void testBuildFromStringWithNullBase()
683       throws IOException JavaDoc, ParsingException {
684         Document document = builder.build(source, null);
685         verify(document);
686         assertEquals("", document.getBaseURI());
687     }
688     
689     
690     private void verify(Document document) {
691         
692         assertTrue(document.getChild(1) instanceof ProcessingInstruction);
693         assertTrue(document.getChild(2) instanceof Comment);
694         DocType doctype = document.getDocType();
695         Element root = document.getRootElement();
696
697         assertEquals(1, root.getAttributeCount());
698         assertEquals("value", root.getAttributeValue("name"));
699         assertEquals("test", root.getQualifiedName());
700         assertEquals("test", root.getLocalName());
701         assertEquals("", root.getNamespaceURI());
702         
703         assertTrue(doctype != null);
704         assertTrue(document.getChild(0) instanceof DocType);
705         assertTrue(document.getChild(4) instanceof Comment);
706         assertTrue(document.getChild(2) instanceof Comment);
707         assertEquals(" test ", document.getChild(2).getValue());
708         assertEquals("epilog", document.getChild(4).getValue());
709         assertTrue(document.getChild(1) instanceof ProcessingInstruction);
710         assertEquals("test", doctype.getRootElementName());
711         assertNull(doctype.getPublicID());
712         assertNull(doctype.getSystemID());
713         
714         String JavaDoc internalDTDSubset = doctype.getInternalDTDSubset();
715         assertTrue(
716           internalDTDSubset,
717           internalDTDSubset.indexOf(elementDeclaration) > 0
718         );
719         assertTrue(
720           internalDTDSubset,
721           internalDTDSubset.indexOf(attributeDeclaration) > 0
722         );
723         assertTrue(
724           internalDTDSubset,
725           internalDTDSubset.indexOf(attributeDeclaration2) > 0
726         );
727         assertTrue(
728           internalDTDSubset,
729           internalDTDSubset.indexOf(internalEntityDeclaration) > 0
730         );
731         assertTrue(
732           internalDTDSubset,
733           internalDTDSubset.indexOf(externalEntityDeclarationPublic) > 0
734         );
735         assertTrue(
736           internalDTDSubset,
737           internalDTDSubset.indexOf(externalEntityDeclarationSystem) > 0
738         );
739         assertTrue(
740           internalDTDSubset,
741           internalDTDSubset.indexOf(unparsedEntityDeclaration) > 0
742         );
743         assertTrue(
744           internalDTDSubset,
745           internalDTDSubset.indexOf(unparsedEntityDeclarationPublic) > 0
746         );
747         assertTrue(
748           internalDTDSubset,
749           internalDTDSubset.indexOf(notationDeclarationPublic) > 0
750         );
751         assertTrue(
752           internalDTDSubset,
753           internalDTDSubset.indexOf(notationDeclarationSystem) > 0
754         );
755         assertTrue(
756           internalDTDSubset,
757           internalDTDSubset.indexOf(notationDeclarationPublicAndSystem) > 0
758         );
759                
760     }
761
762     
763     public void testValidateFromReader()
764       throws IOException JavaDoc, ParsingException {
765         
766         Reader JavaDoc reader1 = new StringReader JavaDoc(validDoc);
767         Document document1 = validator.build(reader1);
768         assertEquals("", document1.getBaseURI());
769         Reader JavaDoc reader2 = new StringReader JavaDoc(validDoc);
770         Document document2 = builder.build(reader2);
771         assertEquals(document2, document1);
772         
773     }
774
775     
776     public void testDocumentWithDefaultNamespaceOnPrefixedElement()
777       throws IOException JavaDoc, ParsingException {
778         
779         Reader JavaDoc reader = new StringReader JavaDoc("<pre:root " +
780                 "xmlns='http://www.example.org/' " +
781                 "xmlns:pre='http://www.cafeconleche.org/'/>");
782         Document document = builder.build(reader);
783         Element root = document.getRootElement();
784         assertEquals("http://www.example.org/", root.getNamespaceURI(""));
785         assertEquals("http://www.cafeconleche.org/", root.getNamespaceURI("pre"));
786         assertEquals("http://www.cafeconleche.org/", root.getNamespaceURI());
787         
788     }
789     
790     
791     public void testValidateFromReaderWithBase()
792       throws IOException JavaDoc, ParsingException {
793         
794         Reader JavaDoc reader = new StringReader JavaDoc(validDoc);
795         Document document = validator.build(reader, base);
796         assertEquals(base, document.getBaseURI());
797         Reader JavaDoc reader2 = new StringReader JavaDoc(validDoc);
798         Document document2 = builder.build(reader2);
799         assertEquals(document2, document);
800         
801     }
802     
803     
804     public void testValidateFromInputStreamWithBase()
805       throws IOException JavaDoc, ParsingException {
806         
807         InputStream JavaDoc in = new ByteArrayInputStream JavaDoc(validDoc.getBytes("UTF-8"));
808         Document document = validator.build(in, base);
809         assertEquals(base, document.getBaseURI());
810         Reader JavaDoc reader2 = new StringReader JavaDoc(validDoc);
811         Document document2 = builder.build(reader2);
812         assertEquals(document2, document);
813         
814     }
815     
816     
817     public void testValidateInSeries()
818       throws IOException JavaDoc, ParsingException {
819           
820         try {
821             Reader JavaDoc reader = new StringReader JavaDoc(source);
822             validator.build(reader);
823             fail("Allowed invalid doc");
824         }
825         catch (ValidityException success) {
826             assertNotNull(success.getMessage());
827         }
828         // now make sure validating a valid document doesn't
829
// throw an exception
830
InputStream JavaDoc in = new ByteArrayInputStream JavaDoc(validDoc.getBytes("UTF-8"));
831         validator.build(in, base);
832         
833     }
834     
835     
836     public void testValidateFromInputStreamWithoutBase()
837       throws IOException JavaDoc, ParsingException {
838         
839         InputStream JavaDoc in = new ByteArrayInputStream JavaDoc(validDoc.getBytes("UTF-8"));
840         Document document = validator.build(in);
841         assertEquals("", document.getBaseURI());
842         Reader JavaDoc reader2 = new StringReader JavaDoc(validDoc);
843         Document document2 = builder.build(reader2);
844         assertEquals(document2, document);
845         
846     }
847
848     
849     public void testValidateFromStringWithBase()
850       throws IOException JavaDoc, ParsingException {
851         
852         Document document = validator.build(validDoc, base);
853         assertEquals(base, document.getBaseURI());
854         Reader JavaDoc reader2 = new StringReader JavaDoc(validDoc);
855         Document document2 = builder.build(reader2);
856         assertEquals(document2, document);
857         
858     }
859     
860     
861     public void testValidateWithCrimson()
862       throws IOException JavaDoc, ParsingException {
863         
864         XMLReader JavaDoc crimson;
865         try {
866             crimson = XMLReaderFactory.createXMLReader(
867               "org.apache.crimson.parser.XMLReaderImpl");
868         }
869         catch (SAXException JavaDoc ex) {
870             // can't test Crimson if you can't load it
871
return;
872         }
873         Builder validator = new Builder(crimson, true);
874         Document document = validator.build(validDoc, base);
875         assertEquals(base, document.getBaseURI());
876         Reader JavaDoc reader2 = new StringReader JavaDoc(validDoc);
877         Document document2 = builder.build(reader2);
878         assertEquals(document2, document);
879         
880     }
881
882     
883     public void testEnumerationAttributeType()
884       throws IOException JavaDoc, ParsingException {
885         
886         XMLReader JavaDoc crimson;
887         try {
888             crimson = XMLReaderFactory.createXMLReader(
889               "org.apache.crimson.parser.XMLReaderImpl");
890         }
891         catch (SAXException JavaDoc ex) {
892             // can't test Crimson if you can't load it
893
return;
894         }
895         Builder builder = new Builder(crimson, false);
896         String JavaDoc doc = "<!DOCTYPE root [" +
897                 "<!ATTLIST root att (yes | no) #IMPLIED>" +
898                 "]><root att='yes'/>";
899         Document document = builder.build(doc, base);
900         Element root = document.getRootElement();
901         Attribute att = root.getAttribute(0);
902         assertEquals(Attribute.Type.ENUMERATION, att.getType());
903         
904     }
905
906     
907     public void testWarningDoesNotStopBuild()
908       throws IOException JavaDoc, ParsingException, SAXException JavaDoc {
909         
910         XMLReader JavaDoc xerces;
911         try {
912             xerces = XMLReaderFactory.createXMLReader(
913               "org.apache.xerces.parsers.SAXParser");
914         }
915         catch (SAXException JavaDoc ex) {
916             // can't test Xerces if you can't load it
917
return;
918         }
919         // This document generates a warning due to the duplicate
920
// attribute declaration
921
xerces.setFeature(
922           "http://apache.org/xml/features/validation/warn-on-duplicate-attdef",
923           true);
924         Builder builder = new Builder(xerces, true);
925         Document document = builder.build("<!DOCTYPE root [" +
926                 "<!ELEMENT root ANY>" +
927                 "<!ATTLIST root b CDATA #IMPLIED>" +
928                 "<!ATTLIST root b NMTOKEN #REQUIRED>" +
929                 "]><root b='test'/>", base);
930         // The main test is that the document is built successfully.
931
assertEquals(2, document.getChildCount());
932         assertEquals("root", document.getRootElement().getQualifiedName());
933         
934     }
935     
936     
937     private static class EntitySkipper extends XMLFilterImpl JavaDoc {
938
939         public EntitySkipper(XMLReader JavaDoc reader) {
940             super(reader);
941         }
942         
943         public void characters(char[] data, int start, int length)
944           throws SAXException JavaDoc {
945             super.skippedEntity("name");
946         }
947         
948     }
949     
950     
951     public void testSkippedEntityThrowsParsingException()
952       throws IOException JavaDoc, ParsingException, SAXException JavaDoc {
953         
954         XMLReader JavaDoc xerces = XMLReaderFactory.createXMLReader(
955           "org.apache.xerces.parsers.SAXParser");
956         XMLReader JavaDoc filter = new EntitySkipper(xerces);
957         
958         Builder builder = new Builder(filter, true);
959         try {
960             builder.build("<root>replace</root>", base);
961             fail("Allowed skipped entity");
962         }
963         catch (ParsingException success) {
964             assertNotNull(success.getMessage());
965         }
966         
967     }
968     
969     
970     public void testValidateFromStringWithNullBase()
971       throws IOException JavaDoc, ParsingException {
972         Document document = validator.build(validDoc, null);
973         assertEquals("", document.getBaseURI());
974         Reader JavaDoc reader2 = new StringReader JavaDoc(validDoc);
975         Document document2 = builder.build(reader2);
976         assertEquals(document2, document);
977     }
978
979
980     public void testCannotBuildNamespaceMalformedDocument()
981       throws IOException JavaDoc {
982         
983         try {
984             builder.build("<root:root/>", null);
985             fail("Builder allowed undeclared prefix");
986         }
987         catch (ParsingException success) {
988             assertNotNull(success.getMessage());
989         }
990         
991     }
992
993     
994     public void testInvalidDocFromReader()
995       throws IOException JavaDoc, ParsingException {
996         
997         Reader JavaDoc reader = new StringReader JavaDoc(source);
998         try {
999             validator.build(reader);
1000            fail("Allowed invalid doc");
1001        }
1002        catch (ValidityException success) {
1003            assertNotNull(success.getMessage());
1004            assertTrue(success.getErrorCount() > 0);
1005            for (int i = 0; i < success.getErrorCount(); i++) {
1006                assertNotNull(success.getValidityError(i));
1007                assertTrue(success.getLineNumber(i) >= -1);
1008                assertTrue(success.getColumnNumber(i) >= -1);
1009            }
1010            if (!xercesBroken) {
1011                Document doc = builder.build(new StringReader JavaDoc(source));
1012                this.verify(success.getDocument());
1013                assertEquals(doc, success.getDocument());
1014            }
1015        }
1016        
1017    }
1018    
1019    
1020    public void testNamespaceMalformedDocumentWithCrimson()
1021      throws IOException JavaDoc {
1022        
1023        StringReader JavaDoc reader = new StringReader JavaDoc("<root:root/>");
1024        XMLReader JavaDoc crimson;
1025        try {
1026            crimson = XMLReaderFactory.createXMLReader(
1027              "org.apache.crimson.parser.XMLReaderImpl");
1028        }
1029        catch (SAXException JavaDoc ex) {
1030           // No Crimson in classpath; therefore can't test it
1031
return;
1032        }
1033        Builder builder = new Builder(crimson);
1034        try {
1035            builder.build(reader);
1036            fail("Crimson allowed namespace malformed doc");
1037        }
1038        catch (ParsingException success) {
1039            assertNotNull(success.getMessage());
1040        }
1041        
1042    }
1043
1044    
1045    public void testValidateNamespaceMalformedInvalidDocumentWithCrimson()
1046      throws IOException JavaDoc {
1047        
1048        StringReader JavaDoc reader = new StringReader JavaDoc("<!DOCTYPE root [" +
1049                "<!ELEMENT root (a)>\n" +
1050                "<!ELEMENT a (#PCDATA)> \n" +
1051                "]>\n" +
1052                "<root><b:b /></root>");
1053        XMLReader JavaDoc crimson;
1054        try {
1055            crimson = XMLReaderFactory.createXMLReader(
1056              "org.apache.crimson.parser.XMLReaderImpl");
1057        }
1058        catch (SAXException JavaDoc ex) {
1059           // No Crimson in classpath; therefore can't test it
1060
return;
1061        }
1062        Builder builder = new Builder(crimson);
1063        try {
1064            builder.build(reader);
1065            fail("Crimson allowed namespace malformed doc");
1066        }
1067        catch (ValidityException ex) {
1068            fail("Crimson should have thrown ParsingException instead");
1069        }
1070        catch (ParsingException success) {
1071            assertNotNull(success.getMessage());
1072        }
1073        
1074    }
1075    
1076    
1077    public void testInvalidDocFromReaderWithBase()
1078      throws IOException JavaDoc, ParsingException {
1079        
1080        Reader JavaDoc reader1 = new StringReader JavaDoc(source);
1081        try {
1082            validator.build(reader1, base);
1083            fail("Allowed invalid doc");
1084        }
1085        catch (ValidityException ex) {
1086            assertNotNull(ex.getMessage());
1087            assertEquals(base, ex.getURI());
1088            assertTrue(ex.getErrorCount() > 0);
1089            for (int i = 0; i < ex.getErrorCount(); i++) {
1090                assertNotNull(ex.getValidityError(i));
1091                assertTrue(ex.getLineNumber(i) >= -1);
1092                assertTrue(ex.getColumnNumber(i) >= -1);
1093            }
1094            if (!xercesBroken) {
1095                Document doc = builder.build(new StringReader JavaDoc(source), base);
1096                this.verify(ex.getDocument());
1097                assertEquals(doc, ex.getDocument());
1098            }
1099        }
1100        
1101    }
1102 
1103    
1104    public void testInvalidDocFromInputStreamWithBase()
1105      throws IOException JavaDoc, ParsingException {
1106        
1107        InputStream JavaDoc in = new ByteArrayInputStream JavaDoc(source.getBytes("UTF-8"));
1108        try {
1109            validator.build(in, base);
1110            fail("Allowed invalid doc");
1111        }
1112        catch (ValidityException ex) {
1113            assertNotNull(ex.getMessage());
1114            assertEquals(base, ex.getURI());
1115            assertTrue(ex.getErrorCount() > 0);
1116            for (int i = 0; i < ex.getErrorCount(); i++) {
1117                assertNotNull(ex.getValidityError(i));
1118                assertTrue(ex.getLineNumber(i) >= -1);
1119                assertTrue(ex.getColumnNumber(i) >= -1);
1120            }
1121            if (!xercesBroken) {
1122                Document doc = builder.build(
1123                  new ByteArrayInputStream JavaDoc(source.getBytes("UTF-8")), base
1124                );
1125                this.verify(ex.getDocument());
1126                assertEquals(doc, ex.getDocument());
1127            }
1128        }
1129        
1130    }
1131    
1132    
1133    public void testInvalidDocFromInputStreamWithoutBase()
1134      throws IOException JavaDoc, ParsingException {
1135        
1136        InputStream JavaDoc in = new ByteArrayInputStream JavaDoc(source.getBytes("UTF-8"));
1137        try {
1138            validator.build(in);
1139            fail("Allowed invalid doc");
1140        }
1141        catch (ValidityException ex) {
1142            assertNotNull(ex.getMessage());
1143            assertTrue(ex.getErrorCount() > 0);
1144            for (int i = 0; i < ex.getErrorCount(); i++) {
1145                assertNotNull(ex.getValidityError(i));
1146                assertTrue(ex.getLineNumber(i) >= -1);
1147                assertTrue(ex.getColumnNumber(i) >= -1);
1148            }
1149            if (!xercesBroken) {
1150                Document doc = builder.build(
1151                  new ByteArrayInputStream JavaDoc(source.getBytes("UTF-8"))
1152                );
1153                this.verify(ex.getDocument());
1154                assertEquals(doc, ex.getDocument());
1155            }
1156        }
1157        
1158    }
1159
1160    
1161    public void testInvalidDocFromStringWithBase()
1162      throws IOException JavaDoc, ParsingException {
1163        
1164        try {
1165            validator.build(source, base);
1166            fail("Allowed invalid doc");
1167        }
1168        catch (ValidityException ex) {
1169            assertNotNull(ex.getMessage());
1170            assertEquals(base, ex.getURI());
1171            assertTrue(ex.getErrorCount() > 0);
1172            for (int i = 0; i < ex.getErrorCount(); i++) {
1173                assertNotNull(ex.getValidityError(i));
1174                assertTrue(ex.getLineNumber(i) >= -1);
1175                assertTrue(ex.getColumnNumber(i) >= -1);
1176            }
1177            if (!xercesBroken) {
1178                Document doc = builder.build(source, base);
1179                this.verify(ex.getDocument());
1180                assertEquals(doc, ex.getDocument());
1181            }
1182        }
1183        
1184    }
1185    
1186
1187    public void testInvalidDocWithCrimson()
1188      throws IOException JavaDoc, ParsingException {
1189        
1190        XMLReader JavaDoc crimson;
1191        try {
1192            crimson = XMLReaderFactory.createXMLReader(
1193              "org.apache.crimson.parser.XMLReaderImpl");
1194        }
1195        catch (SAXException JavaDoc ex) {
1196            // can't test Crimson if you can't load it
1197
return;
1198        }
1199        Builder validator = new Builder(crimson, true);
1200        try {
1201            validator.build(source, null);
1202            fail("Allowed invalid doc");
1203        }
1204        catch (ValidityException ex) {
1205            assertTrue(ex.getErrorCount() > 0);
1206            assertNull(ex.getURI());
1207            for (int i = 0; i < ex.getErrorCount(); i++) {
1208                assertNotNull(ex.getValidityError(i));
1209            }
1210        }
1211        
1212    }
1213
1214    
1215    public void testInvalidDocFromStringWithNullBase()
1216      throws IOException JavaDoc, ParsingException {
1217        
1218        try {
1219            validator.build(source, null);
1220            fail("Allowed invalid doc");
1221        }
1222        catch (ValidityException ex) {
1223            assertTrue(ex.getErrorCount() > 0);
1224            assertNull(ex.getURI());
1225            for (int i = 0; i < ex.getErrorCount(); i++) {
1226                assertNotNull(ex.getValidityError(i));
1227            }
1228            if (!xercesBroken) {
1229                Document doc = builder.build(source, null);
1230                this.verify(ex.getDocument());
1231                assertEquals(doc, ex.getDocument());
1232            }
1233        }
1234        
1235    }
1236    
1237    
1238    public void testJavaEncodings()
1239      throws IOException JavaDoc, ParsingException {
1240        
1241        String JavaDoc str = "<?xml version='1.0' encoding='ISO8859_1'?>" +
1242            "<root>é</root>";
1243        byte[] data = str.getBytes("8859_1");
1244        InputStream JavaDoc in = new ByteArrayInputStream JavaDoc(data);
1245        Document doc = builder.build(in);
1246        assertEquals("é", doc.getValue());
1247        
1248    }
1249
1250    
1251    // Crimson improperly converts 0x0D and 0x0A to spaces
1252
// even when the attribute type is not CDATA.
1253
// This bug explains why the canonicalizer tests fail
1254
// with Crimson
1255
public void testCrimsonCharacterReferenceBug()
1256      throws IOException JavaDoc, ParsingException {
1257        
1258        String JavaDoc data =
1259          "<!DOCTYPE test [<!ATTLIST test name ID #IMPLIED>]>"
1260          + "<test name='&#x0D;'/>";
1261        InputStream JavaDoc in = new ByteArrayInputStream JavaDoc(
1262          data.getBytes("UTF8"));
1263        Document document = builder.build(in, null);
1264        assertEquals("\r",
1265          document.getRootElement().getAttributeValue("name"));
1266        
1267    }
1268    
1269    
1270    public void testBaseRelativeResolution()
1271      throws IOException JavaDoc, ParsingException {
1272        builder.build(new File JavaDoc(inputDir, "baserelative/test.xml"));
1273    }
1274    
1275    
1276    // make sure transcoders on input are using normalization
1277
// form C when converting from other encodings
1278
public void testNFC()
1279      throws IOException JavaDoc, ParsingException {
1280        
1281        Document doc = builder.build(new File JavaDoc(inputDir, "nfctest.xml"));
1282        Element root = doc.getRootElement();
1283        String JavaDoc s = root.getValue();
1284        assertEquals(1, s.length());
1285        assertEquals(0xE9, s.charAt(0));
1286        
1287    }
1288    
1289    
1290    // This tests XOM's workaround for a bug in Crimson, Xerces,
1291
// and possibly other parsers
1292
public void testBaseRelativeResolutionRemotely()
1293      throws IOException JavaDoc, ParsingException {
1294        builder.build("http://www.cafeconleche.org");
1295    }
1296    
1297    
1298    public void testExternalEntityResolution()
1299      throws IOException JavaDoc, ParsingException {
1300        
1301        File JavaDoc input = new File JavaDoc(inputDir, "entitytest.xml");
1302        Builder builder = new Builder(false);
1303        Document doc = builder.build(input);
1304        Element root = doc.getRootElement();
1305        Element external = root.getFirstChildElement("external");
1306        assertEquals("Hello from an entity!", external.getValue());
1307        
1308    }
1309     
1310    
1311    // This test exposes a bug in Crimson but not Xerces.
1312
// It's testing whether the external DTD subset is read,
1313
// default attribute values applied, and comments and
1314
// processing instructions in the external DTD subset are not
1315
// reported.
1316
public void testExternalDTDSubset()
1317      throws IOException JavaDoc, ParsingException {
1318        
1319        File JavaDoc input = new File JavaDoc(inputDir, "externalDTDtest.xml");
1320        Builder builder = new Builder(false);
1321        Document doc = builder.build(input);
1322        assertEquals(2, doc.getChildCount());
1323        Element root = doc.getRootElement();
1324        Attribute name = root.getAttribute("name");
1325        assertEquals("value", name.getValue());
1326        DocType doctype = doc.getDocType();
1327        assertEquals("", doctype.getInternalDTDSubset());
1328        
1329    }
1330
1331    
1332    // Not really ignore, simple resolve, and not
1333
// treat specially otherwise; i.e. don't copy
1334
// parameter entity declarations into the internal
1335
// DTD subset string
1336
public void testIgnoreInternalParameterEntitiesInInternalDTDSubset()
1337      throws IOException JavaDoc, ParsingException {
1338        
1339        Builder builder = new Builder(false);
1340        Document doc = builder.build("<!DOCTYPE root [" +
1341                "<!ENTITY % name \"PCDATA\">" +
1342                "]><root/>", "http://www.example.com/");
1343        assertEquals(2, doc.getChildCount());
1344        DocType doctype = doc.getDocType();
1345        assertEquals("", doctype.getInternalDTDSubset());
1346        
1347    }
1348    
1349    
1350    public void testIgnoreExternalParameterEntitiesInInternalDTDSubset()
1351      throws IOException JavaDoc, ParsingException {
1352        
1353        Builder builder = new Builder(false);
1354        Document doc = builder.build("<!DOCTYPE root [" +
1355                "<!ENTITY % name SYSTEM \"http://www.example.org/\">" +
1356                "]><root/>", "http://www.example.com/");
1357        assertEquals(2, doc.getChildCount());
1358        DocType doctype = doc.getDocType();
1359        assertEquals("", doctype.getInternalDTDSubset());
1360        
1361    }
1362    
1363    
1364    
1365    /* <?xml version="1.0"?>
1366<!DOCTYPE root [
1367  <!ELEMENT root (#PCDATA)>
1368  <!-- comment -->
1369  <?target PI data?>
1370  <!NOTATION JPEG SYSTEM "image/jpeg">
1371  <!ATTLIST root source ENTITY #REQUIRED>
1372  <!ENTITY picture SYSTEM "picture.jpg" NDATA JPEG>
1373]>
1374<root source="picture">
1375  This document is intended to test the building of
1376  various constructs in the internal DTD subset.
1377</root>
1378*/

1379    public void testInternalDTDSubset()
1380      throws ValidityException, ParsingException, IOException JavaDoc {
1381        
1382        File JavaDoc input = new File JavaDoc(inputDir, "internaldtdsubsettest.xml");
1383        Builder builder = new Builder(false);
1384        Document doc = builder.build(input);
1385        String JavaDoc internalSubset = doc.getDocType().getInternalDTDSubset();
1386        assertTrue(internalSubset.indexOf("<!-- comment -->") > 0);
1387        assertTrue(internalSubset.indexOf("<?target PI data?>") > 0);
1388        assertTrue(internalSubset.indexOf("<!ELEMENT root (#PCDATA)>") > 0);
1389        assertTrue(internalSubset.indexOf("<!ATTLIST root source ENTITY #REQUIRED>") > 0);
1390        // some confusion in the parser resolving these as relative URLs.
1391
// This is in accordance with the SAX spec, see
1392
// http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html#notationDecl(java.lang.String,%20java.lang.String,%20java.lang.String)
1393
// but how does it know the notation system ID is really a URL?
1394
assertTrue(internalSubset.indexOf("<!ENTITY picture SYSTEM ") > 0);
1395        assertTrue(internalSubset.indexOf("picture.jpg\" NDATA JPEG>") > 0);
1396        assertTrue(internalSubset.indexOf("<!NOTATION JPEG SYSTEM ") > 0);
1397        assertTrue(internalSubset.indexOf("image/jpeg\">") > 0);
1398        
1399    }
1400    
1401
1402    // This test exposes a bug in Crimson, Xerces 2.5 and earlier,
1403
// and possibly other parsers. I've reported the bug in Xerces,
1404
// and it is fixed in Xerces 2.6.
1405
public void testBaseRelativeResolutionRemotelyWithDirectory()
1406      throws IOException JavaDoc, ParsingException {
1407        builder.build("http://www.ibiblio.org/xml");
1408    }
1409
1410    
1411    // This test exposes a bug in Crimson, Xerces 2.5 and earlier,
1412
// and possibly other parsers. I've reported the bug in Xerces,
1413
// and it should be fixed in Xerces 2.6.
1414
public void testRelativeURIResolutionAgainstARedirectedBase()
1415      throws IOException JavaDoc, ParsingException {
1416        builder.build("http://www.ibiblio.org/xml/redirecttest.xml");
1417    }
1418
1419    
1420    public void testDontGetNodeFactory() {
1421        
1422        Builder builder = new Builder();
1423        NodeFactory factory = builder.getNodeFactory();
1424        if (factory != null) {
1425            assertFalse(
1426              factory.getClass().getName().endsWith("NonVerifyingFactory")
1427            );
1428        }
1429        
1430    }
1431    
1432    
1433    public void testGetNodeFactory() {
1434        NodeFactory factory = new NodeFactory();
1435        Builder builder = new Builder(factory);
1436        assertEquals(factory, builder.getNodeFactory());
1437    }
1438    
1439    
1440    // Make sure additional namespaces aren't added for
1441
// attributes. This test is flaky because it assumes
1442
// the parser reports attributes in the correct order,
1443
// which is not guaranteed. I use a custom SAX Filter to
1444
// make sure the namespace declaration comes before the attribute.
1445
public void testAttributesVsNamespaces()
1446      throws ParsingException, IOException JavaDoc, SAXException JavaDoc {
1447          
1448       XMLFilter JavaDoc filter = new OrderingFilter();
1449       filter.setParent(
1450         XMLReaderFactory.createXMLReader(
1451           "org.apache.xerces.parsers.SAXParser"
1452         )
1453       );
1454       Builder builder = new Builder(filter);
1455       String JavaDoc data ="<a/>";
1456       Document doc = builder.build(data, null);
1457       Element root = doc.getRootElement();
1458       root.removeAttribute(root.getAttribute(0));
1459       assertNull(root.getNamespaceURI("pre"));
1460       
1461    }
1462
1463    
1464    private static class OrderingFilter extends XMLFilterImpl JavaDoc {
1465        
1466        public void startElement(String JavaDoc namespaceURI, String JavaDoc localName,
1467          String JavaDoc qualifiedName, Attributes JavaDoc atts) throws SAXException JavaDoc {
1468    
1469            AttributesImpl JavaDoc newAttributes = new AttributesImpl JavaDoc();
1470            newAttributes.addAttribute(
1471              "",
1472              "pre",
1473              "xmlns:pre",
1474              "CDATA",
1475              "http://www.example.com/");
1476            newAttributes.addAttribute(
1477              "http://www.example.com/",
1478              "name",
1479              "pre:name",
1480              "CDATA",
1481              "value");
1482            super.startElement(namespaceURI, localName, qualifiedName,
1483              newAttributes);
1484        }
1485
1486    }
1487
1488    
1489    public void testValidateMalformedDocument()
1490      throws IOException JavaDoc {
1491        
1492        Reader JavaDoc reader = new StringReader JavaDoc("<!DOCTYPE root [" +
1493                "<!ELEMENT root (a, b)>" +
1494                "<!ELEMENT a (EMPTY)>" +
1495                "<!ELEMENT b (PCDATA)>" +
1496                "]><root><a/><b></b>");
1497        try {
1498            validator.build(reader);
1499            fail("Allowed malformed doc");
1500        }
1501        catch (ValidityException ex) {
1502            fail("Threw validity error instead of well-formedness error");
1503        }
1504        catch (ParsingException ex) {
1505            assertNotNull(ex.getMessage());
1506            assertNull(ex.getURI());
1507        }
1508        
1509    }
1510
1511    
1512    public void testValidateMalformedDocumentWithCrimson()
1513      throws IOException JavaDoc {
1514        
1515        Reader JavaDoc reader = new StringReader JavaDoc("<!DOCTYPE root [" +
1516                "<!ELEMENT root (a, b)>" +
1517                "<!ELEMENT a (EMPTY)>" +
1518                "<!ELEMENT b (PCDATA)>" +
1519                "]><root><a/><b></b>");
1520        XMLReader JavaDoc crimson;
1521        try {
1522            crimson = XMLReaderFactory.createXMLReader(
1523              "org.apache.crimson.parser.XMLReaderImpl");
1524        }
1525        catch (SAXException JavaDoc ex) {
1526            // can't test Crimson if you can't load it
1527
return;
1528        }
1529        Builder validator = new Builder(crimson, true);
1530        try {
1531            validator.build(reader);
1532            fail("Allowed malformed doc");
1533        }
1534        catch (ValidityException ex) {
1535            fail("Crimson threw validity error instead of well-formedness error");
1536        }
1537        catch (ParsingException success) {
1538            assertNotNull(success.getMessage());
1539            assertNull(success.getURI());
1540        }
1541        
1542    }
1543
1544    
1545    // This is testing a work-around for a Xerces bug
1546
// http://nagoya.apache.org/bugzilla/show_bug.cgi?id=27583
1547
// that reports this as an IOException rather than a SAXException
1548
public void testBuildMalformedDocumentWithUnpairedSurrogate()
1549      throws IOException JavaDoc {
1550        
1551        String JavaDoc doc = "<doc>A\uD800A</doc>";
1552        try {
1553            builder.build(doc, "http://www.example.com");
1554            fail("Allowed malformed doc");
1555        }
1556        catch (ParsingException success) {
1557            assertNotNull(success.getMessage());
1558            assertEquals("http://www.example.com/", success.getURI());
1559        }
1560        
1561    }
1562    
1563    
1564    public void testBuildMalformedDocumentWithBadUnicodeData()
1565      throws IOException JavaDoc {
1566        
1567        File JavaDoc f = new File JavaDoc(inputDir, "xmlconf");
1568        f = new File JavaDoc(f, "xmltest");
1569        f = new File JavaDoc(f, "not-wf");
1570        f = new File JavaDoc(f, "sa");
1571        f = new File JavaDoc(f, "170.xml");
1572        if (f.exists()) {
1573            try {
1574                builder.build(f);
1575                fail("Allowed malformed doc");
1576            }
1577            catch (ParsingException success) {
1578                assertNotNull(success.getMessage());
1579                assertTrue(success.getURI().endsWith(
1580                  "data/xmlconf/xmltest/not-wf/sa/170.xml"));
1581                assertTrue(success.getURI().startsWith("file:/"));
1582            }
1583        }
1584        
1585    }
1586    
1587    
1588    public void testBuildAnotherMalformedDocumentWithBadUnicodeData()
1589      throws IOException JavaDoc {
1590        
1591        String JavaDoc filename = "data/oasis/p02fail30.xml";
1592        File JavaDoc f = new File JavaDoc(inputDir, "oasis");
1593        f = new File JavaDoc(f, "p02fail30.xml");
1594        if (f.exists()) {
1595            try {
1596                builder.build(f);
1597                fail("Allowed malformed doc");
1598            }
1599            catch (ParsingException success) {
1600                assertNotNull(success.getMessage());
1601                assertTrue(success.getURI().endsWith(filename));
1602                assertTrue(success.getURI().startsWith("file:/"));
1603            }
1604        }
1605        
1606    }
1607    
1608    
1609    public void testBuildMalformedDocumentWithBadParser()
1610      throws ParsingException, IOException JavaDoc {
1611        
1612        try {
1613            XMLReader JavaDoc parser = new CustomReader();
1614            Builder builder = new Builder(parser);
1615            builder.build("data doesn't matter");
1616        }
1617        catch (IllegalNameException success) {
1618            assertNotNull(success.getMessage());
1619        }
1620        
1621    }
1622
1623    
1624    public void testBuildMalformedDocumentWithCrimson()
1625      throws IOException JavaDoc {
1626        
1627        Reader JavaDoc reader = new StringReader JavaDoc("<!DOCTYPE root [" +
1628                "<!ELEMENT root (a, b)>" +
1629                "<!ELEMENT a (EMPTY)>" +
1630                "<!ELEMENT b (PCDATA)>" +
1631                "]><root><a/><b></b>");
1632        XMLReader JavaDoc crimson;
1633        try {
1634            crimson = XMLReaderFactory.createXMLReader(
1635              "org.apache.crimson.parser.XMLReaderImpl");
1636        }
1637        catch (SAXException JavaDoc ex) {
1638            // can't test Crimson if you can't load it
1639
return;
1640        }
1641        Builder builder = new Builder(crimson);
1642        try {
1643            builder.build(reader);
1644            fail("Allowed malformed doc");
1645        }
1646        catch (ValidityException ex) {
1647            fail("Crimson threw validity error instead of well-formedness error");
1648        }
1649        catch (ParsingException ex) {
1650            assertNotNull(ex.getMessage());
1651            assertNull(ex.getURI());
1652        }
1653        
1654    }
1655    
1656    
1657    public void testBuildFunkyNamespacesWithUntrustedParser()
1658      throws ParsingException, IOException JavaDoc, SAXException JavaDoc {
1659        
1660        Reader JavaDoc reader = new StringReader JavaDoc(
1661          "<root xmlns='http://example.org/'>" +
1662          "<pre:a xmlns:pre='http://www.root.org/' " +
1663          "xmlns='http://www.red.com'>" +
1664          "<b/>" +
1665          "</pre:a></root>");
1666        XMLReader JavaDoc parser = XMLReaderFactory.createXMLReader(
1667          "org.apache.xerces.parsers.SAXParser");
1668        XMLFilter JavaDoc filter = new XMLFilterImpl JavaDoc();
1669        filter.setParent(parser);
1670        Builder builder = new Builder(filter);
1671        Document doc = builder.build(reader);
1672        Element root = doc.getRootElement();
1673        Element prea = (Element) root.getChild(0);
1674        Element b = (Element) prea.getChild(0);
1675        assertEquals("http://www.red.com", b.getNamespaceURI());
1676        
1677    }
1678    
1679    
1680    // from XML Conformance Test Suite; James Clark test
1681
// valid 097
1682
public void testLineBreaksInInternalDTDSubset()
1683      throws ParsingException, IOException JavaDoc {
1684        
1685        Document doc = builder.build(new File JavaDoc(inputDir, "097.xml"));
1686        String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
1687            + "<!DOCTYPE doc [\n"
1688            + " <!ELEMENT doc (#PCDATA)>\n"
1689            + " <!ATTLIST doc a1 CDATA \"v1\">\n"
1690            + " <!ATTLIST doc a2 CDATA #IMPLIED>\n"
1691            + "]>\n"
1692            + "<doc a1=\"v1\" />\n";
1693        String JavaDoc actual = doc.toXML();
1694        assertEquals(expectedResult, actual);
1695        
1696    }
1697    
1698    
1699    public void testBuildDocumentThatUndeclaresDefaultNamespace()
1700      throws ParsingException, IOException JavaDoc {
1701        
1702        Document doc = builder.build(new File JavaDoc(inputDir, "undeclare.xml"));
1703        String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
1704          + "<root xmlns=\"http://www.example.org\" "
1705          + "xmlns:pre=\"http://www.red.com/\" test=\"test\" "
1706          + "pre:red=\"value\">some data<something xmlns=\"\" />"
1707          + "</root>\n";
1708        String JavaDoc actual = doc.toXML();
1709        assertEquals(expectedResult, actual);
1710        
1711    }
1712    
1713    
1714    public void testBuildFromFileThatContainsNonASCIICharacterInName()
1715      throws ParsingException, IOException JavaDoc {
1716        
1717        File JavaDoc f = new File JavaDoc(inputDir, "resumé.xml");
1718        try {
1719            Writer JavaDoc out = new OutputStreamWriter JavaDoc(
1720              new FileOutputStream JavaDoc(f), "UTF8");
1721            out.write("<resumé />");
1722            out.flush();
1723            out.close();
1724            Document doc = builder.build(f);
1725            String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
1726                + "<resumé />\n";
1727            String JavaDoc actual = doc.toXML();
1728            assertEquals(expectedResult, actual);
1729            assertTrue(doc.getBaseURI().startsWith("file:/"));
1730            assertTrue(doc.getBaseURI().endsWith("data/resum%C3%A9.xml"));
1731        }
1732        finally {
1733            if (f.exists()) f.delete();
1734        }
1735        
1736    }
1737    
1738    
1739    // This test fails on Mac OS X. It passes on Linux.
1740
public void testBuildFromFileThatContainsPlane1CharacterInName()
1741      throws ParsingException, IOException JavaDoc {
1742        
1743        int gclef = 0x1D120;
1744        char high = (char) ((gclef - 0x10000)/0x400 + 0xD800);
1745        char low = (char) ((gclef - 0x10000) % 0x400 + 0xDC00);
1746        File JavaDoc f = new File JavaDoc(inputDir, "music" + high + "" + low + ".xml");
1747        try {
1748            Writer JavaDoc out = new OutputStreamWriter JavaDoc(
1749              new FileOutputStream JavaDoc(f), "UTF8");
1750            out.write("<resumé />");
1751            out.flush();
1752            out.close();
1753            Document doc = builder.build(f);
1754            String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
1755                + "<resumé />\n";
1756            String JavaDoc actual = doc.toXML();
1757            assertEquals(expectedResult, actual);
1758        }
1759        finally {
1760            if (f.exists()) f.delete();
1761        }
1762        
1763    }
1764    
1765    
1766    private File JavaDoc makeFile(String JavaDoc name) throws IOException JavaDoc {
1767        
1768        File JavaDoc f = new File JavaDoc(inputDir, "" + name);
1769        Writer JavaDoc out = new OutputStreamWriter JavaDoc(
1770          new FileOutputStream JavaDoc(f), "UTF8");
1771        out.write("<data/>");
1772        out.flush();
1773        out.close();
1774        return f;
1775        
1776    }
1777
1778
1779    public void testBuildFromFileThatContainsAmpersandInName()
1780      throws ParsingException, IOException JavaDoc {
1781        
1782        Document doc = builder.build(new File JavaDoc(inputDir, "&file.xml"));
1783        String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
1784            + "<data />\n";
1785        String JavaDoc actual = doc.toXML();
1786        assertEquals(expectedResult, actual);
1787        assertTrue(doc.getBaseURI().startsWith("file:/"));
1788        assertTrue(doc.getBaseURI().endsWith("data/&file.xml"));
1789        
1790    }
1791  
1792    
1793    public void testBuildFromFileThatContainsSpaceInName()
1794      throws ParsingException, IOException JavaDoc {
1795        
1796        File JavaDoc f = makeFile("space file.xml");
1797        Document doc = builder.build(f);
1798        String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
1799            + "<data />\n";
1800        String JavaDoc actual = doc.toXML();
1801        f.delete();
1802        assertEquals(expectedResult, actual);
1803        assertTrue(doc.getBaseURI().startsWith("file:/"));
1804        assertTrue(doc.getBaseURI().endsWith("data/space%"
1805          + Integer.toHexString(' ') + "file.xml"));
1806        
1807    }
1808  
1809    
1810    public void testBuildFromFileThatContainsSharpInName()
1811      throws ParsingException, IOException JavaDoc {
1812        
1813        File JavaDoc f = new File JavaDoc(inputDir, "#file.xml");
1814        try {
1815            Writer JavaDoc out = new OutputStreamWriter JavaDoc(
1816              new FileOutputStream JavaDoc(f), "UTF8");
1817            out.write("<data />");
1818            out.flush();
1819            out.close();
1820            Document doc = builder.build(f);
1821            String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
1822                + "<data />\n";
1823            String JavaDoc actual = doc.toXML();
1824            assertEquals(expectedResult, actual);
1825            assertTrue(doc.getBaseURI().startsWith("file:/"));
1826            assertTrue(doc.getBaseURI().endsWith("data/%23file.xml"));
1827        }
1828        finally {
1829            if (f.exists()) f.delete();
1830        }
1831        
1832    }
1833  
1834    
1835    public void testBuildFromFileThatContainsExclamationPointInName()
1836      throws ParsingException, IOException JavaDoc {
1837        
1838        Document doc = builder.build(new File JavaDoc(inputDir, "!file.xml"));
1839        String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
1840            + "<data />\n";
1841        String JavaDoc actual = doc.toXML();
1842        assertEquals(expectedResult, actual);
1843        assertTrue(doc.getBaseURI().startsWith("file:/"));
1844        assertTrue(doc.getBaseURI().endsWith("data/!file.xml"));
1845        
1846    }
1847  
1848    
1849    public void testBuildFromFileThatContainsDoubleQuoteInName()
1850      throws ParsingException, IOException JavaDoc {
1851        
1852        File JavaDoc f = makeFile("\"file\".xml");
1853        try {
1854            Document doc = builder.build(f);
1855            f.delete();
1856            String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n<data />\n";
1857            String JavaDoc actual = doc.toXML();
1858            assertEquals(expectedResult, actual);
1859            assertTrue(doc.getBaseURI().startsWith("file:/"));
1860            assertTrue(doc.getBaseURI().endsWith("data/%22file%22.xml"));
1861        }
1862        catch (FileNotFoundException JavaDoc ex) {
1863            // This platform doesn't allow double quotes in file names
1864
}
1865        
1866    }
1867  
1868    
1869    public void testBuildFromFileThatContainsSingleQuoteInName()
1870      throws ParsingException, IOException JavaDoc {
1871        
1872        File JavaDoc f = makeFile("'file'.xml");
1873        Document doc = builder.build(f);
1874        f.delete();
1875        String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
1876            + "<data />\n";
1877        String JavaDoc actual = doc.toXML();
1878        assertEquals(expectedResult, actual);
1879        assertTrue(doc.getBaseURI().startsWith("file:/"));
1880        assertTrue(doc.getBaseURI().endsWith("data/'file'.xml"));
1881        
1882    }
1883  
1884    
1885    public void testBuildFromFileThatContainsParenthesesInName()
1886      throws ParsingException, IOException JavaDoc {
1887        
1888        Document doc = builder.build(new File JavaDoc(inputDir, "()file.xml"));
1889        String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
1890            + "<data />\n";
1891        String JavaDoc actual = doc.toXML();
1892        assertEquals(expectedResult, actual);
1893        assertTrue(doc.getBaseURI().startsWith("file:/"));
1894        assertTrue(doc.getBaseURI().endsWith("data/()file.xml"));
1895        
1896    }
1897  
1898    
1899    public void testBuildFromFileThatContainsCurlyBracesInName()
1900      throws ParsingException, IOException JavaDoc {
1901        
1902        Document doc = builder.build(new File JavaDoc(inputDir, "{file}.xml"));
1903        String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
1904            + "<data />\n";
1905        String JavaDoc actual = doc.toXML();
1906        assertEquals(expectedResult, actual);
1907        assertTrue(doc.getBaseURI().startsWith("file:/"));
1908        assertTrue(doc.getBaseURI().endsWith("data/%"
1909          + Integer.toHexString('{').toUpperCase() + "file%"
1910          + Integer.toHexString('}').toUpperCase() + ".xml"));
1911        
1912    }
1913  
1914    
1915    public void testBuildFromFileThatContainsSquareBracketsInName()
1916      throws ParsingException, IOException JavaDoc {
1917        
1918        Document doc = builder.build(new File JavaDoc(inputDir, "[file].xml"));
1919        String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
1920            + "<data />\n";
1921        String JavaDoc actual = doc.toXML();
1922        assertEquals(expectedResult, actual);
1923        assertTrue(doc.getBaseURI().startsWith("file:/"));
1924        assertTrue(doc.getBaseURI().endsWith("data/%"
1925          + Integer.toHexString('[').toUpperCase() + "file%"
1926          + Integer.toHexString(']').toUpperCase() + ".xml"));
1927        
1928    }
1929  
1930    
1931    public void testBuildFromFileThatContainsVerticalBarInName()
1932      throws ParsingException, IOException JavaDoc {
1933        
1934        File JavaDoc f = makeFile("|file.xml");
1935        try {
1936            Document doc = builder.build(f);
1937            f.delete();
1938            String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
1939                + "<data />\n";
1940            String JavaDoc actual = doc.toXML();
1941            assertEquals(expectedResult, actual);
1942            assertTrue(doc.getBaseURI().startsWith("file:/"));
1943            assertTrue(doc.getBaseURI().endsWith("data/%"
1944              + Integer.toHexString('|').toUpperCase()
1945              + "file.xml"));
1946        }
1947        catch (FileNotFoundException JavaDoc ex) {
1948            // This platform doesn't allow vertical bars in file names
1949
}
1950        
1951    }
1952
1953    
1954    public void testBuildFromFileThatContainsColonInName()
1955      throws ParsingException, IOException JavaDoc {
1956        
1957        File JavaDoc f = makeFile(":file.xml");
1958        try {
1959            Document doc = builder.build(f);
1960            f.delete();
1961            String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
1962                + "<data />\n";
1963            String JavaDoc actual = doc.toXML();
1964            assertEquals(expectedResult, actual);
1965            assertTrue(doc.getBaseURI().startsWith("file:/"));
1966            assertTrue(doc.getBaseURI().endsWith("data/:file.xml"));
1967        }
1968        catch (FileNotFoundException JavaDoc ex) {
1969            // This platform doesn't allow colons in file names
1970
}
1971        
1972    }
1973
1974    
1975    public void testBuildFromFileThatContainsUnderscoreInName()
1976      throws ParsingException, IOException JavaDoc {
1977        
1978        File JavaDoc f = makeFile("_file.xml");
1979        Document doc = builder.build(f);
1980        f.delete();
1981        String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
1982            + "<data />\n";
1983        String JavaDoc actual = doc.toXML();
1984        assertEquals(expectedResult, actual);
1985        assertTrue(doc.getBaseURI().startsWith("file:/"));
1986        assertTrue(doc.getBaseURI().endsWith("data/_file.xml"));
1987        
1988    }
1989
1990    
1991    public void testBuildFromFileThatContainsUppercaseASCIIInName()
1992      throws ParsingException, IOException JavaDoc {
1993        
1994        File JavaDoc f = makeFile("ABCDEFGHIJKLMONPQRSTUVWXYZ.xml");
1995        Document doc = builder.build(f);
1996        f.delete();
1997        String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
1998            + "<data />\n";
1999        String JavaDoc actual = doc.toXML();
2000        assertEquals(expectedResult, actual);
2001        assertTrue(doc.getBaseURI().startsWith("file:/"));
2002        assertTrue(doc.getBaseURI().endsWith("data/ABCDEFGHIJKLMONPQRSTUVWXYZ.xml"));
2003        
2004    }
2005
2006    
2007    public void testBuildFromFileThatContainsAsteriskInName()
2008      throws ParsingException, IOException JavaDoc {
2009        
2010        File JavaDoc f = makeFile("*file.xml");
2011        try {
2012            Document doc = builder.build(f);
2013            f.delete();
2014            String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
2015                + "<data />\n";
2016            String JavaDoc actual = doc.toXML();
2017            assertEquals(expectedResult, actual);
2018            assertTrue(doc.getBaseURI().startsWith("file:/"));
2019            assertTrue(doc.getBaseURI().endsWith("data/*file.xml"));
2020        }
2021        catch (FileNotFoundException JavaDoc ex) {
2022            // This platform doesn't allow asterisks in file names
2023
}
2024        
2025    }
2026  
2027    
2028    public void testBuildFromFileThatContainsSemicolonInName()
2029      throws ParsingException, IOException JavaDoc {
2030        
2031        Document doc = builder.build(new File JavaDoc(inputDir, ";file.xml"));
2032        String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
2033            + "<data />\n";
2034        String JavaDoc actual = doc.toXML();
2035        assertEquals(expectedResult, actual);
2036        assertTrue(doc.getBaseURI().startsWith("file:/"));
2037        assertTrue(doc.getBaseURI().endsWith("data/;file.xml"));
2038        
2039    }
2040  
2041    
2042    public void testBuildFromFileThatContainsPlusSignInName()
2043      throws ParsingException, IOException JavaDoc {
2044        
2045        Document doc = builder.build(new File JavaDoc(inputDir, "+file.xml"));
2046        String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
2047            + "<data />\n";
2048        String JavaDoc actual = doc.toXML();
2049        assertEquals(expectedResult, actual);
2050        assertTrue(doc.getBaseURI().startsWith("file:/"));
2051        assertTrue(doc.getBaseURI().endsWith("data/%"
2052          + Integer.toHexString('+').toUpperCase() + "file.xml"));
2053        
2054    }
2055  
2056    
2057    public void testBuildFromFileThatContainsCommaInName()
2058      throws ParsingException, IOException JavaDoc {
2059        
2060        File JavaDoc f = new File JavaDoc(inputDir, ",file.xml");
2061        try {
2062            Writer JavaDoc out = new OutputStreamWriter JavaDoc(
2063              new FileOutputStream JavaDoc(f), "UTF8");
2064            out.write("<data />");
2065            out.flush();
2066            out.close();
2067            Document doc = builder.build(f);
2068            String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
2069                + "<data />\n";
2070            String JavaDoc actual = doc.toXML();
2071            assertEquals(expectedResult, actual);
2072            assertTrue(doc.getBaseURI().startsWith("file:/"));
2073            assertTrue(doc.getBaseURI().endsWith("data/,file.xml"));
2074        }
2075        finally {
2076            if (f.exists()) f.delete();
2077        }
2078        
2079    }
2080  
2081    
2082    public void testBuildFromFileThatContainsBackslashInName()
2083      throws ParsingException, IOException JavaDoc {
2084        
2085        String JavaDoc os = System.getProperty("os.name", "Unix");
2086        if (os.indexOf("Windows") >= 0) return;
2087  
2088        File JavaDoc f = new File JavaDoc(inputDir, "\\file.xml");
2089        try {
2090            Writer JavaDoc out = new OutputStreamWriter JavaDoc(
2091              new FileOutputStream JavaDoc(f), "UTF8");
2092            out.write("<data />");
2093            out.flush();
2094            out.close();
2095            Document doc = builder.build(f);
2096            String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
2097                + "<data />\n";
2098            String JavaDoc actual = doc.toXML();
2099            assertEquals(expectedResult, actual);
2100            assertTrue(doc.getBaseURI().startsWith("file:/"));
2101            assertTrue(doc.getBaseURI().endsWith("data/%5Cfile.xml"));
2102        }
2103        finally {
2104            if (f.exists()) f.delete();
2105        }
2106        
2107    }
2108  
2109    
2110    public void testBuildFromFileThatContainsC0ControlCharacterInName()
2111      throws ParsingException, IOException JavaDoc {
2112        
2113        File JavaDoc f = new File JavaDoc(inputDir, "\u0019file.xml");
2114        try {
2115            Writer JavaDoc out = new OutputStreamWriter JavaDoc(
2116              new FileOutputStream JavaDoc(f), "UTF8");
2117            out.write("<data />");
2118            out.flush();
2119            out.close();
2120            Document doc = builder.build(f);
2121            String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
2122                + "<data />\n";
2123            String JavaDoc actual = doc.toXML();
2124            assertEquals(expectedResult, actual);
2125            assertTrue(doc.getBaseURI().startsWith("file:/"));
2126            assertTrue(doc.getBaseURI().endsWith("data/%19file.xml"));
2127        }
2128        catch (FileNotFoundException JavaDoc ex) {
2129            // This platform doesn't allow C0 controls in file names
2130
}
2131        finally {
2132            if (f.exists()) f.delete();
2133        }
2134        
2135    }
2136  
2137    
2138    public void testBuildFromFileThatContainsTabCharacterInName()
2139      throws ParsingException, IOException JavaDoc {
2140        
2141        File JavaDoc f = new File JavaDoc(inputDir, "\tfile.xml");
2142        try {
2143            Writer JavaDoc out = new OutputStreamWriter JavaDoc(
2144              new FileOutputStream JavaDoc(f), "UTF8");
2145            out.write("<data />");
2146            out.flush();
2147            out.close();
2148            Document doc = builder.build(f);
2149            String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
2150                + "<data />\n";
2151            String JavaDoc actual = doc.toXML();
2152            assertEquals(expectedResult, actual);
2153            assertTrue(doc.getBaseURI().startsWith("file:/"));
2154            assertTrue(doc.getBaseURI().endsWith("data/%09file.xml"));
2155        }
2156        catch (FileNotFoundException JavaDoc ex) {
2157            // This platform doesn't allow tabs in file names
2158
}
2159        finally {
2160            if (f.exists()) f.delete();
2161        }
2162        
2163    }
2164  
2165    
2166    public void testBuildFromFileThatContainsTildeInName()
2167      throws ParsingException, IOException JavaDoc {
2168        
2169        File JavaDoc f = new File JavaDoc(inputDir, "~file.xml");
2170        try {
2171            Writer JavaDoc out = new OutputStreamWriter JavaDoc(
2172              new FileOutputStream JavaDoc(f), "UTF8");
2173            out.write("<data />");
2174            out.flush();
2175            out.close();
2176            Document doc = builder.build(f);
2177            String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
2178                + "<data />\n";
2179            String JavaDoc actual = doc.toXML();
2180            assertEquals(expectedResult, actual);
2181            assertTrue(doc.getBaseURI().startsWith("file:/"));
2182            assertTrue(doc.getBaseURI().endsWith("data/~file.xml"));
2183        }
2184        finally {
2185            if (f.exists()) f.delete();
2186        }
2187        
2188    }
2189  
2190    
2191    public void testBuildFromFileThatContainsAngleBracketsInName()
2192      throws ParsingException, IOException JavaDoc {
2193        
2194        File JavaDoc f = makeFile("<file>.xml");
2195        try {
2196            Document doc = builder.build(f);
2197            f.delete();
2198            String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
2199                + "<data />\n";
2200            String JavaDoc actual = doc.toXML();
2201            assertEquals(expectedResult, actual);
2202            assertTrue(doc.getBaseURI().startsWith("file:/"));
2203            assertTrue(doc.getBaseURI().endsWith("data/%"
2204              + Integer.toHexString('<').toUpperCase() + "file%"
2205              + Integer.toHexString('>').toUpperCase() + ".xml"));
2206        }
2207        catch (FileNotFoundException JavaDoc ex) {
2208            // This platform doesn't allow < and > in file names
2209
}
2210        
2211    }
2212  
2213    
2214    public void testBuildFromFileThatContainsDollarSignInName()
2215      throws ParsingException, IOException JavaDoc {
2216        
2217        Document doc = builder.build(new File JavaDoc(inputDir, "$file.xml"));
2218        String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
2219            + "<data />\n";
2220        String JavaDoc actual = doc.toXML();
2221        assertEquals(expectedResult, actual);
2222        assertTrue(doc.getBaseURI().startsWith("file:/"));
2223        assertTrue(doc.getBaseURI().endsWith("data/$file.xml"));
2224        
2225    }
2226  
2227    
2228    public void testBuildFromFileThatContainsPercentSignInName()
2229      throws ParsingException, IOException JavaDoc {
2230        
2231        Document doc = builder.build(new File JavaDoc(inputDir, "%file.xml"));
2232        String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
2233            + "<data />\n";
2234        String JavaDoc actual = doc.toXML();
2235        assertEquals(expectedResult, actual);
2236        assertTrue(doc.getBaseURI().startsWith("file:/"));
2237        assertTrue(doc.getBaseURI().endsWith("data/%"
2238          + Integer.toHexString('%') + "file.xml"));
2239        
2240    }
2241  
2242    
2243    public void testBuildFromFileThatContainsQuestionMarkInName()
2244      throws ParsingException, IOException JavaDoc {
2245        
2246        File JavaDoc f = makeFile("?file.xml");
2247        try {
2248            Document doc = builder.build(f);
2249            f.delete();
2250            String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
2251                + "<data />\n";
2252            String JavaDoc actual = doc.toXML();
2253            assertEquals(expectedResult, actual);
2254            assertTrue(doc.getBaseURI().startsWith("file:/"));
2255            assertTrue(doc.getBaseURI().endsWith("data/%"
2256              + Integer.toHexString('?').toUpperCase() + "file.xml"));
2257        }
2258        catch (FileNotFoundException JavaDoc ex) {
2259            // This platform doesn't allow question marks in file names
2260
}
2261        
2262    }
2263  
2264    
2265    public void testBuildFromFileThatContainsAtSignInName()
2266      throws ParsingException, IOException JavaDoc {
2267        
2268        Document doc = builder.build(new File JavaDoc(inputDir, "@file.xml"));
2269        String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
2270            + "<data />\n";
2271        String JavaDoc actual = doc.toXML();
2272        assertEquals(expectedResult, actual);
2273        assertTrue(doc.getBaseURI().startsWith("file:/"));
2274        assertTrue(doc.getBaseURI().endsWith("data/%"
2275          + Integer.toHexString('@') + "file.xml"));
2276        
2277    }
2278  
2279    
2280    public void testBuildFromFileThatContainsEqualsSignInName()
2281      throws ParsingException, IOException JavaDoc {
2282        
2283        Document doc = builder.build(new File JavaDoc(inputDir, "=file.xml"));
2284        String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
2285            + "<data />\n";
2286        String JavaDoc actual = doc.toXML();
2287        assertEquals(expectedResult, actual);
2288        assertTrue(doc.getBaseURI().startsWith("file:/"));
2289        assertTrue(doc.getBaseURI().endsWith("data/=file.xml"));
2290        
2291    }
2292  
2293    
2294    public void testBuildFromFileThatContainsCaretInName()
2295      throws ParsingException, IOException JavaDoc {
2296        
2297        Document doc = builder.build(new File JavaDoc(inputDir, "^file.xml"));
2298        String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
2299            + "<data />\n";
2300        String JavaDoc actual = doc.toXML();
2301        assertEquals(expectedResult, actual);
2302        assertTrue(doc.getBaseURI().startsWith("file:/"));
2303        assertTrue(doc.getBaseURI().endsWith("data/%"
2304          + Integer.toHexString('^').toUpperCase() + "file.xml"));
2305        
2306    }
2307  
2308    
2309    public void testBuildFromFileThatContainsBactickInName()
2310      throws ParsingException, IOException JavaDoc {
2311        
2312        Document doc = builder.build(new File JavaDoc(inputDir, "`file.xml"));
2313        String JavaDoc expectedResult = "<?xml version=\"1.0\"?>\n"
2314            + "<data />\n";
2315        String JavaDoc actual = doc.toXML();
2316        assertEquals(expectedResult, actual);
2317        assertTrue(doc.getBaseURI().startsWith("file:/"));
2318        assertTrue(doc.getBaseURI().endsWith("data/%"
2319          + Integer.toHexString('`') + "file.xml"));
2320        
2321    }
2322    
2323    
2324    private static class NonValidatingFilter extends XMLFilterImpl JavaDoc {
2325        
2326        public void setFeature(String JavaDoc uri, boolean value)
2327          throws SAXNotRecognizedException JavaDoc, SAXNotSupportedException JavaDoc {
2328           
2329            if ("http://xml.org/sax/features/validation".equals(uri) && value) {
2330                throw new SAXNotSupportedException JavaDoc("");
2331            }
2332            super.setFeature(uri, value);
2333            
2334        }
2335        
2336        public boolean getFeature(String JavaDoc uri)
2337          throws SAXNotRecognizedException JavaDoc, SAXNotSupportedException JavaDoc {
2338            
2339            if ("http://xml.org/sax/features/validation".equals(uri)) {
2340                return false;
2341            }
2342            return super.getFeature(uri);
2343            
2344        }
2345        
2346        
2347    }
2348    
2349    
2350    public void testNonValidatingParserException() throws SAXException JavaDoc {
2351        
2352        XMLReader JavaDoc parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
2353        XMLFilter JavaDoc filter = new NonValidatingFilter();
2354        filter.setParent(parser);
2355        
2356        try {
2357            new Builder(filter, true, null);
2358            fail("Validating with a non-validating parser");
2359        }
2360        catch (XMLException success) {
2361            assertNotNull(success.getMessage());
2362        }
2363        
2364    }
2365  
2366    private static class NonEntityResolvingFilter extends XMLFilterImpl JavaDoc {
2367        
2368        public void setFeature(String JavaDoc uri, boolean value)
2369          throws SAXNotRecognizedException JavaDoc, SAXNotSupportedException JavaDoc {
2370           
2371            if (value && (
2372              "http://xml.org/sax/features/validation".equals(uri)
2373              || "http://xml.org/sax/features/external-general-entities".equals(uri))
2374              || "http://xml.org/sax/features/external-parameter-entities".equals(uri)) {
2375                throw new SAXNotSupportedException JavaDoc("");
2376            }
2377            super.setFeature(uri, value);
2378            
2379        }
2380        
2381        public boolean getFeature(String JavaDoc uri)
2382          throws SAXNotRecognizedException JavaDoc, SAXNotSupportedException JavaDoc {
2383            
2384            if ("http://xml.org/sax/features/validation".equals(uri)
2385              || "http://xml.org/sax/features/external-general-entities".equals(uri)
2386              || "http://xml.org/sax/features/external-parameter-entities".equals(uri)) {
2387                return false;
2388            }
2389            return super.getFeature(uri);
2390            
2391        }
2392        
2393        
2394    }
2395    
2396    
2397    public void testNonEntityResolvingParserException() throws SAXException JavaDoc {
2398        
2399        XMLReader JavaDoc parser = XMLReaderFactory.createXMLReader(
2400          "org.apache.xerces.parsers.SAXParser");
2401        XMLFilter JavaDoc filter = new NonEntityResolvingFilter();
2402        filter.setParent(parser);
2403        
2404        try {
2405            new Builder(filter, false, null);
2406            fail("Accepted a non-entity resolving parser");
2407        }
2408        catch (XMLException success) {
2409            assertNotNull(success.getMessage());
2410        }
2411        
2412    }
2413  
2414    
2415    // Fake certain errors to test workarounds for bugs in certain
2416
// parsers, especially Piccolo.
2417
private static class ExceptionTester extends XMLFilterImpl JavaDoc {
2418        
2419        private Exception JavaDoc ex;
2420        
2421        ExceptionTester(Exception JavaDoc ex) {
2422            this.ex = ex;
2423        }
2424        
2425        public void parse(InputSource JavaDoc in) throws IOException JavaDoc, SAXException JavaDoc {
2426            if (ex instanceof IOException JavaDoc) throw (IOException JavaDoc) ex;
2427            else if (ex instanceof SAXException JavaDoc) throw (SAXException JavaDoc) ex;
2428            else throw (RuntimeException JavaDoc) ex;
2429        }
2430        
2431    }
2432    
2433    
2434    public void testParserThrowsNullPointerException()
2435      throws SAXException JavaDoc, IOException JavaDoc {
2436        
2437        XMLReader JavaDoc parser = XMLReaderFactory.createXMLReader(
2438          "org.apache.xerces.parsers.SAXParser");
2439        Exception JavaDoc cause = new NullPointerException JavaDoc();
2440        XMLFilter JavaDoc filter = new ExceptionTester(cause);
2441        filter.setParent(parser);
2442        Builder builder = new Builder(filter);
2443        
2444        try {
2445            builder.build("<data/>");
2446        }
2447        catch (ParsingException success) {
2448            assertEquals(cause, success.getCause());
2449        }
2450        
2451    }
2452    
2453    
2454    public void testParserThrowsNegativeArraySizeException()
2455      throws SAXException JavaDoc, IOException JavaDoc {
2456        
2457        XMLReader JavaDoc parser = XMLReaderFactory.createXMLReader(
2458          "org.apache.xerces.parsers.SAXParser");
2459        Exception JavaDoc cause = new NegativeArraySizeException JavaDoc();
2460        XMLFilter JavaDoc filter = new ExceptionTester(cause);
2461        filter.setParent(parser);
2462        Builder builder = new Builder(filter);
2463        
2464        try {
2465            builder.build("<data/>");
2466        }
2467        catch (ParsingException success) {
2468            assertEquals(cause, success.getCause());
2469        }
2470        
2471    }
2472    
2473    
2474    public void testParserThrowsArrayIndexOutOfBoundsException()
2475      throws SAXException JavaDoc, IOException JavaDoc {
2476        
2477        XMLReader JavaDoc parser = XMLReaderFactory.createXMLReader(
2478          "org.apache.xerces.parsers.SAXParser");
2479        Exception JavaDoc cause = new ArrayIndexOutOfBoundsException JavaDoc();
2480        XMLFilter JavaDoc filter = new ExceptionTester(cause);
2481        filter.setParent(parser);
2482        Builder builder = new Builder(filter);
2483        
2484        try {
2485            builder.build("<data/>");
2486        }
2487        catch (ParsingException success) {
2488            assertEquals(cause, success.getCause());
2489        }
2490        
2491    }
2492    
2493    
2494    public void testParserThrowsUTFDataFormatException()
2495      throws SAXException JavaDoc, IOException JavaDoc {
2496        
2497        XMLReader JavaDoc parser = XMLReaderFactory.createXMLReader(
2498          "org.apache.xerces.parsers.SAXParser");
2499        Exception JavaDoc cause = new UTFDataFormatException JavaDoc();
2500        XMLFilter JavaDoc filter = new ExceptionTester(cause);
2501        filter.setParent(parser);
2502        Builder builder = new Builder(filter);
2503        
2504        try {
2505            builder.build("<data/>");
2506        }
2507        catch (ParsingException success) {
2508            assertEquals(cause, success.getCause());
2509        }
2510        
2511    }
2512    
2513
2514    public void testParserThrowsCharConversionException()
2515      throws SAXException JavaDoc, IOException JavaDoc {
2516        
2517        XMLReader JavaDoc parser = XMLReaderFactory.createXMLReader(
2518          "org.apache.xerces.parsers.SAXParser");
2519        Exception JavaDoc cause = new CharConversionException JavaDoc();
2520        XMLFilter JavaDoc filter = new ExceptionTester(cause);
2521        filter.setParent(parser);
2522        Builder builder = new Builder(filter);
2523        
2524        try {
2525            builder.build("<data/>");
2526        }
2527        catch (ParsingException success) {
2528            assertEquals(cause, success.getCause());
2529        }
2530        
2531    }
2532    
2533
2534    public void testParserThrowsPlainSAXException()
2535      throws SAXException JavaDoc, IOException JavaDoc {
2536        
2537        XMLReader JavaDoc parser = XMLReaderFactory.createXMLReader(
2538          "org.apache.xerces.parsers.SAXParser");
2539        Exception JavaDoc cause = new SAXException JavaDoc("What happened to no-args constructor?");
2540        XMLFilter JavaDoc filter = new ExceptionTester(cause);
2541        filter.setParent(parser);
2542        Builder builder = new Builder(filter);
2543        
2544        try {
2545            builder.build("<data/>");
2546        }
2547        catch (ParsingException success) {
2548            assertEquals(cause, success.getCause());
2549        }
2550        
2551    }
2552    
2553
2554    public void testParserThrowsUnexpectedRuntimeException()
2555      throws SAXException JavaDoc, IOException JavaDoc {
2556        
2557        XMLReader JavaDoc parser = XMLReaderFactory.createXMLReader(
2558          "org.apache.xerces.parsers.SAXParser");
2559        Exception JavaDoc cause = new RuntimeException JavaDoc();
2560        XMLFilter JavaDoc filter = new ExceptionTester(cause);
2561        filter.setParent(parser);
2562        Builder builder = new Builder(filter);
2563        
2564        try {
2565            builder.build("<data/>");
2566        }
2567        catch (ParsingException success) {
2568            assertEquals(cause, success.getCause());
2569        }
2570        
2571    }
2572    
2573
2574    public void testParserThrowsIOException()
2575      throws SAXException JavaDoc, ParsingException {
2576        
2577        XMLReader JavaDoc parser = XMLReaderFactory.createXMLReader(
2578          "org.apache.xerces.parsers.SAXParser");
2579        Exception JavaDoc cause = new IOException JavaDoc();
2580        XMLFilter JavaDoc filter = new ExceptionTester(cause);
2581        filter.setParent(parser);
2582        Builder builder = new Builder(filter);
2583        
2584        try {
2585            builder.build("<data/>");
2586        }
2587        catch (IOException JavaDoc success) {
2588            assertEquals(cause, success);
2589        }
2590        
2591    }
2592    
2593    
2594    public void testCrimsonIgnoresWarning()
2595      throws SAXException JavaDoc, ParsingException, IOException JavaDoc {
2596        
2597        
2598        XMLReader JavaDoc parser;
2599        try {
2600          parser = XMLReaderFactory.createXMLReader(
2601            "org.apache.crimson.parser.XMLReaderImpl"
2602          );
2603        }
2604        catch (SAXException JavaDoc ex) {
2605            // Can't test Crimson if you can't load it
2606
return;
2607        }
2608        XMLFilter JavaDoc filter = new WarningFilter();
2609        filter.setParent(parser);
2610        Builder builder = new Builder(filter);
2611        
2612        Document doc = builder.build("<data/>", null);
2613        assertEquals("<?xml version=\"1.0\"?>\n<data />\n", doc.toXML());
2614        
2615    }
2616    
2617    
2618    private static class WarningFilter extends XMLFilterImpl JavaDoc {
2619        
2620        public void startElement(String JavaDoc namespaceURI, String JavaDoc localName,
2621          String JavaDoc qualifiedName, Attributes JavaDoc atts) throws SAXException JavaDoc {
2622    
2623            this.getErrorHandler().warning(
2624              new SAXParseException JavaDoc("Warning", new LocatorImpl JavaDoc())
2625            );
2626            super.startElement(namespaceURI, localName, qualifiedName,
2627              atts);
2628            
2629        }
2630
2631    }
2632    
2633
2634    public void testSaxonsAElfredIsVerified()
2635      throws SAXException JavaDoc, IOException JavaDoc {
2636        
2637        XMLReader JavaDoc parser;
2638        try {
2639          parser = XMLReaderFactory.createXMLReader(
2640            "com.icl.saxon.aelfred.SAXDriver"
2641          );
2642        }
2643        catch (SAXException JavaDoc ex) {
2644            // Can't test SAXON if you can't load it
2645
return;
2646        }
2647        Builder builder = new Builder(parser);
2648        
2649        try {
2650            // known bug in Saxon; doesn't catch
2651
// colon in processing instruction targets
2652
builder.build("<?test:data ?><data/>", null);
2653            fail("Didn't verify Saxon's input");
2654        }
2655        catch (ParsingException success) {
2656            assertNotNull(success.getMessage());
2657        }
2658        
2659    }
2660    
2661    
2662    public void testSaxon7sAElfredIsVerified()
2663      throws SAXException JavaDoc, IOException JavaDoc {
2664        
2665        XMLReader JavaDoc parser;
2666        try {
2667          parser = XMLReaderFactory.createXMLReader(
2668            "net.sf.saxon.aelfred.SAXDriver"
2669          );
2670        }
2671        catch (SAXException JavaDoc ex) {
2672            // Can't test SAXON if you can't load it
2673
return;
2674        }
2675        Builder builder = new Builder(parser);
2676        
2677        try {
2678            // known bug in Saxon: doesn't catch
2679
// colon in processing instruction targets
2680
builder.build("<?test:data ?><data/>", null);
2681            fail("Didn't verify Saxon's input");
2682        }
2683        catch (ParsingException success) {
2684            assertNotNull(success.getMessage());
2685        }
2686        
2687    }
2688    
2689    
2690   public void testGNUJAXPIsVerified()
2691      throws SAXException JavaDoc, IOException JavaDoc {
2692        
2693        XMLReader JavaDoc parser;
2694        try {
2695          parser = XMLReaderFactory.createXMLReader(
2696            "gnu.xml.aelfred2.XmlReader"
2697          );
2698        }
2699        catch (SAXException JavaDoc ex) {
2700            // Can't test GNU JAXP if you can't load it
2701
return;
2702        }
2703        Builder builder = new Builder(parser);
2704        
2705        try {
2706            // known bug in GNUJAXP: doesn't catch
2707
// colon in processing instruction targets
2708
builder.build("<?test:data ?><data/>", null);
2709            fail("Didn't verify GNU JAXP's input");
2710        }
2711        catch (ParsingException success) {
2712            assertNotNull(success.getMessage());
2713        }
2714        
2715    }
2716   
2717   
2718   public void testCatalogOnTopOfTrustedParserIsTrusted() throws
2719     NoSuchMethodException JavaDoc, InstantiationException JavaDoc, IllegalAccessException JavaDoc, InvocationTargetException JavaDoc {
2720       
2721        try {
2722            XMLReader JavaDoc parser = XMLReaderFactory.createXMLReader(
2723              "org.apache.crimson.parser.XMLReaderImpl"
2724            );
2725        
2726            Class JavaDoc filter = Class.forName("org.apache.xml.resolver.tools.ResolvingXMLFilter");
2727            Class JavaDoc[] types = {XMLReader JavaDoc.class};
2728            Constructor JavaDoc constructor = filter.getConstructor(types);
2729            Object JavaDoc[] args = {parser};
2730            XMLReader JavaDoc reader = (XMLReader JavaDoc) constructor.newInstance(args);
2731            Builder builder = new Builder(reader);
2732            // If the factory is a nonverifying factory, then
2733
// getNodeFactory() won't return it.
2734
assertNull(builder.getNodeFactory());
2735        }
2736        catch (ClassNotFoundException JavaDoc ex) {
2737            // Can't test is we can't find the class
2738
}
2739        catch (SAXException JavaDoc ex) {
2740            // Need a trusted parser to test this
2741
}
2742
2743   }
2744    
2745    
2746}
2747
Popular Tags