1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    * 
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   * 
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */ 
17  package org.apache.commons.betwixt.io;
18  
19  import java.io.StringReader;
20  import java.io.StringWriter;
21  
22  import javax.xml.parsers.DocumentBuilder;
23  import javax.xml.parsers.DocumentBuilderFactory;
24  
25  import junit.framework.Test;
26  import junit.framework.TestSuite;
27  import junit.textui.TestRunner;
28  
29  import org.apache.commons.betwixt.AbstractTestCase;
30  import org.apache.commons.betwixt.PersonBean;
31  import org.w3c.dom.Document;
32  import org.w3c.dom.Element;
33  import org.w3c.dom.Node;
34  import org.w3c.dom.NodeList;
35  import org.xml.sax.Attributes;
36  import org.xml.sax.InputSource;
37  import org.xml.sax.helpers.DefaultHandler;
38  
39  /** 
40   * Test harness for SAXBeanWriter.
41   * 
42   * @author <a href="mailto:contact@hdietrich.net">Harald Dietrich</a>
43   * @author <a href="mailto:martin@mvdb.net">Martin van den Bemt</a>
44   * @version $Id: TestSAXBeanWriter.java 438373 2006-08-30 05:17:21Z bayard $
45   */
46  public class TestSAXBeanWriter extends AbstractTestCase {
47      
48      public static final String XML = "<?xml version='1.0'?><PersonBean id='1'><age>35</age><name>John Smith</name></PersonBean>";
49  
50      public TestSAXBeanWriter(String name) {
51          super(name);
52      }
53  
54      public void testWrite() throws Exception {
55          PersonBean bean = new PersonBean(35, "John Smith");
56  
57          // writer bean into string
58          StringWriter out = new StringWriter();
59          
60          //SimpleLog log = new SimpleLog("[TestWrite:SAXBeanWriter]");
61          //log.setLevel(SimpleLog.LOG_LEVEL_TRACE);
62          
63          SAXBeanWriter writer = new SAXBeanWriter(new SAXContentHandler(out));
64          //writer.setLog(log);
65  		writer.getBindingConfiguration().setMapIDs(false);
66          writer.write(bean);
67          String beanString = out.getBuffer().toString();
68          String xml = "<?xml version='1.0'?><PersonBean><age>35</age>"
69                  + "<name>John Smith</name></PersonBean>";
70                  
71                          
72          xmlAssertIsomorphicContent(
73                      parseString(xml),
74                      parseString(beanString),
75                      true);
76       
77          // test the result
78          DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
79          DocumentBuilder builder = factory.newDocumentBuilder();
80          factory.setIgnoringElementContentWhitespace(true);
81          InputSource in = new InputSource();
82          StringReader reader = new StringReader(beanString);
83          in.setCharacterStream(reader);
84          Document doc = builder.parse(in);
85          assertNotNull("Document missing", doc);        
86          Element root = doc.getDocumentElement();
87          assertNotNull("Document root missing", root);
88          assertEquals("Document root name wrong", "PersonBean", root.getNodeName());
89          NodeList children = root.getChildNodes();       
90          for (int i = 0; i < children.getLength(); i++) {
91              Node child = children.item(i);
92              if (child.getNodeName().equals("age")) {
93                  assertNotNull("Person age missing", child.getFirstChild());
94                  assertEquals("Person age wrong", "35", child.getFirstChild().getNodeValue().trim());
95              } else if (child.getNodeName().equals("name")) {
96                  assertNotNull("Person name missing", child.getFirstChild());
97                  assertEquals("Person name wrong", "John Smith", child.getFirstChild().getNodeValue().trim());
98              } else {
99                  if (child.getNodeName().equals("#text")) {
100                     // now check if the textNode is empty after a trim.
101                     String value = child.getNodeValue();
102                     if (value != null) {
103                         value = value.trim();
104                     }
105                     if (value.length() != 0) {
106                         fail("Text should not contain content in node " + child.getNodeName());
107                     }
108                 }else{
109                     fail("Invalid node " + child.getNodeName());
110                 }
111                 
112             }
113         }
114     }       
115         
116     public void testDocumentElements() throws Exception {
117         
118         class TestDocHandler extends DefaultHandler {
119             
120             boolean startCalled = false;
121             boolean endCalled = false;
122             
123             public void startDocument() {
124                 startCalled = true;
125             }	
126             
127             public void endDocument() {
128                 endCalled = true;
129             }
130             
131         }
132         
133         PersonBean bean = new PersonBean(35, "John Smith");
134         
135         TestDocHandler handler = new TestDocHandler();
136         SAXBeanWriter writer = new SAXBeanWriter(handler);
137         writer.setCallDocumentEvents(true);
138         writer.write(bean);
139         
140         assertEquals("Start not called", handler.startCalled , true); 
141         assertEquals("End not called", handler.endCalled , true); 
142         
143         handler = new TestDocHandler();
144         writer = new SAXBeanWriter(handler);
145         writer.setCallDocumentEvents(false);
146         writer.write(bean);
147         
148         assertEquals("Start called", handler.startCalled , false); 
149         assertEquals("End called", handler.endCalled , false);     
150     }
151     
152     /** This tests whether local names and qNames match */
153     public void testLocalNames() throws Exception {
154     
155         class TestNames extends DefaultHandler {
156             boolean namesMatch = true;
157             
158             public void startElement(String uri, String localName, String qName, Attributes attributes) {
159                 if (!localName.equals(qName)) {
160                     namesMatch = false;
161                 }
162                 
163                 for (int i=0, size=attributes.getLength(); i<size; i++) {
164                     if (!attributes.getLocalName(i).equals(attributes.getQName(i))) {
165                         namesMatch = false;
166                     }
167                 }
168             }
169             
170             public void endElement(String uri, String localName, String qName) {
171                 if (!localName.equals(qName)) {
172                     namesMatch = false;
173                 }
174             }
175         }
176         
177         PersonBean bean = new PersonBean(24, "vikki");
178         TestNames testHandler = new TestNames();
179         SAXBeanWriter writer = new SAXBeanWriter(testHandler);
180         writer.write(bean);
181         
182         assertEquals("Local names match QNames", testHandler.namesMatch, true);
183     }
184     
185         
186     public static Test suite() {
187         return new TestSuite(TestSAXBeanWriter.class);
188     }    
189     
190     public static void main(String[] args) {
191         TestRunner.run(suite());
192     }
193 }