1   /*
2    * Copyright 2001-2004 The Apache Software Foundation.
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   
17  package org.apache.commons.betwixt.introspection;
18  
19  import java.beans.BeanInfo;
20  import java.beans.Introspector;
21  import java.beans.PropertyDescriptor;
22  import java.io.StringWriter;
23  
24  import junit.framework.Test;
25  import junit.framework.TestSuite;
26  import junit.textui.TestRunner;
27  
28  import org.apache.commons.betwixt.AbstractTestCase;
29  import org.apache.commons.betwixt.AttributeDescriptor;
30  import org.apache.commons.betwixt.ElementDescriptor;
31  import org.apache.commons.betwixt.XMLBeanInfo;
32  import org.apache.commons.betwixt.XMLIntrospector;
33  import org.apache.commons.betwixt.io.BeanWriter;
34  import org.apache.commons.betwixt.registry.DefaultXMLBeanInfoRegistry;
35  import org.apache.commons.betwixt.registry.NoCacheRegistry;
36  import org.apache.commons.betwixt.strategy.ClassNormalizer;
37  import org.apache.commons.betwixt.strategy.ListedClassNormalizer;
38  import org.apache.commons.digester.rss.Channel;
39  
40  
41  /*** Test harness for the XMLIntrospector
42    *
43    * @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
44    * @version $Revision: 155402 $
45    */
46  public class TestXMLIntrospector extends AbstractTestCase {
47      
48      public static void main( String[] args ) {
49          TestRunner.run( suite() );
50      }
51      
52      public static Test suite() {
53          return new TestSuite(TestXMLIntrospector.class);
54      }
55          
56      public TestXMLIntrospector(String testName) {
57          super(testName);
58      }
59      
60      public void testIntrospector() throws Exception {
61          //SimpleLog log = new SimpleLog("testIntrospector:introspector");
62          //log.setLevel(SimpleLog.LOG_LEVEL_TRACE);
63          XMLIntrospector introspector = new XMLIntrospector();
64          //introspector.setLog(log);
65          
66          introspector.getConfiguration().setAttributesForPrimitives(true);
67          
68          Object bean = createBean();
69          
70          XMLBeanInfo info = introspector.introspect( bean );
71          
72          assertTrue( "Found XMLBeanInfo", info != null );
73          
74          ElementDescriptor descriptor = info.getElementDescriptor();
75          
76          assertTrue( "Found root element descriptor", descriptor != null );
77          
78          AttributeDescriptor[] attributes = descriptor.getAttributeDescriptors();
79          
80          assertTrue( "Found attributes", attributes != null && attributes.length > 0 );
81          
82          // test second introspection with caching on
83          info = introspector.introspect( bean );
84          
85          assertTrue( "Found XMLBeanInfo", info != null );
86          
87          descriptor = info.getElementDescriptor();
88          
89          assertTrue( "Found root element descriptor", descriptor != null );
90          
91          attributes = descriptor.getAttributeDescriptors();
92          
93          assertTrue( "Found attributes", attributes != null && attributes.length > 0 );
94  
95  
96          // test introspection with caching off      
97          //introspector.setCachingEnabled(false);  
98          introspector.setRegistry(new NoCacheRegistry());
99          info = introspector.introspect( bean );
100         
101         assertTrue( "Found XMLBeanInfo", info != null );
102         
103         descriptor = info.getElementDescriptor();
104         
105         assertTrue( "Found root element descriptor", descriptor != null );
106         
107         attributes = descriptor.getAttributeDescriptors();
108         
109         assertTrue( "Found attributes", attributes != null && attributes.length > 0 );
110 
111 
112         // test introspection after flushing cache
113 //        introspector.setCachingEnabled(true);
114         introspector.setRegistry(new DefaultXMLBeanInfoRegistry()); 
115         //introspector.flushCache();
116         info = introspector.introspect( bean );
117         
118         assertTrue( "Found XMLBeanInfo", info != null );
119         
120         descriptor = info.getElementDescriptor();
121         
122         assertTrue( "Found root element descriptor", descriptor != null );
123         
124         attributes = descriptor.getAttributeDescriptors();
125         
126         assertTrue( "Found attributes", attributes != null && attributes.length > 0 );
127 
128     }
129     
130     public void testBeanWithBeanInfo() throws Exception {
131         
132         // let's check that bean info's ok
133         BeanInfo bwbiBeanInfo = Introspector.getBeanInfo(BeanWithBeanInfoBean.class);
134         
135         PropertyDescriptor[] propertyDescriptors = bwbiBeanInfo.getPropertyDescriptors();
136 
137         assertEquals("Wrong number of properties", 2 , propertyDescriptors.length);
138         
139         // order of properties isn't guarenteed 
140         if ("alpha".equals(propertyDescriptors[0].getName())) {
141         
142             assertEquals("Second property name", "gamma" , propertyDescriptors[1].getName());
143             
144         } else {
145         
146             assertEquals("First property name", "gamma" , propertyDescriptors[0].getName());
147             assertEquals("Second property name", "alpha" , propertyDescriptors[1].getName());
148         }
149         
150         // finished with the descriptors
151         propertyDescriptors = null;
152 
153 //        SimpleLog log = new SimpleLog("[testBeanWithBeanInfo:XMLIntrospector]");
154 //        log.setLevel(SimpleLog.LOG_LEVEL_TRACE);
155 
156         XMLIntrospector introspector = new XMLIntrospector();
157         introspector.getConfiguration().setAttributesForPrimitives(false);
158 //        introspector.setLog(log);
159         
160         XMLBeanInfo xmlBeanInfo = introspector.introspect(BeanWithBeanInfoBean.class);
161         
162         ElementDescriptor[] elementDescriptors = xmlBeanInfo.getElementDescriptor().getElementDescriptors();
163         
164 //        log = new SimpleLog("[testBeanWithBeanInfo]");
165 //        log.setLevel(SimpleLog.LOG_LEVEL_DEBUG);
166         
167 //        log.debug("XMLBeanInfo:");
168 //        log.debug(xmlBeanInfo);
169 //        log.debug("Elements:");
170 //        log.debug(elementDescriptors[0].getPropertyName());
171 //        log.debug(elementDescriptors[1].getPropertyName());
172         
173         assertEquals("Wrong number of elements", 2 , elementDescriptors.length);
174 
175         // order of properties isn't guarenteed 
176         boolean alphaFirst = true;
177         if ("alpha".equals(elementDescriptors[0].getPropertyName())) {
178             
179             assertEquals("Second element name", "gamma" , elementDescriptors[1].getPropertyName());
180             
181         } else {
182             alphaFirst = false;
183             assertEquals("First element name", "gamma" , elementDescriptors[0].getPropertyName());
184             assertEquals("Second element name", "alpha" , elementDescriptors[1].getPropertyName());
185         }
186         
187         // might as well give test output
188         StringWriter out = new StringWriter();
189         BeanWriter writer = new BeanWriter(out);
190         writer.getBindingConfiguration().setMapIDs(false);
191         BeanWithBeanInfoBean bean = new BeanWithBeanInfoBean("alpha value","beta value","gamma value");
192         writer.write(bean);
193         
194         if (alphaFirst) {
195         
196             xmlAssertIsomorphicContent(
197                     parseFile("src/test/org/apache/commons/betwixt/introspection/test-bwbi-output-a.xml"),
198                     parseString(out.toString()));
199         
200         } else {
201             xmlAssertIsomorphicContent(
202                     parseFile("src/test/org/apache/commons/betwixt/introspection/test-bwbi-output-g.xml"),
203                     parseString(out.toString()));
204         }
205     }
206     
207     public void testDefaultClassNormalizer() throws Exception {
208         XMLIntrospector introspector = new XMLIntrospector();
209         
210         FaceImpl face = new FaceImpl();
211         XMLBeanInfo info = introspector.introspect( face );
212         ElementDescriptor elementDescriptor = info.getElementDescriptor();
213     
214         AttributeDescriptor[] attributeDescriptor = elementDescriptor.getAttributeDescriptors();      
215         ElementDescriptor[] children = elementDescriptor.getElementDescriptors();
216         
217         assertEquals("Expected no attributes", 0, attributeDescriptor.length);
218         assertEquals("Expected two elements", 2, children.length);
219     }	
220     
221     public void testClassNormalizer() throws Exception {
222         XMLIntrospector introspector = new XMLIntrospector();
223         introspector.getConfiguration().setClassNormalizer( new ClassNormalizer() {
224                 
225                 public Class normalize(Class clazz) {
226                     if (IFace.class.isAssignableFrom( clazz )) {
227                         return IFace.class;
228                     }	
229                     return super.normalize( clazz );
230                 }	
231             });
232         
233         FaceImpl face = new FaceImpl();
234         XMLBeanInfo info = introspector.introspect( face );
235         ElementDescriptor elementDescriptor = info.getElementDescriptor();
236         assertEquals("Expected only itself", 1, elementDescriptor.getElementDescriptors().length);
237     
238         AttributeDescriptor[] attributeDescriptor = elementDescriptor.getAttributeDescriptors();      
239         ElementDescriptor[] children = elementDescriptor.getElementDescriptors();
240         
241         assertEquals("Expected no attributes", 0, attributeDescriptor.length);
242         assertEquals("Expected one elements", 1, children.length);
243         assertEquals("Expected element", "name", children[0].getLocalName());
244     }	
245     
246     public void testListedClassNormalizer() throws Exception {
247         ListedClassNormalizer classNormalizer = new ListedClassNormalizer();
248         classNormalizer.addSubstitution( IFace.class );
249         XMLIntrospector introspector = new XMLIntrospector();
250         introspector.getConfiguration().setClassNormalizer(classNormalizer);
251         
252         FaceImpl face = new FaceImpl();
253         
254         XMLBeanInfo info = introspector.introspect( face );
255         ElementDescriptor elementDescriptor = info.getElementDescriptor();
256         AttributeDescriptor[] attributeDescriptor = elementDescriptor.getAttributeDescriptors();      
257         ElementDescriptor[] children = elementDescriptor.getElementDescriptors();
258         
259         assertEquals("Expected no attributes", 0, attributeDescriptor.length);
260         assertEquals("Expected one elements", 1, children.length);
261         assertEquals("Expected element", "name", children[0].getLocalName());
262     }	    
263     
264     public void testListedClassNormalizerWrite() throws Exception {
265         ListedClassNormalizer classNormalizer = new ListedClassNormalizer();
266         classNormalizer.addSubstitution( IFace.class );
267         
268         StringWriter out = new StringWriter();
269         out.write("<?xml version='1.0'?>");
270         BeanWriter writer = new BeanWriter( out );
271 		writer.getBindingConfiguration().setMapIDs(false);
272         writer.getXMLIntrospector().getConfiguration().setClassNormalizer( classNormalizer );
273         FaceImpl bean = new FaceImpl();
274         bean.setName("Old Tom Cobbly");
275         writer.write(bean);
276         
277         String xml="<?xml version='1.0'?><IFace><name>Old Tom Cobbly</name></IFace>";
278         xmlAssertIsomorphicContent(
279                             parseString(out.getBuffer().toString()),
280                             parseString(xml), 
281                             true);
282     }	
283     
284     public void testBetwixtFileType() throws Exception {
285     	XMLIntrospector introspector = new XMLIntrospector();
286     	XMLBeanInfo info = introspector.introspect( Channel.class );
287     	
288     	ElementDescriptor elementDescriptor = info.getElementDescriptor();
289     	
290 		Class clazz = elementDescriptor.getSingularPropertyType();
291 		assertEquals( "Element type correct", Channel.class , clazz);
292 		
293 		assertEquals( "Element name correct", "rss", elementDescriptor.getLocalName());
294     }
295     
296 
297 }
298