KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > ws > jaxme > junit > MarshallerTest


1 /*
2  * Copyright 2003, 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.ws.jaxme.junit;
18
19 import java.io.IOException JavaDoc;
20 import java.io.StringReader JavaDoc;
21 import java.io.StringWriter JavaDoc;
22 import java.math.BigDecimal JavaDoc;
23 import java.math.BigInteger JavaDoc;
24 import java.text.DateFormat JavaDoc;
25 import java.util.ArrayList JavaDoc;
26 import java.util.Arrays JavaDoc;
27 import java.util.Calendar JavaDoc;
28 import java.util.List JavaDoc;
29 import java.util.TimeZone JavaDoc;
30
31 import javax.xml.bind.JAXBContext;
32 import javax.xml.bind.JAXBException;
33 import javax.xml.bind.Marshaller;
34 import javax.xml.bind.UnmarshalException;
35 import javax.xml.bind.Unmarshaller;
36 import javax.xml.bind.ValidationException;
37 import javax.xml.namespace.QName JavaDoc;
38 import javax.xml.parsers.ParserConfigurationException JavaDoc;
39 import javax.xml.parsers.SAXParser JavaDoc;
40 import javax.xml.parsers.SAXParserFactory JavaDoc;
41 import javax.xml.transform.stream.StreamSource JavaDoc;
42
43 import org.apache.ws.jaxme.XMLConstants;
44 import org.apache.ws.jaxme.XMLWriter;
45 import org.apache.ws.jaxme.impl.DatatypeConverterImpl;
46 import org.apache.ws.jaxme.impl.JAXBContextImpl;
47 import org.apache.ws.jaxme.impl.JMMarshallerImpl;
48 import org.apache.ws.jaxme.test.misc.address.Address;
49 import org.apache.ws.jaxme.test.misc.address.AddressType;
50 import org.apache.ws.jaxme.test.misc.types.AllElement;
51 import org.apache.ws.jaxme.test.misc.types.AllSimpleTypes;
52 import org.apache.ws.jaxme.test.misc.types.AllTypesElement;
53 import org.apache.ws.jaxme.test.misc.types.Author;
54 import org.apache.ws.jaxme.test.misc.types.ObjectFactory;
55 import org.apache.ws.jaxme.test.misc.types.impl.AllElementImpl;
56 import org.apache.ws.jaxme.test.misc.types.impl.AllSimpleTypesImpl;
57 import org.apache.ws.jaxme.test.misc.types.impl.AllTypesElementImpl;
58 import org.apache.ws.jaxme.util.Duration;
59 import org.xml.sax.Attributes JavaDoc;
60 import org.xml.sax.InputSource JavaDoc;
61 import org.xml.sax.SAXException JavaDoc;
62 import org.xml.sax.SAXNotRecognizedException JavaDoc;
63 import org.xml.sax.SAXNotSupportedException JavaDoc;
64 import org.xml.sax.XMLReader JavaDoc;
65 import org.xml.sax.helpers.DefaultHandler JavaDoc;
66
67 import sun.security.validator.ValidatorException;
68
69
70 /**
71  * @author <a HREF="mailto:joe@ispsoft.de">Jochen Wiedmann</a>
72  * @version $Id: MarshallerTest.java,v 1.23 2005/06/30 08:16:14 jochen Exp $
73  */

74 public class MarshallerTest extends BaseTestCase {
75     private JAXBContextImpl factory;
76
77   /** <p>Creates a new instance of MarshallerTest.</p>
78    */

79   public MarshallerTest(String JavaDoc arg) { super(arg); }
80
81   public void setUp() throws JAXBException {
82     factory = (JAXBContextImpl) JAXBContext.newInstance("org.apache.ws.jaxme.test.misc.types");
83   }
84
85   protected JAXBContextImpl getFactory() {
86     return factory;
87   }
88
89   protected Calendar JavaDoc getDateTime() {
90     Calendar JavaDoc cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
91     cal.set(Calendar.DAY_OF_MONTH, 22);
92     cal.set(Calendar.MONTH, 11-1);
93     cal.set(Calendar.YEAR, 2002);
94     cal.set(Calendar.HOUR_OF_DAY, 16);
95     cal.set(Calendar.MINUTE, 43);
96     cal.set(Calendar.SECOND, 37);
97     cal.set(Calendar.MILLISECOND, 0);
98     return cal;
99   }
100
101   protected Calendar JavaDoc getTime() {
102     Calendar JavaDoc cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
103     cal.set(Calendar.HOUR_OF_DAY, 16);
104     cal.set(Calendar.MINUTE, 43);
105     cal.set(Calendar.SECOND, 37);
106     cal.set(Calendar.MILLISECOND, 0);
107     cal.set(Calendar.YEAR, 0);
108     cal.set(Calendar.MONTH, 0);
109     cal.set(Calendar.DAY_OF_MONTH, 0);
110     return cal;
111   }
112
113   protected Calendar JavaDoc getDate() {
114     Calendar JavaDoc cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
115     cal.set(Calendar.DAY_OF_MONTH, 22);
116     cal.set(Calendar.MONTH, 11-1);
117     cal.set(Calendar.YEAR, 2002);
118     cal.set(Calendar.HOUR_OF_DAY, 0);
119     cal.set(Calendar.MINUTE, 0);
120     cal.set(Calendar.SECOND, 0);
121     cal.set(Calendar.MILLISECOND, 0);
122     return cal;
123   }
124
125   protected Duration getDuration() {
126     Duration d = new Duration(false, 1, 2, 3, 4, 5, 6, 7);
127     return d;
128   }
129
130   protected byte[] getHexBytes() {
131     return new byte[]{1, 17, 35, 78, 115, -99, -69, -1};
132   }
133
134   protected BigDecimal JavaDoc newBigDecimal() {
135       return new BigDecimal JavaDoc("6.023e23");
136   }
137   
138   protected AllSimpleTypes getAllSimpleTypesElement() {
139     AllSimpleTypes element = new AllSimpleTypesImpl();
140     element.setStringElem("This is a string with german Umlauts: \u00e4\u00f6\u00fc\u00df\u00c4\u00d6\u00dc");
141     element.setDoubleElem(23979782937923.2398798);
142     element.setFloatElem(-34768.3486787f);
143     element.setIntElem(-2139879);
144     element.setLongElem(1290380128309182303l);
145     element.setShortElem((short) 23878);
146     element.setDateElem(getDate());
147     element.setDateTimeElem(getDateTime());
148     element.setTimeElem(getTime());
149     element.setDurationElem(getDuration());
150     element.setHexBinaryElem(getHexBytes());
151     element.setBase64BinaryElem(getHexBytes());
152     element.setNmTokenElem("a-name-token");
153     List JavaDoc nmTokens = element.getNmTokensElem();
154     nmTokens.add("a-name-token");
155     nmTokens.add("another:name-token");
156     element.setDecimalElem(newBigDecimal());
157     element.setIntegerElem(new BigDecimal JavaDoc("-6023e20").toBigInteger());
158     element.setNonNegativeIntegerElem(new BigInteger JavaDoc("101"));
159     element.setPositiveIntegerElem(new BigDecimal JavaDoc("+6023e20").toBigInteger());
160     element.setNonPositiveIntegerElem(new BigInteger JavaDoc("-21714"));
161     element.setNegativeIntegerElem(new BigInteger JavaDoc("-21714"));
162     element.setQNameElem(new QName JavaDoc("http://ws.apache.org/jaxme/test/misc/types", "ias"));
163     element.setBooleanElem(true);
164     return element;
165   }
166
167   protected AllTypesElement getAllTypesElement() throws JAXBException {
168     AllTypesElement element = (AllTypesElement) getFactory().getManager(AllTypesElement.class).getElementJ();
169     element.setAllSimpleTypesElement(getAllSimpleTypesElement());
170     List JavaDoc list = element.getListTypeElement();
171     list.add(new BigInteger JavaDoc("7"));
172     list.add(new BigInteger JavaDoc("-3"));
173     list.add(new BigInteger JavaDoc("0"));
174     element.setUnionTypeElement(getDateTime());
175     return element;
176   }
177
178   protected String JavaDoc getAllSimpleTypesElementString() {
179     AllTypesElementImpl elem = new AllTypesElementImpl();
180     String JavaDoc uri = elem.getQName().getNamespaceURI();
181     return
182       "<ex:AllSimpleTypesElement xmlns:ex=\"" + uri + "\">" +
183       "<ex:StringElem>This is a string with german Umlauts: &#228;&#246;&#252;&#223;&#196;&#214;&#220;</ex:StringElem>" +
184       "<ex:IntElem>-2139879</ex:IntElem>" +
185       "<ex:LongElem>1290380128309182303</ex:LongElem>" +
186       "<ex:ShortElem>23878</ex:ShortElem>" +
187       "<ex:DoubleElem>2.397978293792324E13</ex:DoubleElem>" +
188       "<ex:FloatElem>-34768.348</ex:FloatElem>" +
189       "<ex:DateTimeElem>2002-11-22T16:43:37Z</ex:DateTimeElem>" +
190       "<ex:DateElem>2002-11-22Z</ex:DateElem>" +
191       "<ex:TimeElem>16:43:37Z</ex:TimeElem>" +
192       "<ex:DurationElem>P1Y2M3DT4H5M6.7S</ex:DurationElem>" +
193       "<ex:HexBinaryElem>0111234E739DBBFF</ex:HexBinaryElem>" +
194       "<ex:Base64BinaryElem>AREjTnOdu/8=</ex:Base64BinaryElem>" +
195       "<ex:NmTokenElem>a-name-token</ex:NmTokenElem>" +
196       "<ex:NmTokensElem>a-name-token another:name-token</ex:NmTokensElem>" +
197       "<ex:DecimalElem>" + new DatatypeConverterImpl().printDecimal(newBigDecimal()) + "</ex:DecimalElem>" +
198       "<ex:IntegerElem>-602300000000000000000000</ex:IntegerElem>" +
199       "<ex:NonNegativeIntegerElem>101</ex:NonNegativeIntegerElem>" +
200       "<ex:PositiveIntegerElem>602300000000000000000000</ex:PositiveIntegerElem>" +
201       "<ex:NonPositiveIntegerElem>-21714</ex:NonPositiveIntegerElem>" +
202       "<ex:NegativeIntegerElem>-21714</ex:NegativeIntegerElem>" +
203       "<ex:QNameElem>ex:ias</ex:QNameElem>" +
204       "<ex:BooleanElem>true</ex:BooleanElem>" +
205       "</ex:AllSimpleTypesElement>";
206   }
207
208   private String JavaDoc getAllTypesElementString(boolean pSchemaDeclaration, boolean pFormatted) {
209     AllTypesElementImpl elem = new AllTypesElementImpl();
210     String JavaDoc uri = elem.getQName().getNamespaceURI();
211     String JavaDoc xsi = pSchemaDeclaration ? " xmlns:xsi=\""
212         + XMLConstants.XML_SCHEMA_URI + "\" xsi:"
213         + XMLConstants.XML_SCHEMA_NS_ATTR + "=\"foo.xsd\"" : "";
214     String JavaDoc lf = pFormatted ? "\n" : "";
215     String JavaDoc sep = pFormatted ? " " : "";
216     String JavaDoc sep2 = sep + sep;
217     return
218       "<ex:AllTypesElement xmlns:ex=\"" + uri + "\"" + xsi + ">" + lf +
219       sep + "<ex:AllSimpleTypesElement>" + lf +
220       sep2 + "<ex:StringElem>This is a string with german Umlauts: &#228;&#246;&#252;&#223;&#196;&#214;&#220;</ex:StringElem>" + lf +
221       sep2 + "<ex:IntElem>-2139879</ex:IntElem>" + lf +
222       sep2 + "<ex:LongElem>1290380128309182303</ex:LongElem>" + lf +
223       sep2 + "<ex:ShortElem>23878</ex:ShortElem>" + lf +
224       sep2 + "<ex:DoubleElem>2.397978293792324E13</ex:DoubleElem>" + lf +
225       sep2 + "<ex:FloatElem>-34768.348</ex:FloatElem>" + lf +
226       sep2 + "<ex:DateTimeElem>2002-11-22T16:43:37Z</ex:DateTimeElem>" + lf +
227       sep2 + "<ex:DateElem>2002-11-22Z</ex:DateElem>" + lf +
228       sep2 + "<ex:TimeElem>16:43:37Z</ex:TimeElem>" + lf +
229       sep2 + "<ex:DurationElem>P1Y2M3DT4H5M6.7S</ex:DurationElem>" + lf +
230       sep2 + "<ex:HexBinaryElem>0111234E739DBBFF</ex:HexBinaryElem>" + lf +
231       sep2 + "<ex:Base64BinaryElem>AREjTnOdu/8=</ex:Base64BinaryElem>" + lf +
232       sep2 + "<ex:NmTokenElem>a-name-token</ex:NmTokenElem>" + lf +
233       sep2 + "<ex:NmTokensElem>a-name-token another:name-token</ex:NmTokensElem>" + lf +
234       sep2 + "<ex:DecimalElem>" + new DatatypeConverterImpl().printDecimal(newBigDecimal()) + "</ex:DecimalElem>" + lf +
235       sep2 + "<ex:IntegerElem>-602300000000000000000000</ex:IntegerElem>" + lf +
236       sep2 + "<ex:NonNegativeIntegerElem>101</ex:NonNegativeIntegerElem>" + lf +
237       sep2 + "<ex:PositiveIntegerElem>602300000000000000000000</ex:PositiveIntegerElem>" + lf +
238       sep2 + "<ex:NonPositiveIntegerElem>-21714</ex:NonPositiveIntegerElem>" + lf +
239       sep2 + "<ex:NegativeIntegerElem>-21714</ex:NegativeIntegerElem>" + lf +
240       sep2 + "<ex:QNameElem>ex:ias</ex:QNameElem>" + lf +
241       sep2 + "<ex:BooleanElem>true</ex:BooleanElem>" + lf +
242       sep + "</ex:AllSimpleTypesElement>" + lf +
243       sep + "<ex:ListTypeElement>7 -3 0</ex:ListTypeElement>" + lf +
244       sep + "<ex:UnionTypeElement>2002-11-22T16:43:37Z</ex:UnionTypeElement>" + lf +
245       "</ex:AllTypesElement>";
246   }
247
248   protected XMLReader JavaDoc getXMLReader() throws ParserConfigurationException JavaDoc, SAXException JavaDoc {
249     // Verify whether we can create a SAX Parser; it's better to detect this here
250
// than within JAXB
251
SAXParserFactory JavaDoc spf = SAXParserFactory.newInstance();
252     spf.setNamespaceAware(true);
253     spf.setValidating(false);
254     SAXParser JavaDoc sp = spf.newSAXParser();
255     return sp.getXMLReader();
256   }
257
258   protected void verifyAllSimpleTypesElement(AllSimpleTypes pElement) {
259     assertEquals("This is a string with german Umlauts: \u00e4\u00f6\u00fc\u00df\u00c4\u00d6\u00dc",
260                        pElement.getStringElem());
261     assertEquals(new Double JavaDoc("2.397978293792324E13").doubleValue(),
262                  pElement.getDoubleElem(), 0);
263     assertEquals(new Float JavaDoc(-34768.348).floatValue(), pElement.getFloatElem(), 0);
264     assertEquals(new Integer JavaDoc(-2139879).intValue(), pElement.getIntElem());
265     assertEquals(new Long JavaDoc(1290380128309182303L).longValue(), pElement.getLongElem());
266     assertEquals(new Short JavaDoc((short) 23878).shortValue(), pElement.getShortElem());
267     assertEquals(getDateTime(), pElement.getDateTimeElem());
268     assertEquals(getDate(), pElement.getDateElem());
269     assertEquals(getTime(), pElement.getTimeElem());
270     assertEquals(getDuration(), pElement.getDurationElem());
271     assertEquals(getHexBytes(), pElement.getHexBinaryElem());
272     assertEquals(getHexBytes(), pElement.getBase64BinaryElem());
273     assertEquals(new BigInteger JavaDoc("101"), pElement.getNonNegativeIntegerElem());
274     assertTrue(pElement.isBooleanElem());
275   }
276
277   protected void verifyAllTypesElement(AllTypesElement pElement) {
278     verifyAllSimpleTypesElement(pElement.getAllSimpleTypesElement());
279     List JavaDoc list = pElement.getListTypeElement();
280     assertEquals(3, list.size());
281     assertEquals(new BigInteger JavaDoc("7"), list.get(0));
282     assertEquals(new BigInteger JavaDoc("-3"), list.get(1));
283     assertEquals(new BigInteger JavaDoc("0"), list.get(2));
284     Object JavaDoc object = pElement.getUnionTypeElement();
285     String JavaDoc dateTime1 = DateFormat.getDateTimeInstance().format(getDateTime().getTime());
286     String JavaDoc dateTime2 = DateFormat.getDateTimeInstance().format(((Calendar JavaDoc) object).getTime());
287     assertEquals(dateTime1, dateTime2);
288   }
289
290     /** <p>Tests unmarshalling of a simple element.</p>
291      */

292     public void testUnmarshalSimpleElements() throws Exception JavaDoc {
293         String JavaDoc s = getAllTypesElementString(false, false);
294         StringReader JavaDoc sr = new StringReader JavaDoc(s);
295         AllTypesElement e = (AllTypesElement) getFactory().createUnmarshaller().unmarshal(new InputSource JavaDoc(sr));
296         verifyAllSimpleTypesElement(e.getAllSimpleTypesElement());
297     }
298
299   /** <p>Tests, whether complex elements can be marshalled.</p>
300    */

301   public void testUnmarshalComplexElements() throws Exception JavaDoc {
302     testUnmarshalComplexElements(false);
303     testUnmarshalComplexElements(true);
304   }
305
306   private void testUnmarshalComplexElements(boolean pSchemaLocation)
307       throws Exception JavaDoc {
308     JAXBContext myFactory = getFactory();
309     Unmarshaller unmarshaller = myFactory.createUnmarshaller();
310     String JavaDoc s = getAllTypesElementString(pSchemaLocation, true);
311     StringReader JavaDoc sr = new StringReader JavaDoc(s);
312     AllTypesElement result = (AllTypesElement) unmarshaller.unmarshal(new InputSource JavaDoc(sr));
313     verifyAllTypesElement(result);
314     result = (AllTypesElement) myFactory.createUnmarshaller().unmarshal(new StreamSource JavaDoc(new StringReader JavaDoc(s)));
315     verifyAllTypesElement(result);
316   }
317
318   /** <p>Tests marshalling of a simple element.</p>
319    */

320   public void testMarshalSimpleElements() throws Exception JavaDoc {
321       JMMarshallerImpl m = (JMMarshallerImpl) getFactory().createMarshaller();
322       StringWriter JavaDoc sw = new StringWriter JavaDoc();
323       AllTypesElement element = getAllTypesElement();
324       m.setXmlDeclaration(false);
325       m.setEncoding("US-ASCII");
326       m.marshal(element, sw);
327       String JavaDoc expected = getAllTypesElementString(false, true);
328       assertEquals(expected, sw.toString());
329   }
330
331   /** <p>Tests marshalling of a complex element.</p>
332    */

333   public void testMarshalComplexElements() throws Exception JavaDoc {
334     JAXBContext myFactory = getFactory();
335     JMMarshallerImpl marshaller = (JMMarshallerImpl) myFactory.createMarshaller();
336     marshaller.setXmlDeclaration(false);
337     StringWriter JavaDoc sw = new StringWriter JavaDoc();
338     Class JavaDoc c = marshaller.getXMLWriterClass();
339     XMLWriter w = (XMLWriter) c.newInstance();
340     w.init(marshaller);
341     String JavaDoc rawInput = getAllTypesElementString(false, true);
342     StringBuffer JavaDoc input = new StringBuffer JavaDoc();
343     for (int i = 0; i < rawInput.length(); i++) {
344       char ch = rawInput.charAt(i);
345       boolean done = false;
346       if (ch == '&') {
347         if (i+1 < rawInput.length() && rawInput.charAt(i+1) == '#') {
348           int j = 2;
349           StringBuffer JavaDoc digits = new StringBuffer JavaDoc();
350           while (i+j < rawInput.length() && Character.isDigit(rawInput.charAt(i+j))) {
351             digits.append(rawInput.charAt(i+j));
352             ++j;
353           }
354           if (digits.length() > 0 &&
355               i+j < rawInput.length() && rawInput.charAt(i+j) == ';') {
356             char chr = (char) Integer.parseInt(digits.toString());
357             if (w.canEncode(chr)) {
358               done = true;
359               i += j;
360               input.append(chr);
361             }
362           }
363         }
364       }
365       if (!done) {
366         input.append(ch);
367       }
368     }
369     marshaller.marshal(getAllTypesElement(), sw);
370     assertEquals(input.toString(), sw.toString());
371   }
372
373   protected String JavaDoc getMarshalledAuthor() throws JAXBException {
374       Author author = new ObjectFactory().createAuthor();
375       author.setRating(2);
376       author.setValue("This is a test.");
377       StringWriter JavaDoc sw = new StringWriter JavaDoc();
378       Marshaller m = getFactory().createMarshaller();
379       m.setProperty(JMMarshallerImpl.JAXME_XML_DECLARATION, Boolean.FALSE);
380       m.marshal(author, sw);
381       return sw.toString();
382   }
383
384   /** <p>Tests, whether elements with simple content can be marshalled.</p>
385    */

386   public void testMarshalSimpleContent() throws Exception JavaDoc {
387       String JavaDoc expect = "<ex:Author rating=\"2\" xmlns:ex=\"http://ws.apache.org/jaxme/test/misc/types\">This is a test.</ex:Author>";
388       String JavaDoc got = getMarshalledAuthor();
389       assertEquals(expect, got);
390   }
391
392   private void verifyUnmarshalledAuthor(Author pAuthor) {
393     assertEquals(2, pAuthor.getRating());
394     assertEquals("This is a test.", pAuthor.getValue());
395   }
396
397   /** <p>Tests, whether elements with simple content can be unmarshalled.</p>
398    */

399   public void testUnmarshalSimpleContent() throws Exception JavaDoc {
400       String JavaDoc s = getMarshalledAuthor();
401       Author author = (Author) getFactory().createUnmarshaller().unmarshal(new InputSource JavaDoc(new StringReader JavaDoc(s)));
402       verifyUnmarshalledAuthor(author);
403       author = (Author) getFactory().createUnmarshaller().unmarshal(new StreamSource JavaDoc(new StringReader JavaDoc(s)));
404       verifyUnmarshalledAuthor(author);
405   }
406
407   /**
408    * Tests that toString returns an appropriate xsd:duration value
409    */

410   public void testExplicitToString() {
411       String JavaDoc dur1 = "P0Y0M0DT0H2M60S";
412       Duration duration1 = Duration.valueOf(dur1);
413       String JavaDoc actualReturn = duration1.toString();
414       assertEquals("return value not as expected", dur1, actualReturn);
415   }
416
417   /**
418    * Tests that toString returns an appropriate xsd:duration value
419    */

420   public void testImplicitToString() {
421       String JavaDoc dur2 = "PT2M60S";
422       Duration duration2 = Duration.valueOf(dur2);
423       String JavaDoc actualReturn = duration2.toString();
424       String JavaDoc expect = "P0Y0M0DT0H2M60S";
425       assertEquals("return value not as expected ", expect, actualReturn);
426   }
427   
428   /**
429    * Test that getMillis returns the total time of duration in
430    milliseconds
431    */

432   public void testMillis() {
433       String JavaDoc dur2 = "PT2M60S";
434       Duration duration2 = Duration.valueOf(dur2);
435       assertEquals(2, duration2.getMinutes());
436       assertEquals(60, duration2.getSeconds());
437   }
438
439   protected String JavaDoc getAllElementString(boolean pRandom) {
440     AllElementImpl elem = new AllElementImpl();
441     String JavaDoc uri = elem.getQName().getNamespaceURI();
442     String JavaDoc[] elements = new String JavaDoc[]{
443       "<ex:StringElem>This is a string with german Umlauts: &#228;&#246;&#252;&#223;&#196;&#214;&#220;</ex:StringElem>",
444       "<ex:IntElem>-2139879</ex:IntElem>",
445       "<ex:LongElem>1290380128309182303</ex:LongElem>",
446       "<ex:ShortElem>23878</ex:ShortElem>",
447       "<ex:DoubleElem>2.397978293792324E13</ex:DoubleElem>",
448       "<ex:FloatElem>-34768.348</ex:FloatElem>",
449       "<ex:DateTimeElem>2002-11-22T16:43:37Z</ex:DateTimeElem>",
450       "<ex:DateElem>2002-11-22Z</ex:DateElem>",
451       "<ex:TimeElem>16:43:37Z</ex:TimeElem>",
452       "<ex:DurationElem>P1Y2M3DT4H5M6.7S</ex:DurationElem>",
453       "<ex:HexBinaryElem>0111234E739DBBFF</ex:HexBinaryElem>",
454       "<ex:Base64BinaryElem>AREjTnOdu/8=</ex:Base64BinaryElem>",
455       "<ex:NmTokenElem>a-name-token</ex:NmTokenElem>",
456       "<ex:NmTokensElem>a-name-token another:name-token</ex:NmTokensElem>",
457       "<ex:DecimalElem>" + new DatatypeConverterImpl().printDecimal(newBigDecimal()) + "</ex:DecimalElem>",
458       "<ex:IntegerElem>-602300000000000000000000</ex:IntegerElem>",
459       "<ex:NonNegativeIntegerElem>101</ex:NonNegativeIntegerElem>",
460       "<ex:PositiveIntegerElem>602300000000000000000000</ex:PositiveIntegerElem>",
461       "<ex:NonPositiveIntegerElem>-21714</ex:NonPositiveIntegerElem>",
462       "<ex:NegativeIntegerElem>-21714</ex:NegativeIntegerElem>",
463       "<ex:QNameElem>ex:ias</ex:QNameElem>",
464       "<ex:BooleanElem>true</ex:BooleanElem>"
465     };
466
467     if (pRandom) {
468         List JavaDoc list = new ArrayList JavaDoc(Arrays.asList(elements));
469         for (int i = 0; i < elements.length; i++) {
470             int num = (int) (Math.random() * list.size());
471             String JavaDoc element = (String JavaDoc) list.remove(num);
472             elements[i] = element;
473         }
474     }
475
476     StringBuffer JavaDoc result = new StringBuffer JavaDoc();
477     result.append("<ex:AllElement xmlns:ex=\"" + uri + "\">");
478     for (int i = 0; i < elements.length; i++) {
479         result.append(elements[i]);
480     }
481     result.append("</ex:AllElement>");
482     return result.toString();
483   }
484
485   /** <p>Tests marshalling and unmarshalling of an element with "xs:all"
486    * contents.</p>
487    */

488   public void testAllElement() throws Exception JavaDoc {
489     String JavaDoc s = getAllElementString(true);
490     JAXBContext context = getFactory();
491     AllElement e = (AllElement) context.createUnmarshaller().unmarshal(new InputSource JavaDoc(new StringReader JavaDoc(s)));
492     StringWriter JavaDoc sw = new StringWriter JavaDoc();
493     Marshaller marshaller = context.createMarshaller();
494     marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
495     marshaller.setProperty(Marshaller.JAXB_ENCODING, "ASCII");
496     marshaller.setProperty(JMMarshallerImpl.JAXME_XML_DECLARATION, Boolean.FALSE);
497     marshaller.marshal(e, sw);
498     String JavaDoc got = sw.toString();
499     String JavaDoc expect = getAllElementString(false);
500     assertEquals(expect, got);
501   }
502
503   private RootElementHandler getRootElementInfo(String JavaDoc pElement) throws ParserConfigurationException JavaDoc, IOException JavaDoc, SAXException JavaDoc {
504     RootElementHandler reh = new RootElementHandler();
505     XMLReader JavaDoc xr = getXMLReader();
506     try {
507       xr.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
508     } catch (SAXNotSupportedException JavaDoc e) {
509     } catch (SAXNotRecognizedException JavaDoc e) {
510     }
511     try {
512       xr.setFeature("http://xml.org/sax/features/xmlns-uris", true);
513     } catch (SAXNotSupportedException JavaDoc e) {
514     } catch (SAXNotRecognizedException JavaDoc e) {
515     }
516     xr.setContentHandler(reh);
517     xr.parse(new InputSource JavaDoc(new StringReader JavaDoc(pElement)));
518     return reh;
519   }
520
521   private class RootElementHandler extends DefaultHandler JavaDoc {
522     Attributes JavaDoc rootElementAttributes;
523     String JavaDoc rootElementURI, rootElementLocalName, rootElementQName;
524     private boolean isRootElement = true;
525     public void startElement(String JavaDoc pNamespaceURI, String JavaDoc pLocalName, String JavaDoc pQName,
526                              Attributes JavaDoc pAttr) {
527       if (isRootElement) {
528         isRootElement = false;
529         rootElementAttributes = pAttr;
530         rootElementURI = pNamespaceURI;
531         rootElementLocalName = pLocalName;
532         rootElementQName = pQName;
533       }
534     }
535   }
536
537   private String JavaDoc getContents(String JavaDoc pElement) {
538     int offset1 = pElement.indexOf('>');
539     int offset2 = pElement.lastIndexOf('<');
540     assertTrue(offset2 > offset1);
541     return pElement.substring(offset1+1, offset2);
542   }
543
544   protected void assertEquals(Attributes JavaDoc pAttr1, Attributes JavaDoc pAttr2) {
545     assertEquals(pAttr1.getLength(), pAttr2.getLength());
546     for (int i = 0; i < pAttr1.getLength(); i++) {
547        String JavaDoc uri = pAttr1.getURI(i);
548         String JavaDoc localName = pAttr1.getLocalName(i);
549         String JavaDoc value = pAttr1.getValue(i);
550         assertNotNull(value);
551         assertEquals(value, pAttr2.getValue(uri, localName));
552     }
553   }
554
555   /** <p>Tests the {@link Marshaller} property
556    * {@link Marshaller#JAXB_SCHEMA_LOCATION}.</p>
557    */

558   public void testSchemaLocation() throws Exception JavaDoc {
559     String JavaDoc s = getAllTypesElementString(true, false);
560     JAXBContext context = getFactory();
561     AllTypesElement e = (AllTypesElement) context.createUnmarshaller().unmarshal(new InputSource JavaDoc(new StringReader JavaDoc(s)));
562     StringWriter JavaDoc sw = new StringWriter JavaDoc();
563     Marshaller marshaller = context.createMarshaller();
564     marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "foo.xsd");
565     marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
566     marshaller.setProperty(Marshaller.JAXB_ENCODING, "ASCII");
567     marshaller.setProperty(JMMarshallerImpl.JAXME_XML_DECLARATION, Boolean.FALSE);
568     marshaller.marshal(e, sw);
569     String JavaDoc got = sw.toString();
570     String JavaDoc s1 = "xsi:" + XMLConstants.XML_SCHEMA_NS_ATTR + "='foo.xsd'";
571     String JavaDoc s2 = "xsi:" + XMLConstants.XML_SCHEMA_NS_ATTR + "=\"foo.xsd\"";
572     int offset1 = s.indexOf(s1);
573     int offset2 = s.indexOf(s2);
574     int offset3 = s.indexOf('>');
575     assertTrue((offset1 > 0 && offset1 < offset3)
576                || (offset2 > 0 && offset2 < offset3));
577  
578     // When validating the result, we are unsure about the
579
// order of the attributes in the outermost element.
580
RootElementHandler reh1 = getRootElementInfo(s);
581     RootElementHandler reh2 = getRootElementInfo(got);
582     assertEquals(reh1.rootElementURI, reh2.rootElementURI);
583     assertEquals(reh1.rootElementLocalName, reh2.rootElementLocalName);
584     assertEquals(reh1.rootElementAttributes, reh2.rootElementAttributes);
585     assertEquals(getContents(s), getContents(got));
586   }
587
588
589     /** Tests unmarshalling of an invalid string into a JaxMe object.
590      */

591     public void testValidator() throws Exception JavaDoc {
592         String JavaDoc invalidAddress = // Note the missing "Last"
593
"<Address xmlns=\"http://ws.apache.org/jaxme/test/misc/address\">\n" +
594             " <Name>\n" +
595             " <First>Jane</First>\n" +
596             " </Name>\n" +
597             "</Address>";
598         InputSource JavaDoc isource = new InputSource JavaDoc(new StringReader JavaDoc(invalidAddress));
599         isource.setSystemId("testValidator.xml");
600         JAXBContext context = JAXBContext.newInstance("org.apache.ws.jaxme.test.misc.address");
601         try {
602             context.createUnmarshaller().unmarshal(isource);
603             fail("No error reported.");
604         } catch (UnmarshalException e) {
605             // Ok
606
} catch (Throwable JavaDoc t) {
607             fail("Unexpected throwable " + t);
608         }
609
610         org.apache.ws.jaxme.test.misc.address.ObjectFactory of = new org.apache.ws.jaxme.test.misc.address.ObjectFactory();
611         Address address = of.createAddress();
612         address.setName(of.createAddressTypeNameType());
613         AddressType.NameType name = address.getName();
614         name.setFirst("Jane");
615         try {
616             assertFalse(context.createValidator().validate(address));
617         } catch (Throwable JavaDoc t) {
618             t.printStackTrace();
619             fail("Unexpected throwable " + t);
620         }
621     }
622 }
623
Popular Tags