1   /*
2    * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved.
3    *
4    * This software is open source.
5    * See the bottom of this file for the licence.
6    *
7    * $Id: TestNamespaces.java,v 1.18 2004/08/22 12:19:23 maartenc Exp $
8    */
9   
10  package org.dom4j;
11  
12  import java.io.StringReader;
13  import java.net.URL;
14  import java.util.Iterator;
15  import java.util.List;
16  
17  import javax.xml.parsers.DocumentBuilder;
18  import javax.xml.parsers.DocumentBuilderFactory;
19  
20  import junit.framework.Test;
21  import junit.framework.TestSuite;
22  import junit.textui.TestRunner;
23  
24  import org.dom4j.io.DOMReader;
25  import org.dom4j.io.SAXReader;
26  import org.xml.sax.InputSource;
27  
28  /*** Test the use of namespaces
29    *
30    * @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
31    * @version $Revision: 1.18 $
32    */
33  public class TestNamespaces extends AbstractTestCase {
34  
35      public static void main( String[] args ) {
36          TestRunner.run( suite() );
37      }
38  
39      public static Test suite() {
40          return new TestSuite( TestNamespaces.class );
41      }
42  
43      public TestNamespaces(String name) {
44          super(name);
45      }
46  
47      // Test case(s)
48      //-------------------------------------------------------------------------
49      public void testNamespaces() throws Exception {
50          testNamespaces( document );
51          testNamespaces( saxRoundTrip( document ) );
52          testNamespaces( domRoundTrip( document ) );
53      }
54  
55      public void testNamespaces(Document document) throws Exception {
56          Document doc2 = (Document) document.clone();
57  
58          Element root = doc2.getRootElement();
59          assertNamespace( root.getNamespace(), "", "http://www.w3.org/2001/XMLSchema" );
60          assertEquals( "xmlns=\"http://www.w3.org/2001/XMLSchema\"", root.getNamespace().asXML());
61          assertEquals( "namespace::*[name()='']", root.getNamespace().getPath());
62          assertEquals( "namespace::*[name()='']", root.getNamespace().getUniquePath());
63  
64          List additionalNS = root.additionalNamespaces();
65          assertTrue( "at least one additional namespace", additionalNS != null && additionalNS.size() > 0 );
66  
67          Namespace ns = (Namespace) additionalNS.get(0);
68          assertNamespace( ns, "t", "http://www.w3.org/namespace/" );
69          assertEquals( "xmlns:t=\"http://www.w3.org/namespace/\"", ns.asXML());
70          assertEquals( "namespace::t", ns.getPath());
71          assertEquals( "namespace::t", ns.getUniquePath());
72  
73          Node node = root.node(0);
74          assertTrue( "First node is a namespace", node instanceof Namespace );
75  
76          // now lets try change the namespace
77          root.remove(ns);
78          root.addNamespace( "t", "myNewURI" );
79  
80          additionalNS = root.additionalNamespaces();
81          assertTrue( "at least one additional namespace", additionalNS != null && additionalNS.size() > 0 );
82  
83          ns = (Namespace) additionalNS.get(0);
84          assertNamespace( ns, "t", "myNewURI" );
85  
86          // lets test the list is backed
87          additionalNS.remove(0);
88          additionalNS.add( Namespace.get("t", "myNewURI-2" ) );
89  
90          additionalNS = root.additionalNamespaces();
91          assertTrue( "at least one additional namespace", additionalNS != null && additionalNS.size() > 0 );
92  
93          ns = (Namespace) additionalNS.get(0);
94          assertNamespace( ns, "t", "myNewURI-2" );
95  
96          additionalNS.clear();
97          root.addNamespace( "t", "myNewURI" );
98  
99          additionalNS = root.additionalNamespaces();
100         assertTrue( "at least one additional namespace", additionalNS != null && additionalNS.size() > 0 );
101 
102         ns = (Namespace) additionalNS.get(0);
103         assertNamespace( ns, "t", "myNewURI" );
104 
105 
106         log( "Namespaces: " + additionalNS );
107         log( "XML is now" );
108         log( root.asXML() );
109     }
110 
111     public void testNamespaceForPrefix() throws Exception {
112         testNamespaceForPrefix( document );
113         testNamespaceForPrefix( saxRoundTrip( document ) );
114         testNamespaceForPrefix( domRoundTrip( document ) );
115     }
116 
117     public void testNamespaceForPrefix(Document document) throws Exception {
118         Element root = document.getRootElement();
119         Namespace ns = root.getNamespaceForPrefix( "t" );
120 
121         assertNamespace( ns, "t", "http://www.w3.org/namespace/" );
122 
123         Element element = (Element) root.elements().get(0);
124         Namespace ns2 = element.getNamespaceForPrefix( "t" );
125 
126         assertNamespace( ns2, "t", "http://www.w3.org/namespace/" );
127         assertTrue( "Same namespace instance returned", ns == ns2 );
128 
129         log( "found: " + ns.asXML() );
130     }
131 
132     public void testNamespaceForDefaultPrefix() throws Exception {
133         SAXReader reader = new SAXReader();
134         URL url = getClass().getResource("/xml/test/defaultNamespace.xml");
135         Document document = reader.read(url);
136 
137         testNamespaceForDefaultPrefix( document );
138         testNamespaceForDefaultPrefix( saxRoundTrip( document ) );
139         testNamespaceForDefaultPrefix( domRoundTrip( document ) );
140     }
141 
142     public void testNamespaceForDefaultPrefix(Document document) throws Exception {
143         List list = document.selectNodes( "//*" );
144 
145         for ( Iterator iter = list.iterator(); iter.hasNext(); ) {
146             Element element = (Element) iter.next();
147             Namespace ns = element.getNamespaceForPrefix( "" );
148             assertNamespace( ns, "", "dummyNamespace" );
149             ns = element.getNamespaceForPrefix( null );
150             assertNamespace( ns, "", "dummyNamespace" );
151             log( "found: " + ns.asXML() );
152         }
153     }
154 
155     public void testAttributeDefaultPrefix() throws Exception {
156         SAXReader reader = new SAXReader();
157         URL url = getClass().getResource("/xml/test/soap3.xml");
158         Document document = reader.read(url);
159 
160         testAttributeDefaultPrefix( document );
161         testAttributeDefaultPrefix( saxRoundTrip( document ) );
162         testAttributeDefaultPrefix( domRoundTrip( document ) );
163     }
164 
165     public void testAttributeDefaultPrefix(Document document) throws Exception {
166         List list = document.selectNodes( "//@*[local-name()='actor']" );
167 
168         assertTrue( "Matched at least one 'actor' attribute", list.size() > 0 );
169 
170         for ( Iterator iter = list.iterator(); iter.hasNext(); ) {
171             Attribute attribute = (Attribute) iter.next();
172 
173             log( "found: " + attribute.asXML() );
174 
175             Element element = attribute.getParent();
176             assertTrue( "Attribute has a parent", element != null );
177 
178             Namespace ns = element.getNamespaceForPrefix( "" );
179 
180             assertNamespace( ns, "", "http://schemas.xmlsoap.org/soap/envelope/" );
181 
182             Namespace ns2 = attribute.getNamespace();
183 
184             // Note that namespaces do not inherit the default namespace!
185             assertNamespace( ns2, "", "" );
186             //assertNamespace( ns2, "", "http://schemas.xmlsoap.org/soap/envelope/" );
187         }
188     }
189 
190     public void testNamespaceForURI() throws Exception {
191         testNamespaceForURI(document);
192         testNamespaceForURI( saxRoundTrip( document ) );
193         testNamespaceForURI( domRoundTrip( document ) );
194     }
195 
196     public void testNamespaceForURI(Document document) throws Exception {
197         Element root = document.getRootElement();
198 
199         Namespace ns = root.getNamespaceForURI( "http://www.w3.org/namespace/" );
200 
201         assertNamespace( ns, "t", "http://www.w3.org/namespace/" );
202 
203         Element element = (Element) root.elements().get(0);
204         Namespace ns2 = element.getNamespaceForURI( "http://www.w3.org/namespace/" );
205 
206         assertNamespace( ns2, "t", "http://www.w3.org/namespace/" );
207 
208         assertTrue( "Same namespace instance returned", ns == ns2 );
209 
210         log( "found: " + ns.asXML() );
211     }
212 
213 
214     public void testRedeclareNamespaces() throws Exception {
215         SAXReader reader = new SAXReader();
216         URL url = getClass().getResource("/xml/test/soap2.xml");
217         Document document = reader.read(url);
218         testRedeclareNamespaces( document );
219         testRedeclareNamespaces( saxRoundTrip( document ) );
220         testRedeclareNamespaces( domRoundTrip( document ) );
221     }
222 
223     public void testRedeclareNamespaces(Document document) throws Exception {
224         assertNamespaces(
225             document.selectNodes( "//*[local-name()='Envelope']" ),
226             "SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/"
227         );
228         assertNamespaces(
229             document.selectNodes( "//*[local-name()='Body']" ),
230             "SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/"
231         );
232         assertNamespaces(
233             document.selectNodes( "//*[local-name()='bar']" ),
234             "a", "barURI"
235         );
236         assertNamespaces(
237             document.selectNodes( "//*[local-name()='newBar']" ),
238             "a", "newBarURI"
239         );
240         assertNamespaces(
241             document.selectNodes( "//*[local-name()='foo']" ),
242             "", "fooURI"
243         );
244         assertNamespaces(
245             document.selectNodes( "//*[local-name()='newFoo']" ),
246             "", "newFooURI"
247         );
248     }
249 
250     public void testDefaultNamespaceIssue() throws Exception {
251         SAXReader reader = new SAXReader();
252         URL url = getClass().getResource("/xml/test/defaultNamespaceIssue.xsd");
253         Document document = reader.read(url);
254         testDefaultNamespaceIssue( document );
255         testDefaultNamespaceIssue( saxRoundTrip( document ) );
256         testDefaultNamespaceIssue( domRoundTrip( document ) );
257     }
258 
259     public void testDefaultNamespaceIssue(Document document) throws Exception {
260         // When writing documents using a default namespace with XMLWriter
261         // a redeclaration of the default namespace to "" was dropped in the output.
262         // Test that <xsd:schema><xsd:element><xsd:annotation><xsd:documentation><text> 
263         // is in no namespace.
264         assertNotNull("default namespace redeclaration", (Element)document.selectSingleNode(
265             "/xsd:schema/xsd:element/xsd:annotation/xsd:documentation/text"));
266 
267         // The test document has a default namespace declaration on the root
268         // element ("schema"), but the element itself is not in the default
269         // namespace. Test that declaredNamespaces on the root element also
270         // returns the default namespace declaration.
271         Iterator iter = document.getRootElement().declaredNamespaces().iterator();
272             while (iter.hasNext()) {
273                 Namespace ns = (Namespace)iter.next();
274                     if ("urn:wapforum:devicesheet".equals(ns.getURI())
275                         && "".equals(ns.getPrefix())) {
276                         return;
277                     }
278             }
279         fail("Default namespace declaration not present on root element");
280     }
281     
282     public void testDefaultNamespace() throws Exception {
283     	Document doc = DocumentHelper.createDocument(); 	
284     	Element processDef = doc.addElement("process-definition", "http://jbpm.org/statedefinition-2.0-beta3");
285     	Element startState = processDef.addElement("start-state");
286     	startState.addAttribute("name", "start");
287     	Element transition = startState.addElement("transition");
288     	transition.addAttribute("to", "first");
289     	
290     	assertEquals("http://jbpm.org/statedefinition-2.0-beta3", startState.getNamespace().getURI());
291     	assertEquals("", startState.getNamespace().getPrefix());
292     	
293     	System.out.println(doc.asXML());
294     }
295 
296     // Implementation methods
297     //-------------------------------------------------------------------------
298     protected void setUp() throws Exception {
299         SAXReader reader = new SAXReader();
300         URL url = getClass().getResource("/xml/test/test_schema.xml");
301         if (url != null) {
302         	document = reader.read(url);
303         }
304     }
305 
306     protected Document saxRoundTrip(Document document) throws Exception {
307         return DocumentHelper.parseText( document.asXML() );
308     }
309 
310     protected Document domRoundTrip(Document document) throws Exception {
311         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
312         factory.setNamespaceAware( true );
313         DocumentBuilder builder = factory.newDocumentBuilder();
314         org.w3c.dom.Document domDocument = builder.parse( new InputSource( new StringReader( document.asXML() ) ) );
315 
316         // now lets read it back as a DOM4J object
317         DOMReader domReader = new DOMReader();
318         return domReader.read( domDocument );
319     }
320 
321     protected void assertNamespaces( List elements, String prefix, String uri ) throws Exception {
322         log( "Validating: " + elements.size() + " element(s) are in URI: " + uri );
323         for ( Iterator iter = elements.iterator(); iter.hasNext(); ) {
324             Element element = (Element) iter.next();
325             assertNamespace( element.getNamespace(), prefix, uri );
326         }
327     }
328 
329     protected void assertNamespace(Namespace ns, String prefix, String uri) throws Exception {
330         assertEquals( "namespace prefix", prefix, ns.getPrefix() );
331         assertEquals( "namespace URI", uri, ns.getURI() );
332     }
333 }
334 
335 
336 
337 
338 /*
339  * Redistribution and use of this software and associated documentation
340  * ("Software"), with or without modification, are permitted provided
341  * that the following conditions are met:
342  *
343  * 1. Redistributions of source code must retain copyright
344  *    statements and notices.  Redistributions must also contain a
345  *    copy of this document.
346  *
347  * 2. Redistributions in binary form must reproduce the
348  *    above copyright notice, this list of conditions and the
349  *    following disclaimer in the documentation and/or other
350  *    materials provided with the distribution.
351  *
352  * 3. The name "DOM4J" must not be used to endorse or promote
353  *    products derived from this Software without prior written
354  *    permission of MetaStuff, Ltd.  For written permission,
355  *    please contact dom4j-info@metastuff.com.
356  *
357  * 4. Products derived from this Software may not be called "DOM4J"
358  *    nor may "DOM4J" appear in their names without prior written
359  *    permission of MetaStuff, Ltd. DOM4J is a registered
360  *    trademark of MetaStuf, Ltd.
361  *
362  * 5. Due credit should be given to the DOM4J Project - 
363  *    http://www.dom4j.org
364  *
365  * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS
366  * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
367  * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
368  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
369  * METASTUFF, LTD. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
370  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
371  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
372  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
373  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
374  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
375  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
376  * OF THE POSSIBILITY OF SUCH DAMAGE.
377  *
378  * Copyright 2001-2004 (C) MetaStuff, Ltd. All Rights Reserved.
379  *
380  * $Id: TestNamespaces.java,v 1.18 2004/08/22 12:19:23 maartenc Exp $
381  */