Source Code Cross Referenced for TestBeanReader.java in  » Library » Apache-commons-betwixt-0.8-src » org » apache » commons » betwixt » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Library » Apache commons betwixt 0.8 src » org.apache.commons.betwixt 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * Licensed to the Apache Software Foundation (ASF) under one or more
003:         * contributor license agreements.  See the NOTICE file distributed with
004:         * this work for additional information regarding copyright ownership.
005:         * The ASF licenses this file to You under the Apache License, Version 2.0
006:         * (the "License"); you may not use this file except in compliance with
007:         * the License.  You may obtain a copy of the License at
008:         * 
009:         *      http://www.apache.org/licenses/LICENSE-2.0
010:         * 
011:         * Unless required by applicable law or agreed to in writing, software
012:         * distributed under the License is distributed on an "AS IS" BASIS,
013:         * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014:         * See the License for the specific language governing permissions and
015:         * limitations under the License.
016:         */
017:
018:        package org.apache.commons.betwixt;
019:
020:        import java.io.FileInputStream;
021:        import java.io.IOException;
022:        import java.io.InputStream;
023:        import java.io.StringReader;
024:        import java.io.StringWriter;
025:        import java.math.BigDecimal;
026:        import java.math.BigInteger;
027:        import java.sql.Date;
028:        import java.sql.Time;
029:        import java.sql.Timestamp;
030:        import java.text.ParseException;
031:        import java.text.SimpleDateFormat;
032:        import java.util.ArrayList;
033:        import java.util.Calendar;
034:        import java.util.Iterator;
035:        import java.util.List;
036:
037:        import junit.framework.Test;
038:        import junit.framework.TestSuite;
039:        import junit.textui.TestRunner;
040:
041:        import org.apache.commons.beanutils.ConversionException;
042:        import org.apache.commons.beanutils.ConvertUtils;
043:        import org.apache.commons.beanutils.Converter;
044:        import org.apache.commons.betwixt.io.BeanReader;
045:        import org.apache.commons.betwixt.io.BeanWriter;
046:        import org.apache.commons.betwixt.strategy.ConvertUtilsObjectStringConverter;
047:        import org.apache.commons.betwixt.strategy.HyphenatedNameMapper;
048:        import org.apache.commons.digester.ExtendedBaseRules;
049:        import org.apache.commons.digester.Rule;
050:        import org.xml.sax.Attributes;
051:
052:        /** Test harness for the BeanReader
053:         *
054:         * @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
055:         * @version $Revision: 438373 $
056:         */
057:        public class TestBeanReader extends AbstractTestCase {
058:
059:            public static void main(String[] args) {
060:                TestRunner.run(suite());
061:            }
062:
063:            public static Test suite() {
064:                return new TestSuite(TestBeanReader.class);
065:            }
066:
067:            public TestBeanReader(String testName) {
068:                super (testName);
069:            }
070:
071:            public void testBeanWriter() throws Exception {
072:                BeanReader reader = new BeanReader();
073:                reader.registerBeanClass(getBeanClass());
074:
075:                InputStream in = getXMLInput();
076:                try {
077:                    Object bean = reader.parse(in);
078:
079:                    testCustomer(bean);
080:
081:                    String out = writeBean(bean);
082:                    String xml = "<?xml version='1.0'?><CustomerBean><name>James</name><time>20:30:40</time>"
083:                            + "<date>2002-03-17</date><projectMap/><bigDecimal>1234567890.12345</bigDecimal>"
084:                            + "<bigInteger>1234567890</bigInteger><projectNames/><emails>"
085:                            + "<email>jstrachan@apache.org</email><email>james_strachan@yahoo.co.uk</email>"
086:                            + "</emails><timestamp>2002-03-17 20:30:40.0</timestamp><locations>"
087:                            + "<location>London</location><location>Bath</location></locations>"
088:                            + "<ID/><projectURLs/><nickName/><address><code/><country/>"
089:                            + "<city/><street/></address><numbers><number>3</number><number>4</number>"
090:                            + "<number>5</number></numbers></CustomerBean>";
091:
092:                    xmlAssertIsomorphic(parseString(xml), parseString(out),
093:                            true);
094:                } finally {
095:                    in.close();
096:                }
097:            }
098:
099:            public void testWriteThenRead() throws Exception {
100:                // test defaults
101:                PersonBean bean = new PersonBean(21, "Samual Smith");
102:                StringWriter stringWriter = new StringWriter();
103:                BeanWriter beanWriter = new BeanWriter(stringWriter);
104:                beanWriter.write(bean);
105:                stringWriter.flush();
106:                String xml = "<?xml version='1.0'?>" + stringWriter.toString();
107:
108:                BeanReader reader = new BeanReader();
109:                reader.registerBeanClass(PersonBean.class);
110:                bean = (PersonBean) reader.parse(new StringReader(xml));
111:
112:                assertEquals("Person age wrong", 21, bean.getAge());
113:                assertEquals("Person name wrong", "Samual Smith", bean
114:                        .getName());
115:
116:                // test now with attributes for primitives
117:                bean = new PersonBean(19, "John Smith");
118:                stringWriter = new StringWriter();
119:                beanWriter = new BeanWriter(stringWriter);
120:                beanWriter.getXMLIntrospector().getConfiguration()
121:                        .setAttributesForPrimitives(true);
122:                beanWriter.write(bean);
123:                stringWriter.flush();
124:                xml = "<?xml version='1.0'?>" + stringWriter.toString();
125:
126:                reader = new BeanReader();
127:                reader.getXMLIntrospector().getConfiguration()
128:                        .setAttributesForPrimitives(true);
129:                reader.registerBeanClass(PersonBean.class);
130:                bean = (PersonBean) reader.parse(new StringReader(xml));
131:
132:                assertEquals("[Attribute] Person age wrong", 19, bean.getAge());
133:                assertEquals("[Attribute] Person name wrong", "John Smith",
134:                        bean.getName());
135:            }
136:
137:            public String writeBean(Object bean) throws Exception {
138:                StringWriter out = new StringWriter();
139:                out.write("<?xml version='1.0'?>");
140:                BeanWriter writer = new BeanWriter(out);
141:                writer.getBindingConfiguration().setMapIDs(false);
142:                writer.setEndOfLine("\n");
143:                writer.enablePrettyPrint();
144:                writer.write(bean);
145:                return out.getBuffer().toString();
146:            }
147:
148:            /** @return the bean class to use as the root */
149:            public Class getBeanClass() {
150:                return CustomerBean.class;
151:            }
152:
153:            /** 
154:             * Asserts that the parsed CustomerBean looks fine
155:             */
156:            protected void testCustomer(Object bean) throws Exception {
157:                assertTrue("Is a CustomerBean", bean instanceof  CustomerBean);
158:                CustomerBean customer = (CustomerBean) bean;
159:
160:                assertEquals("name", "James", customer.getName());
161:
162:                String[] emails = customer.getEmails();
163:                assertTrue("contains some emails", emails != null);
164:                assertEquals("emails.length", 2, emails.length);
165:                assertEquals("emails[0]", "jstrachan@apache.org", emails[0]);
166:                assertEquals("emails[1]", "james_strachan@yahoo.co.uk",
167:                        emails[1]);
168:
169:                int[] numbers = customer.getNumbers();
170:                assertTrue("contains some numbers", numbers != null);
171:                assertEquals("numbers.length", 3, numbers.length);
172:                assertEquals("numbers[0]", 3, numbers[0]);
173:                assertEquals("numbers[1]", 4, numbers[1]);
174:                assertEquals("numbers[2]", 5, numbers[2]);
175:
176:                List locations = customer.getLocations();
177:                assertTrue("contains some locations", locations != null);
178:                assertEquals("locations.size()", 2, locations.size());
179:                assertEquals("locations[0]", "London", locations.get(0));
180:                assertEquals("locations[1]", "Bath", locations.get(1));
181:
182:                assertEquals(ConvertUtils.convert("2002-03-17", Date.class),
183:                        customer.getDate());
184:                assertEquals(ConvertUtils.convert("20:30:40", Time.class),
185:                        customer.getTime());
186:                assertEquals(ConvertUtils.convert("2002-03-17 20:30:40.0",
187:                        Timestamp.class), customer.getTimestamp());
188:
189:                assertEquals(new BigDecimal("1234567890.12345"), customer
190:                        .getBigDecimal());
191:                assertEquals(new BigInteger("1234567890"), customer
192:                        .getBigInteger());
193:            }
194:
195:            protected InputStream getXMLInput() throws IOException {
196:                return new FileInputStream(
197:                        getTestFile("src/test/org/apache/commons/betwixt/customer.xml"));
198:            }
199:
200:            /** 
201:             * This tests that you can read a bean which has an adder but not a property
202:             */
203:            public void testAdderButNoProperty() throws Exception {
204:                /*
205:                // 
206:                // This is a test for an unfixed issue that might - or might not - be a bug
207:                // a developer submitted a patch but this broke the other unit test
208:                // a proper fix would require quite a lot of work including some refactoring
209:                // of various interfaces
210:                //
211:                
212:                // check bean's still working
213:                AdderButNoPropertyBean bean = new AdderButNoPropertyBean();
214:                bean.addString("one");
215:                bean.addString("two");
216:                bean.addString("three");
217:                checkBean(bean);
218:                
219:                BeanReader reader = new BeanReader();
220:                reader.registerBeanClass( AdderButNoPropertyBean.class );
221:                
222:                InputStream in =  
223:                    new FileInputStream( getTestFile("src/test/org/apache/commons/betwixt/adder-np.xml") );
224:                try {
225:                
226:                    checkBean((AdderButNoPropertyBean) reader.parse( in ));
227:                    
228:                }
229:                finally {
230:                    in.close();
231:                }        
232:                 */
233:            }
234:
235:            private void checkBean(AdderButNoPropertyBean bean)
236:                    throws Exception {
237:                assertEquals("Bad addString call count", 3, bean
238:                        .stringCallCount());
239:            }
240:
241:            private void checkBean(PersonListBean bean) throws Exception {
242:                assertEquals("PersonList size", 4, bean.getPersonList().size());
243:                assertEquals("PersonList value (1)", "Athos",
244:                        ((PersonBean) bean.getPersonList().get(0)).getName());
245:                assertEquals("PersonList value (2)", "Porthos",
246:                        ((PersonBean) bean.getPersonList().get(1)).getName());
247:                assertEquals("PersonList value (3)", "Aramis",
248:                        ((PersonBean) bean.getPersonList().get(2)).getName());
249:                assertEquals("PersonList value (4)", "D'Artagnan",
250:                        ((PersonBean) bean.getPersonList().get(3)).getName());
251:            }
252:
253:            public void testPersonList() throws Exception {
254:
255:                PersonListBean people = new PersonListBean();
256:                people.addPerson(new PersonBean(22, "Athos"));
257:                people.addPerson(new PersonBean(25, "Porthos"));
258:                people.addPerson(new PersonBean(23, "Aramis"));
259:                people.addPerson(new PersonBean(18, "D'Artagnan"));
260:
261:                checkBean(people);
262:                //
263:                // Logging and debugging code for this method commented out
264:                //
265:                //        writeBean(people);
266:
267:                //        SimpleLog log = new SimpleLog("[TestPersonList:XMLIntrospectorHelper]");
268:                //        log.setLevel(SimpleLog.LOG_LEVEL_TRACE);
269:                //        XMLIntrospectorHelper.setLog(log);
270:
271:                //        log = new SimpleLog("[TestPersonList:BeanCreateRule]");
272:                //        log.setLevel(SimpleLog.LOG_LEVEL_TRACE);
273:                //        BeanCreateRule.setLog(log);
274:
275:                //        log = new SimpleLog("[TestPersonList:XMLIntrospector]");
276:                //        log.setLevel(SimpleLog.LOG_LEVEL_TRACE);
277:
278:                BeanReader reader = new BeanReader();
279:                //        reader.getXMLIntrospector().setLog(log);
280:
281:                //        log = new SimpleLog("[TestPersonList:BeanReader]");
282:                //        log.setLevel(SimpleLog.LOG_LEVEL_TRACE);
283:
284:                //        reader.setLog(log);
285:                reader.registerBeanClass(PersonListBean.class);
286:
287:                InputStream in = new FileInputStream(
288:                        getTestFile("src/test/org/apache/commons/betwixt/person-list.xml"));
289:                try {
290:
291:                    checkBean((PersonListBean) reader.parse(in));
292:
293:                } finally {
294:                    in.close();
295:                }
296:            }
297:
298:            /** Another test for reading wrapped collections */
299:            public void testWrapElements() throws Exception {
300:                ListOfNames listOfNames = new ListOfNames();
301:                listOfNames.addName(new NameBean("Martin"));
302:
303:                String xml = "<ListOfNames><names><name name='Martin'/></names></ListOfNames>";
304:
305:                BeanReader reader = new BeanReader();
306:                reader.getXMLIntrospector().getConfiguration()
307:                        .setAttributesForPrimitives(true);
308:                reader.getXMLIntrospector().getConfiguration()
309:                        .setWrapCollectionsInElement(true);
310:
311:                reader.registerBeanClass(ListOfNames.class);
312:                ListOfNames newListOfNames = (ListOfNames) reader
313:                        .parse(new StringReader(xml));
314:
315:                assertEquals("Wrapped collection read fails", listOfNames,
316:                        newListOfNames);
317:            }
318:
319:            public void testSetDigesterRules() throws Exception {
320:                NameBean martinBean = new NameBean("Martin");
321:                ListOfNames listOfNames = new ListOfNames();
322:                listOfNames.addName(martinBean);
323:
324:                String xml = "<ListOfNames><names><name name='Martin'/></names></ListOfNames>";
325:
326:                BeanReader reader = new BeanReader();
327:                reader.setRules(new ExtendedBaseRules());
328:                reader.getXMLIntrospector().getConfiguration()
329:                        .setAttributesForPrimitives(true);
330:                reader.getXMLIntrospector().getConfiguration()
331:                        .setWrapCollectionsInElement(true);
332:
333:                TestRule ruleOne = new TestRule();
334:                TestRule ruleTwo = new TestRule();
335:
336:                // add a test rule before the bean rules
337:                reader.addRule("!*/ListOfNames/names/name", ruleOne);
338:                reader.registerBeanClass(ListOfNames.class);
339:                // add a test rule after the bean rules
340:                reader.addRule("!*/ListOfNames/names/name", ruleTwo);
341:
342:                ListOfNames newListOfNames = (ListOfNames) reader
343:                        .parse(new StringReader(xml));
344:
345:                reader.parse(new StringReader(xml));
346:
347:                // test that the rules were called
348:                assertEquals("Rule one called", true, ruleOne.isCalled());
349:                assertEquals("Rule two called", true, ruleTwo.isCalled());
350:
351:                // test that the top objects are correct
352:                assertEquals("Rule one digester top object", listOfNames,
353:                        ruleOne.getTop());
354:                assertEquals("Rule two digester top object", martinBean,
355:                        ruleTwo.getTop());
356:            }
357:
358:            public void testDateReadConversion() throws Exception {
359:                Calendar calendar = Calendar.getInstance();
360:                calendar.set(2003, 7, 2, 19, 30, 00);
361:                java.util.Date date = calendar.getTime();
362:
363:                String dateToString = date.toString();
364:
365:                PartyBean bean = new PartyBean("Wedding", date, 1930,
366:                        new AddressBean("Old White Lion Hotel", "Howarth",
367:                                "Merry Old England", "BD22 8EP"));
368:
369:                StringWriter out = new StringWriter();
370:                out.write("<?xml version='1.0'?>");
371:
372:                BeanWriter writer = new BeanWriter(out);
373:                writer.getBindingConfiguration().setMapIDs(false);
374:                XMLIntrospector introspector = writer.getXMLIntrospector();
375:                introspector.getConfiguration().setElementNameMapper(
376:                        new HyphenatedNameMapper());
377:                introspector.getConfiguration().setAttributesForPrimitives(
378:                        false);
379:
380:                writer.write("party", bean);
381:
382:                String xml = "<?xml version='1.0'?><party>"
383:                        + "<venue><street>Old White Lion Hotel</street><city>Howarth</city>"
384:                        + "<code>BD22 8EP</code><country>Merry Old England</country></venue>"
385:                        + "<date-of-party>" + dateToString
386:                        + "</date-of-party><from-hour>1930</from-hour>"
387:                        + "<excuse>Wedding</excuse>" + "</party>";
388:
389:                xmlAssertIsomorphic(parseString(xml), parseString(out), true);
390:
391:                BeanReader reader = new BeanReader();
392:                reader.setXMLIntrospector(introspector);
393:                reader.registerBeanClass("party", PartyBean.class);
394:                PartyBean readBean = (PartyBean) reader.parse(new StringReader(
395:                        xml));
396:
397:                assertEquals("FromHours incorrect property value", readBean
398:                        .getFromHour(), bean.getFromHour());
399:                assertEquals("Excuse incorrect property value", readBean
400:                        .getExcuse(), bean.getExcuse());
401:
402:                // check address
403:                AddressBean readAddress = readBean.getVenue();
404:                AddressBean address = bean.getVenue();
405:                assertEquals("address.street incorrect property value",
406:                        readAddress.getStreet(), address.getStreet());
407:                assertEquals("address.city incorrect property value",
408:                        readAddress.getCity(), address.getCity());
409:                assertEquals("address.code incorrect property value",
410:                        readAddress.getCode(), address.getCode());
411:                assertEquals("address.country incorrect property value",
412:                        readAddress.getCountry(), address.getCountry());
413:
414:                // check dates
415:                assertEquals("Incorrect date property", date.toGMTString(),
416:                        readBean.getDateOfParty().toGMTString());
417:            }
418:
419:            public void testHyphenatedNameMapping() throws Exception {
420:                Calendar calendar = Calendar.getInstance();
421:                calendar.set(2003, 7, 2, 19, 30, 00);
422:                java.util.Date date = calendar.getTime();
423:
424:                String dateToString = date.toString();
425:
426:                PartyBean bean = new PartyBean("Wedding", date, 1930,
427:                        new AddressBean("Old White Lion Hotel", "Howarth",
428:                                "Merry Old England", "BD22 8EP"));
429:
430:                StringWriter out = new StringWriter();
431:                out.write("<?xml version='1.0'?>");
432:
433:                BeanWriter writer = new BeanWriter(out);
434:                writer.getBindingConfiguration().setMapIDs(false);
435:                XMLIntrospector introspector = writer.getXMLIntrospector();
436:                introspector.getConfiguration().setElementNameMapper(
437:                        new HyphenatedNameMapper());
438:                introspector.getConfiguration().setAttributesForPrimitives(
439:                        false);
440:
441:                writer.write(bean);
442:
443:                String xml = "<?xml version='1.0'?><party-bean>"
444:                        + "<venue><street>Old White Lion Hotel</street><city>Howarth</city>"
445:                        + "<code>BD22 8EP</code><country>Merry Old England</country></venue>"
446:                        + "<date-of-party>" + dateToString
447:                        + "</date-of-party><from-hour>1930</from-hour>"
448:                        + "<excuse>Wedding</excuse>" + "</party-bean>";
449:
450:                xmlAssertIsomorphic(parseString(xml), parseString(out), true);
451:
452:                BeanReader reader = new BeanReader();
453:                reader.setXMLIntrospector(introspector);
454:                reader.registerBeanClass(PartyBean.class);
455:                PartyBean readBean = (PartyBean) reader.parse(new StringReader(
456:                        xml));
457:
458:                assertEquals("FromHours incorrect property value", readBean
459:                        .getFromHour(), bean.getFromHour());
460:                assertEquals("Excuse incorrect property value", readBean
461:                        .getExcuse(), bean.getExcuse());
462:
463:                // check address
464:                AddressBean readAddress = readBean.getVenue();
465:                AddressBean address = bean.getVenue();
466:                assertEquals("address.street incorrect property value",
467:                        readAddress.getStreet(), address.getStreet());
468:                assertEquals("address.city incorrect property value",
469:                        readAddress.getCity(), address.getCity());
470:                assertEquals("address.code incorrect property value",
471:                        readAddress.getCode(), address.getCode());
472:                assertEquals("address.country incorrect property value",
473:                        readAddress.getCountry(), address.getCountry());
474:
475:                // check dates
476:                assertEquals("Incorrect date property", date.toGMTString(),
477:                        readBean.getDateOfParty().toGMTString());
478:
479:            }
480:
481:            public void testCustomDateReadConversion() throws Exception {
482:
483:                BindingConfiguration configuration = new BindingConfiguration(
484:                        new ConvertUtilsObjectStringConverter(), false);
485:
486:                //SimpleLog log = new SimpleLog("testDateReadConversion:MethodUpdater");
487:                //log.setLevel(SimpleLog.LOG_LEVEL_TRACE);
488:                //MethodUpdater.setLog(log);
489:
490:                class ISOToStringConverter implements  Converter {
491:                    final SimpleDateFormat formatter = new SimpleDateFormat(
492:                            "yyyyMMdd");
493:
494:                    public Object convert(Class type, Object value) {
495:                        if (value == null) {
496:                            return null;
497:                        }
498:                        if (value instanceof  java.util.Date) {
499:                            return formatter.format((java.util.Date) value);
500:                        }
501:                        return value.toString();
502:                    }
503:                }
504:
505:                class ISODateConverter implements  Converter {
506:                    final SimpleDateFormat formatter = new SimpleDateFormat(
507:                            "yyyyMMdd");
508:
509:                    public Object convert(Class type, Object value) {
510:
511:                        if (value == null) {
512:                            return null;
513:                        }
514:
515:                        if (value instanceof  java.util.Date) {
516:
517:                            return formatter.format((java.util.Date) value);
518:                        }
519:
520:                        try {
521:                            return formatter.parse(value.toString());
522:                        } catch (ParseException ex) {
523:                            throw new ConversionException(ex);
524:                        }
525:                    }
526:                }
527:
528:                ISODateConverter converter = new ISODateConverter();
529:                ConvertUtils.register(converter, java.util.Date.class);
530:                ISOToStringConverter tsConverter = new ISOToStringConverter();
531:                ConvertUtils.register(tsConverter, String.class);
532:
533:                Converter dateConverter = ConvertUtils
534:                        .lookup(java.util.Date.class);
535:                assertEquals("Date converter successfully registered",
536:                        dateConverter, converter);
537:                Converter stringConverter = ConvertUtils.lookup(String.class);
538:                assertEquals("Date converter successfully registered",
539:                        tsConverter, stringConverter);
540:
541:                java.util.Date conversionResult = (java.util.Date) ConvertUtils
542:                        .convert("20030101", java.util.Date.class);
543:
544:                Calendar calendar = Calendar.getInstance();
545:                calendar.setTime(conversionResult);
546:                int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
547:                assertEquals("Correct conversion result", dayOfYear, 1);
548:
549:                calendar.set(2003, 7, 2);
550:                java.util.Date date = calendar.getTime();
551:
552:                PartyBean bean = new PartyBean("Wedding", date, 1900,
553:                        new AddressBean("Old White Lion Hotel", "Howarth",
554:                                "Merry Old England", "BD22 8EP"));
555:
556:                StringWriter out = new StringWriter();
557:                out.write("<?xml version='1.0'?>");
558:
559:                BeanWriter writer = new BeanWriter(out);
560:                writer.setBindingConfiguration(configuration);
561:                XMLIntrospector introspector = writer.getXMLIntrospector();
562:                introspector.getConfiguration().setElementNameMapper(
563:                        new HyphenatedNameMapper());
564:                introspector.getConfiguration().setAttributesForPrimitives(
565:                        false);
566:
567:                writer.write("party", bean);
568:
569:                String xml = "<?xml version='1.0'?><party>"
570:                        + "<venue><street>Old White Lion Hotel</street><city>Howarth</city>"
571:                        + "<code>BD22 8EP</code><country>Merry Old England</country></venue>"
572:                        + "<date-of-party>20030802</date-of-party><from-hour>1900</from-hour>"
573:                        + "<excuse>Wedding</excuse>" + "</party>";
574:
575:                xmlAssertIsomorphic(parseString(xml), parseString(out), true);
576:
577:                BeanReader reader = new BeanReader();
578:                reader.setBindingConfiguration(configuration);
579:                reader.setXMLIntrospector(introspector);
580:                reader.registerBeanClass("party", PartyBean.class);
581:                PartyBean readBean = (PartyBean) reader.parse(new StringReader(
582:                        xml));
583:
584:                assertEquals("FromHours incorrect property value", readBean
585:                        .getFromHour(), bean.getFromHour());
586:                assertEquals("Excuse incorrect property value", readBean
587:                        .getExcuse(), bean.getExcuse());
588:
589:                // check address
590:                AddressBean readAddress = readBean.getVenue();
591:                AddressBean address = bean.getVenue();
592:                assertEquals("address.street incorrect property value",
593:                        readAddress.getStreet(), address.getStreet());
594:                assertEquals("address.city incorrect property value",
595:                        readAddress.getCity(), address.getCity());
596:                assertEquals("address.code incorrect property value",
597:                        readAddress.getCode(), address.getCode());
598:                assertEquals("address.country incorrect property value",
599:                        readAddress.getCountry(), address.getCountry());
600:
601:                // check dates
602:                calendar.setTime(bean.getDateOfParty());
603:                calendar.set(Calendar.HOUR_OF_DAY, 0);
604:                dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
605:                int year = calendar.get(Calendar.YEAR);
606:                calendar.setTime(readBean.getDateOfParty());
607:                calendar.set(Calendar.HOUR_OF_DAY, 0);
608:                int readDayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
609:                int readYear = calendar.get(Calendar.YEAR);
610:                assertEquals("date incorrect property value (year)", year,
611:                        readYear);
612:                assertEquals("date incorrect property value (day)", dayOfYear,
613:                        readDayOfYear);
614:
615:                ConvertUtils.deregister();
616:            }
617:
618:            public void testReadMap() throws Exception {
619:                // we might as well start by writing out 
620:                MapBean bean = new MapBean("drinkers");
621:                bean
622:                        .addAddress("Russell McManus", new AddressBean(
623:                                "6, Westgate", "Shipley", "United Kingdom",
624:                                "BD17 5EJ"));
625:                bean.addAddress("Alex Compbell", new AddressBean("5, Kirkgate",
626:                        "Shipley", "United Kingdom", "BD18 3QW"));
627:                bean.addAddress("Sid Gardner", new AddressBean(
628:                        "Old House At Home, Otley Road", "Shipley",
629:                        "United Kingdom", "BD18 2BJ"));
630:
631:                StringWriter out = new StringWriter();
632:                out.write("<?xml version='1.0'?>");
633:                BeanWriter writer = new BeanWriter(out);
634:                writer.getBindingConfiguration().setMapIDs(false);
635:                writer.write("address-book", bean);
636:
637:                String xml = "<?xml version='1.0'?><address-book><title>drinkers</title>"
638:                        + "<addresses>"
639:                        + "<entry><key>Alex Compbell</key><value><country>United Kingdom</country>"
640:                        + "<code>BD18 3QW</code><city>Shipley</city><street>5, Kirkgate</street></value></entry>"
641:                        + "<entry><key>Russell McManus</key><value><country>United Kingdom</country><code>BD17 5EJ</code>"
642:                        + "<city>Shipley</city><street>6, Westgate</street></value></entry>"
643:                        + "<entry><key>Sid Gardner</key><value><country>United Kingdom</country>"
644:                        + "<code>BD18 2BJ</code><city>Shipley</city><street>Old House At Home, Otley Road</street>"
645:                        + "</value></entry>" + "</addresses></address-book>";
646:
647:                xmlAssertIsomorphic(parseString(out.toString()),
648:                        parseString(xml), true);
649:
650:                //        SimpleLog log = new SimpleLog("[testReadMap:BeanRuleSet]");
651:                //        log.setLevel(SimpleLog.LOG_LEVEL_TRACE);
652:                //        BeanRuleSet.setLog(log);
653:                //        log = new SimpleLog("[testReadMap:XMLIntrospectorHelper]");
654:                //        log.setLevel(SimpleLog.LOG_LEVEL_TRACE);
655:                //        XMLIntrospectorHelper.setLog(log);
656:                //        log = new SimpleLog("[testReadMap:MapEntryAdder]");
657:                //        log.setLevel(SimpleLog.LOG_LEVEL_TRACE);
658:                //        MapEntryAdder.setLog(log);
659:
660:                BeanReader reader = new BeanReader();
661:
662:                //        log = new SimpleLog("[testReadMap:BeanReader]");
663:                //        log.setLevel(SimpleLog.LOG_LEVEL_TRACE);
664:                //        reader.setLog(log);
665:                //        log = new SimpleLog("[testReadMap:XMLIntrospector]");
666:                //        log.setLevel(SimpleLog.LOG_LEVEL_TRACE);
667:                //        reader.getXMLIntrospector().setLog(log);
668:
669:                reader.getBindingConfiguration().setMapIDs(false);
670:                reader.registerBeanClass("address-book", MapBean.class);
671:                bean = (MapBean) reader.parse(new StringReader(xml));
672:
673:                assertEquals("Title property is incorrect", "drinkers", bean
674:                        .getTitle());
675:                assertEquals("Map entries", 3, bean.getAddresses().size());
676:
677:                AddressBean address = (AddressBean) bean.getAddresses().get(
678:                        "Russell McManus");
679:                assertNotNull("Missing entry for 'Russell McManus'", address);
680:                assertEquals("Bad address (1)", "6, Westgate", address
681:                        .getStreet());
682:                assertEquals("Bad address (2)", "Shipley", address.getCity());
683:                assertEquals("Bad address (3)", "United Kingdom", address
684:                        .getCountry());
685:                assertEquals("Bad address (4)", "BD17 5EJ", address.getCode());
686:
687:                address = (AddressBean) bean.getAddresses()
688:                        .get("Alex Compbell");
689:                assertNotNull("Missing entry for 'Alex Compbell'", address);
690:                assertEquals("Bad address (5)", "5, Kirkgate", address
691:                        .getStreet());
692:                assertEquals("Bad address (6)", "Shipley", address.getCity());
693:                assertEquals("Bad address (7)", "United Kingdom", address
694:                        .getCountry());
695:                assertEquals("Bad address (8)", "BD18 3QW", address.getCode());
696:
697:                address = (AddressBean) bean.getAddresses().get("Sid Gardner");
698:                assertNotNull("Missing entry for 'Sid Gardner'", address);
699:                assertEquals("Bad address (9)",
700:                        "Old House At Home, Otley Road", address.getStreet());
701:                assertEquals("Bad address (10)", "Shipley", address.getCity());
702:                assertEquals("Bad address (11)", "United Kingdom", address
703:                        .getCountry());
704:                assertEquals("Bad address (12)", "BD18 2BJ", address.getCode());
705:            }
706:
707:            public void testReadMap2() throws Exception {
708:                IdMap idMap = new IdMap();
709:                String id = "3920";
710:                idMap.addId(id, new Integer(1));
711:                StringWriter outputWriter = new StringWriter();
712:                outputWriter.write("<?xml version='1.0' ?>\n");
713:                BeanWriter beanWriter = new BeanWriter(outputWriter);
714:                beanWriter.write(idMap);
715:                String xml = outputWriter.toString();
716:                System.out.println("Map test: " + xml);
717:
718:                BeanReader beanReader = new BeanReader();
719:                beanReader.registerBeanClass(IdMap.class);
720:                IdMap result = (IdMap) beanReader.parse(new StringReader(xml));
721:                assertNotNull("didn't get an object back!", result);
722:                assertNotNull("didn't get a Map out of the IdMap!", result
723:                        .getIds());
724:                assertEquals("Got the Map, but doesn't have an entry!", 1,
725:                        result.getIds().size());
726:                assertNotNull("Got the Map, but doesn't have correct values!",
727:                        result.getIds().get(id));
728:            }
729:
730:            public void testIndirectReference() throws Exception {
731:                Tweedledum dum = new Tweedledum();
732:                Tweedledee dee = new Tweedledee(dum);
733:                StringWriter out = new StringWriter();
734:                out.write("<?xml version='1.0'?>");
735:                BeanWriter writer = new BeanWriter(out);
736:                writer.getBindingConfiguration().setMapIDs(false);
737:                writer.write(dee);
738:                String xml = "<?xml version='1.0'?><Tweedledee><name>Tweedledee</name>"
739:                        + "<brother><name>Tweedledum</name></brother></Tweedledee>";
740:                xmlAssertIsomorphic(parseString(xml), parseString(out), true);
741:
742:                BeanReader reader = new BeanReader();
743:
744:                reader.getBindingConfiguration().setMapIDs(false);
745:                reader.registerBeanClass(Tweedledee.class);
746:                Tweedledee bean = (Tweedledee) reader.parse(new StringReader(
747:                        xml));
748:                assertNotNull(bean.getBrother());
749:            }
750:
751:            public void _testDoubleLinkedCollectionRead() throws Exception {
752:                String xml = "<?xml version='1.0'?><DOUBLE_LINKED_PARENT_BEAN>"
753:                        + "<NAME>Cronus</NAME>" + "<CHILDREN>"
754:                        + "<CHILD><NAME>Hades</NAME></CHILD>"
755:                        + "<CHILD><NAME>Hera</NAME></CHILD>"
756:                        + "<CHILD><NAME>Hestia</NAME></CHILD>"
757:                        + "<CHILD><NAME>Demeter</NAME></CHILD>"
758:                        + "<CHILD><NAME>Poseidon</NAME></CHILD>"
759:                        + "<CHILD><NAME>Zeus</NAME></CHILD>"
760:                        + "</CHILDREN></DOUBLE_LINKED_PARENT_BEAN>";
761:
762:                BeanReader reader = new BeanReader();
763:                reader.getXMLIntrospector().getConfiguration()
764:                        .setElementNameMapper(
765:                                new HyphenatedNameMapper(true, "_"));
766:                reader.registerBeanClass(DoubleLinkedParentBean.class);
767:                DoubleLinkedParentBean bean = (DoubleLinkedParentBean) reader
768:                        .parse(new StringReader(xml));
769:
770:                assertNotNull("Bean read", bean);
771:                assertEquals("Cronus", "Parent name", bean.getName());
772:                assertEquals("Number of children", 6, bean.getSize());
773:
774:                ArrayList list = new ArrayList();
775:                for (Iterator it = bean.getChildren(); it.hasNext();) {
776:                    list.add(it.next());
777:                }
778:
779:                DoubleLinkedChildBean childZero = (DoubleLinkedChildBean) list
780:                        .get(0);
781:                DoubleLinkedChildBean childOne = (DoubleLinkedChildBean) list
782:                        .get(1);
783:                DoubleLinkedChildBean childTwo = (DoubleLinkedChildBean) list
784:                        .get(2);
785:                DoubleLinkedChildBean childThree = (DoubleLinkedChildBean) list
786:                        .get(3);
787:                DoubleLinkedChildBean childFour = (DoubleLinkedChildBean) list
788:                        .get(4);
789:                DoubleLinkedChildBean childFive = (DoubleLinkedChildBean) list
790:                        .get(5);
791:
792:                assertEquals("Child name zero", "Hades", childZero.getName());
793:                assertEquals("Child name one", "Hera", childZero.getName());
794:                assertEquals("Child name two", "Hestia", childZero.getName());
795:                assertEquals("Child name three", "Demeter", childZero.getName());
796:                assertEquals("Child name four", "Poseidon", childZero.getName());
797:                assertEquals("Child name five", "Zeus", childZero.getName());
798:
799:            }
800:
801:            /** 
802:             * This is a member class since all classes starting with test 
803:             * will be run as test cases.
804:             */
805:            private class TestRule extends Rule {
806:
807:                private String name;
808:                private boolean called = false;
809:                private Object top;
810:
811:                public Object getTop() {
812:                    return top;
813:                }
814:
815:                public String getName() {
816:                    return name;
817:                }
818:
819:                public void setName(String name) {
820:                    this .name = name;
821:                }
822:
823:                public boolean isCalled() {
824:                    return called;
825:                }
826:
827:                public void begin(String name, String namespace,
828:                        Attributes attributes) {
829:                    top = getDigester().peek();
830:                    called = true;
831:                }
832:            }
833:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.