• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.apache.harmony.tests.javax.xml.parsers;
17 
18 import junit.framework.TestCase;
19 
20 import org.w3c.dom.Document;
21 import org.w3c.dom.Node;
22 import org.w3c.dom.NodeList;
23 import org.xml.sax.ErrorHandler;
24 import org.xml.sax.SAXException;
25 import org.xml.sax.SAXParseException;
26 import org.xml.sax.SAXNotRecognizedException;
27 import org.xml.sax.SAXNotSupportedException;
28 
29 import java.io.ByteArrayInputStream;
30 import java.io.File;
31 import java.io.IOException;
32 import java.net.URL;
33 import java.net.MalformedURLException;
34 import java.util.ArrayList;
35 import java.util.List;
36 import java.util.Properties;
37 
38 import javax.xml.XMLConstants;
39 import javax.xml.parsers.DocumentBuilder;
40 import javax.xml.parsers.DocumentBuilderFactory;
41 import javax.xml.parsers.FactoryConfigurationError;
42 import javax.xml.parsers.ParserConfigurationException;
43 import javax.xml.transform.stream.StreamSource;
44 import javax.xml.validation.Schema;
45 import javax.xml.validation.SchemaFactory;
46 import javax.xml.validation.SchemaFactoryLoader;
47 
48 public class DocumentBuilderFactoryTest extends TestCase {
49 
50     DocumentBuilderFactory dbf;
51 
52     List<String> cdataElements;
53 
54     List<String> textElements;
55 
56     List<String> commentElements;
57 
setUp()58     protected void setUp() throws Exception {
59         super.setUp();
60         dbf = DocumentBuilderFactory.newInstance();
61 
62         cdataElements = new ArrayList<String>();
63         textElements = new ArrayList<String>();
64         commentElements = new ArrayList<String>();
65     }
66 
tearDown()67     protected void tearDown() throws Exception {
68         dbf = null;
69         cdataElements = null;
70         textElements = null;
71         commentElements = null;
72         super.tearDown();
73     }
74 
75     /**
76      * javax.xml.parsers.DocumentBuilderFactory#DocumentBuilderFactory().
77      */
test_Constructor()78     public void test_Constructor() {
79         try {
80             new DocumentBuilderFactoryChild();
81         } catch (Exception e) {
82             fail("Unexpected exception " + e.toString());
83         }
84     }
85 
86     /**
87      * javax.xml.parsers.DocumentBuilderFactory#getAttribute(String).
88      */
89 //    public void test_getAttributeLjava_lang_String() {
90 //        String[] attributes = {
91 //                "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
92 //                "http://java.sun.com/xml/jaxp/properties/schemaSource" };
93 //        Object[] values = { "http://www.w3.org/2001/XMLSchema", "source" };
94 //
95 //        try {
96 //            for (int i = 0; i < attributes.length; i++) {
97 //                dbf.setAttribute(attributes[i], values[i]);
98 //                assertEquals(values[i], dbf.getAttribute(attributes[i]));
99 //            }
100 //        } catch (IllegalArgumentException e) {
101 //            fail("Unexpected IllegalArgumentException" + e.getMessage());
102 //        } catch (Exception e) {
103 //            fail("Unexpected exception" + e.getMessage());
104 //        }
105 //
106 //        try {
107 //            for (int i = 0; i < attributes.length; i++) {
108 //                dbf.setAttribute(null, null);
109 //                fail("NullPointerException expected");
110 //            }
111 //        } catch (NullPointerException e) {
112 //            // expected
113 //        }
114 //
115 //        String[] badAttributes = {"bad1", "bad2", ""};
116 //        try {
117 //            for (int i = 0; i < badAttributes.length; i++) {
118 //                dbf.getAttribute(badAttributes[i]);
119 //                fail("IllegalArgumentException expected");
120 //            }
121 //        } catch (IllegalArgumentException e) {
122 //            // expected
123 //        }
124 //    }
125 
126     /**
127      * javax.xml.parsers.DocumentBuilderFactory#getFeature(String).
128      */
129 // TODO Fails on JDK. Why?
130 //    public void test_getFeatureLjava_lang_String() {
131 //        String[] features = { "http://xml.org/sax/features/namespaces",
132 //                "http://xml.org/sax/features/validation",
133 //                "http://xml.org/sax/features/external-general-entities" };
134 //        try {
135 //            for (int i = 0; i < features.length; i++) {
136 //                dbf.setFeature(features[i], true);
137 //                assertTrue(dbf.getFeature(features[i]));
138 //            }
139 //        } catch (ParserConfigurationException e) {
140 //            fail("Unexpected ParserConfigurationException " + e.getMessage());
141 //        }
142 //
143 //        try {
144 //            for (int i = 0; i < features.length; i++) {
145 //                dbf.setFeature(features[i], false);
146 //                assertFalse(dbf.getFeature(features[i]));
147 //            }
148 //        } catch (ParserConfigurationException e) {
149 //            fail("Unexpected ParserConfigurationException " + e.getMessage());
150 //        }
151 //
152 //        try {
153 //            for (int i = 0; i < features.length; i++) {
154 //                dbf.setFeature(null, false);
155 //                fail("NullPointerException expected");
156 //            }
157 //        } catch (NullPointerException e) {
158 //            // expected
159 //        } catch (ParserConfigurationException e) {
160 //            fail("Unexpected ParserConfigurationException" + e.getMessage());
161 //        }
162 //
163 //        String[] badFeatures = {"bad1", "bad2", ""};
164 //        try {
165 //            for (int i = 0; i < badFeatures.length; i++) {
166 //                dbf.getFeature(badFeatures[i]);
167 //                fail("ParserConfigurationException expected");
168 //            }
169 //        } catch (ParserConfigurationException e) {
170 //            // expected
171 //        }
172 //
173 //    }
174 
175     /**
176      * javax.xml.parsers.DocumentBuilderFactory#getSchema().
177      *  TBD getSchemas() IS NOT SUPPORTED
178      */
179 /*    public void test_getSchema() {
180         assertNull(dbf.getSchema());
181         SchemaFactory sf =
182             SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
183         try {
184             Schema schema = sf.newSchema();
185             dbf.setSchema(schema);
186             assertNotNull(dbf.getSchema());
187         } catch (SAXException sax) {
188             fail("Unexpected exception " + sax.toString());
189         }
190     }
191     */
192 
193     /**
194      * javax.xml.parsers.DocumentBuilderFactory#isCoalescing().
195      */
test_isCoalescing()196     public void test_isCoalescing() {
197         dbf.setCoalescing(true);
198         assertTrue(dbf.isCoalescing());
199 
200         dbf.setCoalescing(false);
201         assertFalse(dbf.isCoalescing());
202     }
203 
204     /**
205      * javax.xml.parsers.DocumentBuilderFactory#isExpandEntityReferences().
206      */
test_isExpandEntityReferences()207     public void test_isExpandEntityReferences() {
208         dbf.setExpandEntityReferences(true);
209         assertTrue(dbf.isExpandEntityReferences());
210 
211         dbf.setExpandEntityReferences(false);
212         assertFalse(dbf.isExpandEntityReferences());
213     }
214 
215     /**
216      * javax.xml.parsers.DocumentBuilderFactory#isIgnoringComments().
217      */
test_isIgnoringComments()218     public void test_isIgnoringComments() {
219         dbf.setIgnoringComments(true);
220         assertTrue(dbf.isIgnoringComments());
221 
222         dbf.setIgnoringComments(false);
223         assertFalse(dbf.isIgnoringComments());
224     }
225 
226     /**
227      * javax.xml.parsers.DocumentBuilderFactory#isIgnoringElementContentWhitespace().
228      */
test_isIgnoringElementContentWhitespace()229     public void test_isIgnoringElementContentWhitespace() {
230         dbf.setIgnoringElementContentWhitespace(true);
231         assertTrue(dbf.isIgnoringElementContentWhitespace());
232 
233         dbf.setIgnoringElementContentWhitespace(false);
234         assertFalse(dbf.isIgnoringElementContentWhitespace());
235     }
236 
237     /**
238      * javax.xml.parsers.DocumentBuilderFactory#isNamespaceAware().
239      */
test_isNamespaceAware()240     public void test_isNamespaceAware() {
241         dbf.setNamespaceAware(true);
242         assertTrue(dbf.isNamespaceAware());
243 
244         dbf.setNamespaceAware(false);
245         assertFalse(dbf.isNamespaceAware());
246     }
247 
test_setIsValidating()248     public void test_setIsValidating() {
249         dbf.setValidating(true);
250         assertTrue(dbf.isValidating());
251 
252         dbf.setValidating(false);
253         assertFalse(dbf.isValidating());
254     }
255 
test_isSetXIncludeAware()256     public void test_isSetXIncludeAware() {
257         dbf.setXIncludeAware(true);
258         assertTrue(dbf.isXIncludeAware());
259 
260         dbf.setXIncludeAware(false);
261         assertFalse(dbf.isXIncludeAware());
262     }
263 
264     /**
265      * javax.xml.parsers.DocumentBuilderFactory#newInstance().
266      */
test_newInstance()267     public void test_newInstance() {
268         String className = null;
269         try {
270             // case 1: Try to obtain a new instance of factory by default.
271             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
272             assertNotNull(dbf);
273 
274             // case 2: Try to create a new instance of factory using
275             // property DATATYPEFACTORY_PROPERTY
276             className = System.getProperty("javax.xml.parsers.DocumentBuilderFactory");
277             System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
278                     "org.apache.harmony.xml.parsers.DocumentBuilderFactoryImpl");
279 
280             dbf = DocumentBuilderFactory.newInstance();
281             assertNotNull(dbf);
282             assertTrue(dbf instanceof org.apache.harmony.xml.parsers.DocumentBuilderFactoryImpl);
283 
284             // case 3: Try to create a new instance of factory using Property
285             String keyValuePair = "javax.xml.parsers.DocumentBuilderFactory"
286                     + "=" + "org.apache.harmony.xml.parsers.DocumentBuilderFactoryImpl";
287             ByteArrayInputStream bis = new ByteArrayInputStream(keyValuePair
288                     .getBytes());
289             Properties prop = System.getProperties();
290             prop.load(bis);
291             dbf = DocumentBuilderFactory.newInstance();
292             assertNotNull(dbf);
293             assertTrue(dbf instanceof org.apache.harmony.xml.parsers.DocumentBuilderFactoryImpl);
294 
295             // case 4: Check FactoryConfiguration error
296             System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "");
297             try {
298                 DocumentBuilderFactory.newInstance();
299             } catch (FactoryConfigurationError fce) {
300                 // expected
301             }
302 
303         } catch (Exception e) {
304             fail("Unexpected exception " + e.toString());
305         } finally {
306             // Set default value of Datatype factory,
307             // because of this test modifies it.
308             if (className == null) {
309                 System.clearProperty("javax.xml.parsers.DocumentBuilderFactory");
310             } else {
311                 System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
312                     className);
313             }
314         }
315     }
316 
test_newDocumentBuilder()317     public void test_newDocumentBuilder() {
318         // Ordinary case
319         try {
320             DocumentBuilder db = dbf.newDocumentBuilder();
321             assertTrue(db instanceof DocumentBuilder);
322             db.parse(getClass().getResourceAsStream("/simple.xml"));
323         } catch(Exception e) {
324             throw new RuntimeException("Unexpected exception", e);
325         }
326 
327         // Exception case
328         dbf.setValidating(true);
329         try {
330             DocumentBuilder db = dbf.newDocumentBuilder();
331         } catch(ParserConfigurationException e) {
332             // Expected, since Android doesn't have a validating parser.
333         }
334     }
335 
336     /**
337      * javax.xml.parsers.DocumentBuilderFactory#setAttribute(java.lang.String,
338      *     java.lang.Object).
339      */
340 //    public void test_setAttributeLjava_lang_StringLjava_lang_Object() {
341 //        String[] attributes = {
342 //                "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
343 //                "http://java.sun.com/xml/jaxp/properties/schemaSource" };
344 //        Object[] values = { "http://www.w3.org/2001/XMLSchema", "source" };
345 //
346 //        try {
347 //            for (int i = 0; i < attributes.length; i++) {
348 //                dbf.setAttribute(attributes[i], values[i]);
349 //                assertEquals(values[i], dbf.getAttribute(attributes[i]));
350 //            }
351 //        } catch (IllegalArgumentException e) {
352 //            fail("Unexpected IllegalArgumentException" + e.getMessage());
353 //        } catch (Exception e) {
354 //            fail("Unexpected exception" + e.getMessage());
355 //        }
356 //
357 //        String[] badAttributes = {"bad1", "bad2", ""};
358 //        try {
359 //            for (int i = 0; i < badAttributes.length; i++) {
360 //                dbf.setAttribute(badAttributes[i], "");
361 //                fail("IllegalArgumentException expected");
362 //            }
363 //        } catch (IllegalArgumentException iae) {
364 //            // expected
365 //        }
366 //
367 //        try {
368 //            for (int i = 0; i < attributes.length; i++) {
369 //                dbf.setAttribute(null, null);
370 //                fail("NullPointerException expected");
371 //            }
372 //        } catch (NullPointerException e) {
373 //            // expected
374 //        }
375 //    }
376 
377     /**
378      * javax.xml.parsers.DocumentBuilderFactory#setCoalescing(boolean).
379      */
test_setCoalescingZ()380     public void test_setCoalescingZ() {
381         dbf.setCoalescing(true);
382         assertTrue(dbf.isCoalescing());
383 
384         textElements.clear();
385         cdataElements.clear();
386         Exception parseException = null;
387         DocumentBuilder parser = null;
388 
389         try {
390             parser = dbf.newDocumentBuilder();
391             ValidationErrorHandler errorHandler = new ValidationErrorHandler();
392             parser.setErrorHandler(errorHandler);
393 
394             Document document = parser.parse(getClass().getResourceAsStream(
395                     "/recipt.xml"));
396 
397             parseException = errorHandler.getFirstException();
398 
399             goThroughDocument((Node) document, "");
400             assertTrue(textElements
401                     .contains("BeefParmesan<title>withGarlicAngelHairPasta</title>"));
402         } catch (Exception ex) {
403             parseException = ex;
404         }
405         parser.setErrorHandler(null);
406 
407         if (parseException != null) {
408             fail("Unexpected exception " + parseException.getMessage());
409         }
410 
411         dbf.setCoalescing(false);
412         assertFalse(dbf.isCoalescing());
413 
414         textElements.clear();
415         cdataElements.clear();
416 
417         try {
418             parser = dbf.newDocumentBuilder();
419             ValidationErrorHandler errorHandler = new ValidationErrorHandler();
420             parser.setErrorHandler(errorHandler);
421 
422             Document document = parser.parse(getClass().getResourceAsStream(
423                     "/recipt.xml"));
424 
425             parseException = errorHandler.getFirstException();
426 
427             goThroughDocument((Node) document, "");
428 
429             assertFalse(textElements
430                     .contains("BeefParmesan<title>withGarlicAngelHairPasta</title>"));
431 
432         } catch (Exception ex) {
433             parseException = ex;
434         }
435         parser.setErrorHandler(null);
436 
437         if (parseException != null) {
438             fail("Unexpected exception " + parseException.getMessage());
439         }
440     }
441 
442     /**
443      * javax.xml.parsers.DocumentBuilderFactory#setExpandEntityReferences(boolean).
444      */
test_setExpandEntityReferencesZ()445     public void test_setExpandEntityReferencesZ() {
446         dbf.setExpandEntityReferences(true);
447         assertTrue(dbf.isExpandEntityReferences());
448 
449         Exception parseException = null;
450         DocumentBuilder parser = null;
451 
452         try {
453             parser = dbf.newDocumentBuilder();
454             ValidationErrorHandler errorHandler = new ValidationErrorHandler();
455             parser.setErrorHandler(errorHandler);
456 
457             Document document = parser.parse(getClass().getResourceAsStream(
458                     "/recipt.xml"));
459 
460             parseException = errorHandler.getFirstException();
461 
462             assertNotNull(document);
463 
464         } catch (Exception ex) {
465             parseException = ex;
466         }
467         parser.setErrorHandler(null);
468 
469         if (parseException != null) {
470             fail("Unexpected exception " + parseException.getMessage());
471         }
472 
473         dbf.setExpandEntityReferences(false);
474         assertFalse(dbf.isExpandEntityReferences());
475         try {
476             parser = dbf.newDocumentBuilder();
477             ValidationErrorHandler errorHandler = new ValidationErrorHandler();
478             parser.setErrorHandler(errorHandler);
479 
480             Document document = parser.parse(getClass().getResourceAsStream(
481                     "/recipt.xml"));
482 
483             parseException = errorHandler.getFirstException();
484 
485             assertNotNull(document);
486 
487         } catch (Exception ex) {
488             parseException = ex;
489         }
490         parser.setErrorHandler(null);
491 
492         if (parseException != null) {
493             fail("Unexpected exception " + parseException.getMessage());
494         }
495     }
496 
497     /**
498      * javax.xml.parsers.DocumentBuilderFactory#setFeature(java.lang.String).
499      */
test_getSetFeatureLjava_lang_String()500     public void test_getSetFeatureLjava_lang_String() {
501         String[] features = { "http://xml.org/sax/features/namespaces",
502                 "http://xml.org/sax/features/validation" };
503         try {
504             for (int i = 0; i < features.length; i++) {
505                 dbf.setFeature(features[i], true);
506                 assertTrue(dbf.getFeature(features[i]));
507             }
508         } catch (ParserConfigurationException e) {
509             fail("Unexpected ParserConfigurationException" + e.getMessage());
510         }
511 
512         try {
513             for (int i = 0; i < features.length; i++) {
514                 dbf.setFeature(features[i], false);
515                 assertFalse(dbf.getFeature(features[i]));
516             }
517         } catch (ParserConfigurationException e) {
518             fail("Unexpected ParserConfigurationException" + e.getMessage());
519         }
520 
521         try {
522             for (int i = 0; i < features.length; i++) {
523                 dbf.setFeature(null, false);
524                 fail("NullPointerException expected");
525             }
526         } catch (NullPointerException e) {
527             // expected
528         } catch (ParserConfigurationException e) {
529             fail("Unexpected ParserConfigurationException" + e.getMessage());
530         }
531 
532         String[] badFeatures = { "bad1", "bad2", "" };
533         try {
534             for (int i = 0; i < badFeatures.length; i++) {
535                 dbf.setFeature(badFeatures[i], false);
536                 fail("ParserConfigurationException expected");
537             }
538         } catch (ParserConfigurationException e) {
539             // expected
540         }
541     }
542 
543     /**
544      * javax.xml.parsers.DocumentBuilderFactory#setIgnoringComments(boolean).
545      */
test_setIgnoringCommentsZ()546     public void test_setIgnoringCommentsZ() {
547         commentElements.clear();
548 
549         dbf.setIgnoringComments(true);
550         assertTrue(dbf.isIgnoringComments());
551 
552         try {
553             DocumentBuilder parser = dbf.newDocumentBuilder();
554 
555             Document document = parser.parse(getClass().getResourceAsStream(
556                     "/recipt.xml"));
557 
558             goThroughDocument((Node) document, "");
559             assertFalse(commentElements.contains("comment1"));
560             assertFalse(commentElements.contains("comment2"));
561 
562         } catch (IOException e) {
563             fail("Unexpected IOException " + e.getMessage());
564         } catch (ParserConfigurationException e) {
565             fail("Unexpected ParserConfigurationException " + e.getMessage());
566         } catch (SAXException e) {
567             fail("Unexpected SAXException " + e.getMessage());
568         }
569 
570         commentElements.clear();
571 
572         dbf.setIgnoringComments(false);
573         assertFalse(dbf.isIgnoringComments());
574 
575         try {
576             DocumentBuilder parser = dbf.newDocumentBuilder();
577 
578             Document document = parser.parse(getClass().getResourceAsStream(
579                     "/recipt.xml"));
580 
581             goThroughDocument((Node) document, "");
582             assertTrue(commentElements.contains("comment1"));
583             assertTrue(commentElements.contains("comment2"));
584 
585         } catch (IOException e) {
586             fail("Unexpected IOException " + e.getMessage());
587         } catch (ParserConfigurationException e) {
588             fail("Unexpected ParserConfigurationException " + e.getMessage());
589         } catch (SAXException e) {
590             fail("Unexpected SAXException " + e.getMessage());
591         }
592     }
593 
594     /**
595      * javax.xml.parsers.DocumentBuilderFactory#setIgnoringElementContentWhitespace(boolean).
596      */
test_setIgnoringElementContentWhitespaceZ()597     public void test_setIgnoringElementContentWhitespaceZ() {
598         dbf.setIgnoringElementContentWhitespace(true);
599         assertTrue(dbf.isIgnoringElementContentWhitespace());
600 
601         try {
602             DocumentBuilder parser = dbf.newDocumentBuilder();
603 
604             Document document = parser.parse(getClass().getResourceAsStream(
605                     "/recipt.xml"));
606 
607             assertNotNull(document);
608 
609         } catch (IOException e) {
610             fail("Unexpected IOException " + e.getMessage());
611         } catch (ParserConfigurationException e) {
612             fail("Unexpected ParserConfigurationException " + e.getMessage());
613         } catch (SAXException e) {
614             fail("Unexpected SAXException " + e.getMessage());
615         }
616 
617         dbf.setIgnoringElementContentWhitespace(false);
618         assertFalse(dbf.isIgnoringElementContentWhitespace());
619 
620         try {
621             DocumentBuilder parser = dbf.newDocumentBuilder();
622 
623             Document document = parser.parse(getClass().getResourceAsStream(
624                     "/recipt.xml"));
625 
626             assertNotNull(document);
627 
628         } catch (IOException e) {
629             fail("Unexpected IOException " + e.getMessage());
630         } catch (ParserConfigurationException e) {
631             fail("Unexpected ParserConfigurationException " + e.getMessage());
632         } catch (SAXException e) {
633             fail("Unexpected SAXException " + e.getMessage());
634         }
635     }
636 
637     /**
638      * javax.xml.parsers.DocumentBuilderFactory#setNamespaceAware(boolean).
639      */
test_setNamespaceAwareZ()640     public void test_setNamespaceAwareZ() {
641         dbf.setNamespaceAware(true);
642         assertTrue(dbf.isNamespaceAware());
643 
644         try {
645             DocumentBuilder parser = dbf.newDocumentBuilder();
646 
647             Document document = parser.parse(getClass().getResourceAsStream(
648                     "/recipt.xml"));
649 
650             assertNotNull(document);
651 
652         } catch (IOException e) {
653             fail("Unexpected IOException " + e.getMessage());
654         } catch (ParserConfigurationException e) {
655             fail("Unexpected ParserConfigurationException " + e.getMessage());
656         } catch (SAXException e) {
657             fail("Unexpected SAXException " + e.getMessage());
658         }
659 
660         dbf.setNamespaceAware(false);
661         assertFalse(dbf.isNamespaceAware());
662 
663         try {
664             DocumentBuilder parser = dbf.newDocumentBuilder();
665 
666             Document document = parser.parse(getClass().getResourceAsStream(
667                     "/recipt.xml"));
668 
669             assertNotNull(document);
670 
671         } catch (IOException e) {
672             fail("Unexpected IOException " + e.getMessage());
673         } catch (ParserConfigurationException e) {
674             fail("Unexpected ParserConfigurationException " + e.getMessage());
675         } catch (SAXException e) {
676             fail("Unexpected SAXException " + e.getMessage());
677         }
678     }
679 
test_getSetAttribute()680     public void test_getSetAttribute() {
681         // Android SAX implementation doesn't support attributes, so
682         // we can only make sure the expected exception is thrown.
683         try {
684             dbf.setAttribute("foo", new Object());
685             fail("IllegalArgumentException expected");
686         } catch (IllegalArgumentException e) {
687             // Expected
688         }
689 
690         try {
691             dbf.getAttribute("foo");
692             fail("IllegalArgumentException expected");
693         } catch (IllegalArgumentException e) {
694             // Expected
695         }
696     }
697 
698     /**
699      * javax.xml.parsers.DocumentBuilderFactory#setSchema(javax.xml.validation.Schema).
700      */
test_setSchemaLjavax_xml_validation_Schema()701     public void test_setSchemaLjavax_xml_validation_Schema()
702         throws MalformedURLException, SAXException, SAXNotSupportedException {
703         String language = XMLConstants.W3C_XML_SCHEMA_NS_URI;
704         String propName = SchemaFactory.class.getName() + ":" + language;
705         String className =
706             "org.apache.harmony.tests.javax.xml.parsers.MockSchemaFactory";
707 
708         // Test `SchemaFactory.newInstance` methods. Set system property for
709         // schema language to make `newInstance` use the mock implementation of
710         // `SchemaFactory`.
711         System.setProperty(propName, className);
712         SchemaFactory f1 = SchemaFactory.newInstance(language);
713         SchemaFactory f2 = SchemaFactory.newInstance(language, className, null);
714 
715         // Test `SchemaFactory.newSchema` method for `File`, `URL` and `Source`.
716         try {
717             Schema s = f1.newSchema();
718             s = f1.newSchema(new File("test.dtd"));
719             s = f1.newSchema(new URL("https://test.org"));
720             s = f1.newSchema(new StreamSource());
721             dbf.setSchema(s);
722             assertNotNull(dbf.getSchema());
723         } catch (UnsupportedOperationException e) {
724             // Expected.
725         }
726 
727         // Test `newFactory` method for the mock `SchemaFactoryLoader`.
728         SchemaFactoryLoader loader = new MockSchemaFactoryLoader();
729         assertNull(loader.newFactory(language));
730 
731         // Test `getFeature` (the mock implementation always throws).
732         try {
733             f2.getFeature("woot");
734         } catch (SAXNotRecognizedException e) {
735             // Expected.
736         }
737 
738         // Test `setFeature` (the mock implementation always throws).
739         try {
740             f2.setFeature("woot", true);
741         } catch (SAXNotRecognizedException e) {
742             // Expected.
743         }
744 
745         // Test `getProperty` (the mock implementation always throws).
746         try {
747             f2.getProperty("woot");
748         } catch (SAXNotRecognizedException e) {
749             // Expected.
750         }
751 
752         // Test `setProperty` (the mock implementation always throws).
753         try {
754             f2.setProperty("woot", null);
755         } catch (SAXNotRecognizedException e) {
756             // Expected.
757         }
758     }
759 
760     /**
761      * javax.xml.parsers.DocumentBuilderFactory#setValidating(boolean).
762      */
763 //    public void test_setValidatingZ() {
764 //        Exception parseException = null;
765 //        DocumentBuilder parser = null;
766 //        Document document = null;
767 //
768 //        ValidationErrorHandler errorHandler = new ValidationErrorHandler();
769 //
770 //        dbf.setValidating(false);
771 //        assertFalse(dbf.isValidating());
772 //
773 //        // case 1: Validation is not set. Correct xml-file
774 //        try {
775 //
776 //            parser = dbf.newDocumentBuilder();
777 //            parser.setErrorHandler(errorHandler);
778 //
779 //            document = parser.parse(getClass().getResourceAsStream(
780 //                    "/recipt.xml"));
781 //
782 //            parseException = errorHandler.getFirstException();
783 //
784 //            assertNotNull(document);
785 //
786 //            document = parser.parse(getClass().getResourceAsStream(
787 //                    "/reciptWrong.xml"));
788 //
789 //            parseException = errorHandler.getFirstException();
790 //
791 //            assertNotNull(document);
792 //
793 //        } catch (Exception ex) {
794 //            parseException = ex;
795 //        }
796 //        parser.setErrorHandler(null);
797 //
798 //        if (parseException != null) {
799 //            fail("Unexpected exception " + parseException.getMessage());
800 //        }
801 //
802 //        // case 2: Validation is not set. Wrong xml-file
803 //        try {
804 //
805 //            parser = dbf.newDocumentBuilder();
806 //            parser.setErrorHandler(errorHandler);
807 //
808 //            document = parser.parse(getClass().getResourceAsStream(
809 //                    "/reciptWrong.xml"));
810 //            parseException = errorHandler.getFirstException();
811 //
812 //            assertNotNull(document);
813 //
814 //        } catch (Exception ex) {
815 //            parseException = ex;
816 //        }
817 //        parser.setErrorHandler(null);
818 //
819 //        if (parseException != null) {
820 //            fail("Unexpected exception " + parseException.getMessage());
821 //        }
822 //
823 //        // case 3: Validation is set. Correct xml-file
824 //        dbf.setValidating(true);
825 //        assertTrue(dbf.isValidating());
826 //
827 //        try {
828 //
829 //            parser = dbf.newDocumentBuilder();
830 //            parser.setErrorHandler(errorHandler);
831 //
832 //            document = parser.parse(getClass().getResourceAsStream(
833 //                    "/recipt.xml"));
834 //            parseException = errorHandler.getFirstException();
835 //
836 //            assertNotNull(document);
837 //
838 //        } catch (Exception ex) {
839 //            parseException = ex;
840 //        }
841 //        parser.setErrorHandler(null);
842 //
843 //        if (parseException != null) {
844 //            fail("Unexpected exception " + parseException.getMessage());
845 //        }
846 //
847 //        // case 4: Validation is set. Wrong xml-file
848 //        try {
849 //
850 //            parser = dbf.newDocumentBuilder();
851 //            parser.setErrorHandler(errorHandler);
852 //
853 //            document = parser.parse(getClass().getResourceAsStream(
854 //                    "/reciptWrong.xml"));
855 //            parseException = errorHandler.getFirstException();
856 //
857 //            assertNotNull(document);
858 //
859 //        } catch (Exception ex) {
860 //            parseException = ex;
861 //        }
862 //        parser.setErrorHandler(null);
863 //
864 //        if (parseException == null) {
865 //            fail("Unexpected exception " + parseException.getMessage());
866 //        } else {
867 //            assertTrue(parseException
868 //                    .getMessage()
869 //                    .contains(
870 //                            "The content of element type \"collection\" must match \"(description,recipe+)\""));
871 //        }
872 //
873 //    }
874 
875     /**
876      * javax.xml.parsers.DocumentBuilderFactory#setXIncludeAware().
877      */
878 //    public void test_setXIncludeAware() {
879 //        dbf.setXIncludeAware(true);
880 //        assertTrue(dbf.isXIncludeAware());
881 //
882 //        try {
883 //            DocumentBuilder parser = dbf.newDocumentBuilder();
884 //
885 //            Document document = parser.parse(getClass().getResourceAsStream(
886 //                    "/recipt.xml"));
887 //
888 //            assertNotNull(document);
889 //
890 //        } catch (IOException e) {
891 //            fail("Unexpected IOException " + e.getMessage());
892 //        } catch (ParserConfigurationException e) {
893 //            fail("Unexpected ParserConfigurationException " + e.getMessage());
894 //        } catch (SAXException e) {
895 //            fail("Unexpected SAXException " + e.getMessage());
896 //        }
897 //
898 //        dbf.setXIncludeAware(false);
899 //        assertFalse(dbf.isXIncludeAware());
900 //
901 //        try {
902 //            DocumentBuilder parser = dbf.newDocumentBuilder();
903 //
904 //            Document document = parser.parse(getClass().getResourceAsStream(
905 //                    "/recipt.xml"));
906 //
907 //            assertNotNull(document);
908 //
909 //        } catch (IOException e) {
910 //            fail("Unexpected IOException " + e.getMessage());
911 //        } catch (ParserConfigurationException e) {
912 //            fail("Unexpected ParserConfigurationException " + e.getMessage());
913 //        } catch (SAXException e) {
914 //            fail("Unexpected SAXException " + e.getMessage());
915 //        }
916 //    }
917 
goThroughDocument(Node node, String indent)918     private void goThroughDocument(Node node, String indent) {
919         String value = node.getNodeValue();
920 
921         if (value != null) {
922             value = value.replaceAll(" ", "");
923             value = value.replaceAll("\n", "");
924         }
925 
926         switch (node.getNodeType()) {
927         case Node.CDATA_SECTION_NODE:
928             cdataElements.add(value);
929             // System.out.println(indent + "CDATA_SECTION_NODE " + value);
930             break;
931         case Node.COMMENT_NODE:
932             commentElements.add(value);
933             // System.out.println(indent + "COMMENT_NODE " + value);
934             break;
935         case Node.DOCUMENT_FRAGMENT_NODE:
936             // System.out.println(indent + "DOCUMENT_FRAGMENT_NODE " + value);
937             break;
938         case Node.DOCUMENT_NODE:
939             // System.out.println(indent + "DOCUMENT_NODE " + value);
940             break;
941         case Node.DOCUMENT_TYPE_NODE:
942             // System.out.println(indent + "DOCUMENT_TYPE_NODE " + value);
943             break;
944         case Node.ELEMENT_NODE:
945             // System.out.println(indent + "ELEMENT_NODE " + value);
946             break;
947         case Node.ENTITY_NODE:
948             // System.out.println(indent + "ENTITY_NODE " + value);
949             break;
950         case Node.ENTITY_REFERENCE_NODE:
951             // System.out.println(indent + "ENTITY_REFERENCE_NODE " + value);
952             break;
953         case Node.NOTATION_NODE:
954             // System.out.println(indent + "NOTATION_NODE " + value);
955             break;
956         case Node.PROCESSING_INSTRUCTION_NODE:
957             // System.out.println(indent + "PROCESSING_INSTRUCTION_NODE " +
958             // value);
959             break;
960         case Node.TEXT_NODE:
961             textElements.add(value);
962             // System.out.println(indent + "TEXT_NODE " + value);
963             break;
964         default:
965             // System.out.println(indent + "Unknown node " + value);
966             break;
967         }
968         NodeList list = node.getChildNodes();
969         for (int i = 0; i < list.getLength(); i++)
970             goThroughDocument(list.item(i), indent + "   ");
971     }
972 
973     private class ValidationErrorHandler implements ErrorHandler {
974         private SAXException parseException;
975 
976         private int errorCount;
977 
978         private int warningCount;
979 
ValidationErrorHandler()980         public ValidationErrorHandler() {
981             parseException = null;
982             errorCount = 0;
983             warningCount = 0;
984         }
985 
error(SAXParseException ex)986         public void error(SAXParseException ex) {
987             errorCount++;
988             if (parseException == null) {
989                 parseException = ex;
990             }
991         }
992 
warning(SAXParseException ex)993         public void warning(SAXParseException ex) {
994             warningCount++;
995         }
996 
fatalError(SAXParseException ex)997         public void fatalError(SAXParseException ex) {
998             if (parseException == null) {
999                 parseException = ex;
1000             }
1001         }
1002 
getFirstException()1003         public SAXException getFirstException() {
1004             return parseException;
1005         }
1006     }
1007 
1008     private class DocumentBuilderFactoryChild extends DocumentBuilderFactory {
DocumentBuilderFactoryChild()1009         public DocumentBuilderFactoryChild() {
1010             super();
1011         }
1012 
getAttribute(String name)1013         public Object getAttribute(String name) {
1014             return null;
1015         }
1016 
getFeature(String name)1017         public boolean getFeature(String name) {
1018             return false;
1019         }
1020 
newDocumentBuilder()1021         public DocumentBuilder newDocumentBuilder() {
1022             return null;
1023         }
1024 
setAttribute(String name, Object value)1025         public void setAttribute(String name, Object value) {
1026         }
1027 
setFeature(String name, boolean value)1028         public void setFeature(String name, boolean value) {
1029         }
1030 
1031     }
1032 }
1033