KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openide > xml > XMLUtilTest


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.openide.xml;
21
22 import java.io.ByteArrayInputStream JavaDoc;
23 import java.io.ByteArrayOutputStream JavaDoc;
24 import java.io.CharConversionException JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.StringReader JavaDoc;
27 import java.net.URL JavaDoc;
28 import java.net.URLClassLoader JavaDoc;
29 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
30 import junit.framework.Test;
31 import org.netbeans.junit.NbTestCase;
32 import org.netbeans.junit.NbTestSuite;
33 import org.w3c.dom.Document JavaDoc;
34 import org.w3c.dom.DocumentType JavaDoc;
35 import org.w3c.dom.Element JavaDoc;
36 import org.w3c.dom.NodeList JavaDoc;
37 import org.xml.sax.EntityResolver JavaDoc;
38 import org.xml.sax.ErrorHandler JavaDoc;
39 import org.xml.sax.InputSource JavaDoc;
40 import org.xml.sax.SAXException JavaDoc;
41 import org.xml.sax.SAXParseException JavaDoc;
42 import org.xml.sax.XMLReader JavaDoc;
43
44 public class XMLUtilTest extends NbTestCase {
45     
46     public XMLUtilTest(String JavaDoc testName) {
47         super(testName);
48     }
49     
50     public void testCreateXMLReader() {
51         
52         XMLReader JavaDoc parser = null;
53         
54         try {
55             parser = XMLUtil.createXMLReader();
56         } catch (Exception JavaDoc ex) {
57             ex.printStackTrace();
58         }
59                 
60         // Add your test code below by replacing the default call to fail.
61
if (parser == null) fail("Cannot create XML reader");
62     }
63     
64     public void testCreateDocument() {
65        
66         Document JavaDoc doc = null;
67         try {
68             doc = XMLUtil.createDocument("root", null, null, null);
69         } catch (Exception JavaDoc ex) {
70             ex.printStackTrace();
71         }
72         
73         // Add your test code below by replacing the default call to fail.
74
if (doc == null) fail("The test case is empty.");
75     }
76     
77     public void testWrite() throws Exception JavaDoc {
78         String JavaDoc data = "<foo bar=\"val\"><baz/></foo>";
79         Document JavaDoc doc = XMLUtil.parse(new InputSource JavaDoc(new StringReader JavaDoc(data)), false, true, null, null);
80         //System.err.println("XMLUtil.parse impl class: " + doc.getClass().getName());
81
Element JavaDoc el = doc.getDocumentElement();
82         assertEquals("foo", el.getNodeName());
83         assertEquals("val", el.getAttribute("bar"));
84         NodeList JavaDoc l = el.getElementsByTagName("*");
85         assertEquals(1, l.getLength());
86         Element JavaDoc el2 = (Element JavaDoc)l.item(0);
87         assertEquals("baz", el2.getLocalName());
88         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
89         XMLUtil.write(doc, baos, "UTF-8");
90         String JavaDoc data2 = baos.toString("UTF-8");
91         //System.err.println("testWrite: data2:\n" + data2);
92
assertTrue(data2, data2.indexOf("foo") != -1);
93         assertTrue(data2, data2.indexOf("bar") != -1);
94         assertTrue(data2, data2.indexOf("baz") != -1);
95         assertTrue(data2, data2.indexOf("val") != -1);
96     }
97     
98     /** Test that read/write DOCTYPE works too. */
99     public void testDocType() throws Exception JavaDoc {
100         String JavaDoc data = "<!DOCTYPE foo PUBLIC \"The foo DTD\" \"http://nowhere.net/foo.dtd\"><foo><x/><x/></foo>";
101         Document JavaDoc doc = XMLUtil.parse(new InputSource JavaDoc(new StringReader JavaDoc(data)), true, true, new Handler JavaDoc(), new Resolver JavaDoc());
102         DocumentType JavaDoc t = doc.getDoctype();
103         assertNotNull(t);
104         assertEquals("foo", t.getName());
105         assertEquals("The foo DTD", t.getPublicId());
106         assertEquals("http://nowhere.net/foo.dtd", t.getSystemId());
107         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
108         XMLUtil.write(doc, baos, "UTF-8");
109         String JavaDoc data2 = baos.toString("UTF-8");
110         //System.err.println("data2:\n" + data2);
111
assertTrue(data2, data2.indexOf("foo") != -1);
112         assertTrue(data2, data2.indexOf("x") != -1);
113         assertTrue(data2, data2.indexOf("DOCTYPE") != -1);
114         assertTrue(data2, data2.indexOf("The foo DTD") != -1);
115         assertTrue(data2, data2.indexOf("http://nowhere.net/foo.dtd") != -1);
116     }
117     private static final class Handler implements ErrorHandler JavaDoc {
118         public void error(SAXParseException JavaDoc exception) throws SAXException JavaDoc {
119             throw exception;
120         }
121         public void fatalError(SAXParseException JavaDoc exception) throws SAXException JavaDoc {
122             throw exception;
123         }
124         public void warning(SAXParseException JavaDoc exception) throws SAXException JavaDoc {
125             throw exception;
126         }
127     }
128     private static final class Resolver implements EntityResolver JavaDoc {
129         public InputSource JavaDoc resolveEntity(String JavaDoc publicId, String JavaDoc systemId) throws SAXException JavaDoc, IOException JavaDoc {
130             assertEquals("The foo DTD", publicId);
131             assertEquals("http://nowhere.net/foo.dtd", systemId);
132             String JavaDoc data = "<!ELEMENT foo (x+)><!ELEMENT x EMPTY>";
133             return new InputSource JavaDoc(new StringReader JavaDoc(data));
134         }
135     }
136     
137     public void testToAttributeValue() throws IOException JavaDoc {
138         String JavaDoc result = null;
139         try {
140             result = XMLUtil.toAttributeValue("\t\r\n &'<\"");
141         } catch (CharConversionException JavaDoc ex) {
142         }
143         
144         assertEquals("Basic escape test failed", "\t\r\n &amp;&apos;&lt;&quot;", result);
145         
146         try {
147             XMLUtil.toAttributeValue(new String JavaDoc(new byte[] { 0 }));
148             fail("Forbidden character accepted.");
149         } catch (CharConversionException JavaDoc ex) {
150         }
151
152         try {
153             XMLUtil.toAttributeValue(new String JavaDoc(new byte[] { 31 }));
154             fail("Forbidden character accepted.");
155         } catch (CharConversionException JavaDoc ex) {
156         }
157     }
158     
159     public void testElementToContent() {
160         String JavaDoc result = null;
161         
162         try {
163             result = XMLUtil.toElementContent("]]>\t\r\n &<>");
164         } catch (CharConversionException JavaDoc ex) {
165         }
166         
167         assertEquals("Basic escape test failed", "]]&gt;\t\r\n &amp;&lt;>", result);
168         
169         try {
170             XMLUtil.toElementContent(new String JavaDoc(new byte[] { 0 }));
171             fail("Forbidden character accepted.");
172         } catch (CharConversionException JavaDoc ex) {
173         }
174
175         try {
176             XMLUtil.toElementContent(new String JavaDoc(new byte[] { 31 }));
177             fail("Forbidden character accepted.");
178         } catch (CharConversionException JavaDoc ex) {
179         }
180                 
181     }
182     
183     public void testToHex() {
184         
185         byte[] data = new byte[] {0, 1, 15, 16, (byte)255};
186         String JavaDoc s = XMLUtil.toHex(data, 0, data.length);
187         
188         // Add your test code below by replacing the default call to fail.
189
if (s.equalsIgnoreCase("00010f10ff") == false) {
190             fail("toHex() =" + s);
191         }
192     }
193     
194     public void testFromHex() {
195         
196         char[] hex = "00010f10ff".toCharArray();
197         try {
198             byte[] ret = XMLUtil.fromHex(hex, 0, hex.length);
199             if (ret[0] != 0 || ret[1] != 1 || ret[2] != 15 || ret[3] != 16 || ret[4] != (byte)255) {
200                 fail("fromHex()");
201             }
202         } catch (IOException JavaDoc ex) {
203             fail(ex.getMessage());
204         }
205                 
206     }
207     
208     /**
209      * Check that reading and writing namespaces works.
210      * @see "#36294"
211      */

212     public void testNamespaces() throws Exception JavaDoc {
213         String JavaDoc data = "<foo xmlns='bar'><baz/></foo>";
214         Document JavaDoc doc = XMLUtil.parse(new InputSource JavaDoc(new StringReader JavaDoc(data)), false, true, null, null);
215         //System.err.println("XMLUtil.parse impl class: " + doc.getClass().getName());
216
Element JavaDoc el = doc.getDocumentElement();
217         assertEquals("foo", el.getNodeName());
218         assertEquals("foo", el.getTagName());
219         assertEquals("foo", el.getLocalName());
220         assertEquals("bar", el.getNamespaceURI());
221         NodeList JavaDoc l = el.getElementsByTagName("*");
222         assertEquals(1, l.getLength());
223         Element JavaDoc el2 = (Element JavaDoc)l.item(0);
224         assertEquals("baz", el2.getLocalName());
225         assertEquals("bar", el2.getNamespaceURI());
226         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
227         XMLUtil.write(doc, baos, "UTF-8");
228         String JavaDoc data2 = baos.toString("UTF-8");
229         //System.err.println("testNamespaces: data2:\n" + data2);
230
assertTrue(data2, data2.indexOf("foo") != -1);
231         assertTrue(data2, data2.indexOf("bar") != -1);
232         doc = XMLUtil.parse(new InputSource JavaDoc(new ByteArrayInputStream JavaDoc(baos.toByteArray())), false, true, null, null);
233         el = doc.getDocumentElement();
234         assertEquals("foo", el.getLocalName());
235         assertEquals("bar", el.getNamespaceURI());
236         l = el.getElementsByTagName("*");
237         assertEquals(1, l.getLength());
238         el2 = (Element JavaDoc)l.item(0);
239         assertEquals("baz", el2.getLocalName());
240         assertEquals("bar", el2.getNamespaceURI());
241         doc = XMLUtil.createDocument("foo2", "bar2", null, null);
242         //System.err.println("XMLUtil.createDocument impl class: " + doc.getClass().getName());
243
doc.getDocumentElement().appendChild(doc.createElementNS("bar2", "baz2"));
244         baos = new ByteArrayOutputStream JavaDoc();
245         XMLUtil.write(doc, baos, "UTF-8");
246         data2 = baos.toString("UTF-8");
247         assertTrue(data2, data2.indexOf("foo2") != -1);
248         assertTrue("namespace 'bar2' of root element mentioned in output: " + data2, data2.indexOf("bar2") != -1);
249         doc = XMLUtil.parse(new InputSource JavaDoc(new ByteArrayInputStream JavaDoc(baos.toByteArray())), false, true, null, null);
250         el = doc.getDocumentElement();
251         assertEquals("foo2", el.getLocalName());
252         assertEquals("bar2", el.getNamespaceURI());
253         l = el.getElementsByTagName("*");
254         assertEquals(1, l.getLength());
255         el2 = (Element JavaDoc)l.item(0);
256         assertEquals("baz2", el2.getLocalName());
257         assertEquals("bar2", el2.getNamespaceURI());
258     }
259     
260     /**
261      * Check more namespace stuff, since JAXP has a lot of bugs...
262      * @see "#6308026"
263      */

264     public void testNamespaces2() throws Exception JavaDoc {
265         String JavaDoc data = "<root xmlns='root'/>";
266         Document JavaDoc doc = XMLUtil.parse(new InputSource JavaDoc(new StringReader JavaDoc(data)), false, true, null, null);
267         doc.getDocumentElement().appendChild(doc.createElementNS("child", "child"));
268         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
269         XMLUtil.write(doc, baos, "UTF-8");
270         //System.err.println("testNamespaces2:\n" + baos);
271
doc = XMLUtil.parse(new InputSource JavaDoc(new ByteArrayInputStream JavaDoc(baos.toByteArray())), false, true, null, null);
272         Element JavaDoc el = doc.getDocumentElement();
273         assertEquals("root", el.getLocalName());
274         assertEquals("root", el.getNamespaceURI());
275         NodeList JavaDoc l = el.getElementsByTagName("*");
276         assertEquals(1, l.getLength());
277         el = (Element JavaDoc) l.item(0);
278         assertEquals("child", el.getLocalName());
279         assertEquals("Correct namespaces in " + baos.toString(), "child", el.getNamespaceURI());
280     }
281     
282     public void testIndentation() throws Exception JavaDoc {
283         Document JavaDoc doc = XMLUtil.createDocument("root", null, null, null);
284         doc.getDocumentElement().appendChild(doc.createElement("child"));
285         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
286         XMLUtil.write(doc, baos, "UTF-8");
287         String JavaDoc data = baos.toString()/*#62680*/.replaceAll("\r\n", "\n");
288         assertTrue("had reasonable indentation in\n" + data, data.indexOf("<root>\n <child/>\n</root>\n") != -1);
289     }
290     
291     /** cf. #62006 */
292     public void testIndentation2() throws Exception JavaDoc {
293         // XXX currently it seems that the JDK 5/6 serializer adds an extra \n after DOCTYPE, for no apparent reason!
294
// While the Mantis serializer inserts a useless line break in the middle...
295
// so we don't check formatting on that part.
296
// Also serializers may arbitrarily reorder the doctype, so don't even look at it (just make sure it is there).
297
String JavaDoc doctype = "<!DOCTYPE p PUBLIC \"random DTD\" \"" + XMLUtilTest.class.getResource("random.dtd") + "\">\n";
298         String JavaDoc data =
299                 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
300                 doctype +
301                 "<!--\n" +
302                 "Some license or whatever.\n" +
303                 "-->\n" +
304                 "<?stylesheet location=\"here\"?>\n" +
305                 "<p>\n" +
306                 " <t/>\n" +
307                 " <c>\n" +
308                 " <d>\n" +
309                 " <s/>\n" +
310                 " </d>\n" +
311                 " </c>\n" +
312                 "</p>\n";
313         Document JavaDoc doc = XMLUtil.parse(new InputSource JavaDoc(new StringReader JavaDoc(data)), false, false, null, null);
314         Element JavaDoc d = (Element JavaDoc) doc.getElementsByTagName("d").item(0);
315         Element JavaDoc c = (Element JavaDoc) d.getParentNode();
316         Element JavaDoc d2 = (Element JavaDoc) DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument().importNode(d, true);
317         c.removeChild(d);
318         c.appendChild(doc.importNode(d2, true));
319         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
320         XMLUtil.write(doc, baos, "UTF-8");
321         String JavaDoc data2 = baos.toString().replaceAll("\r\n", "\n");
322         //System.err.println("normalized data:\n" + ignoreSpaceChanges(data, doctype) + "\nnormalized data2:\n" + ignoreSpaceChanges(data2, doctype));
323
assertEquals("identity replacement should not mess up indentation in \n" + data2, ignoreSpaceChanges(data, doctype), ignoreSpaceChanges(data2, doctype));
324     }
325     private static String JavaDoc ignoreSpaceChanges(String JavaDoc text, String JavaDoc fuzzy) {
326         // Yes this is confusing!
327
// Inner regexp:
328
// Input: <!DOCTYPE p PUBLIC ...>\n
329
// Output: \Q<!DOCTYPE\E\s+\Qp\E\s+\QPUBLIC...>\E\s+\Q\E
330
// Outer regexp:
331
// Input: stuff\n<!DOCTYPE p\nPUBLIC ...>\n\nmore stuff
332
// Output: stuff\n<!DOCTYPE p PUBLIC ...>\nmore stuff
333
String JavaDoc regexp = "\\Q" + fuzzy.replaceAll("\\s+", "\\\\E\\\\s+\\\\Q") + "\\E";
334         //System.err.println("regexp='" + regexp + "' text='" + text + "' fuzzy='" + fuzzy + "' result='" + text.replaceFirst(regexp, "") + "'");
335
return text.replaceFirst(regexp, "");
336     }
337     
338     public void testSignificantWhitespace() throws Exception JavaDoc {
339         String JavaDoc data =
340                 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
341                 "<r>\n" +
342                 " <p>This is <em>not</em> a test!</p>\n" +
343                 "</r>\n";
344         Document JavaDoc doc = XMLUtil.parse(new InputSource JavaDoc(new StringReader JavaDoc(data)), false, false, null, null);
345         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
346         XMLUtil.write(doc, baos, "UTF-8");
347         String JavaDoc data2 = baos.toString().replaceAll("\r\n", "\n");
348         assertEquals("identity replacement should not mess up significant whitespace", data, data2);
349     }
350 }
351
Popular Tags