KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > xmlpull > v1 > tests > TestSerializeWithNs


1 /* -*- c-basic-offset: 4; indent-tabs-mode: nil; -*- //------100-columns-wide------>|*/
2 // for license see accompanying LICENSE_TESTS.txt file (available also at http://www.xmlpull.org)
3

4 package org.xmlpull.v1.tests;
5
6 import junit.framework.TestCase;
7 import junit.framework.TestSuite;
8
9 import java.io.ByteArrayOutputStream JavaDoc;
10 import java.io.StringWriter JavaDoc;
11
12 import java.io.ByteArrayInputStream JavaDoc;
13 import java.io.StringReader JavaDoc;
14
15 import org.xmlpull.v1.XmlPullParser;
16 import org.xmlpull.v1.XmlPullParserFactory;
17 import org.xmlpull.v1.XmlPullParserException;
18 import org.xmlpull.v1.XmlSerializer;
19
20 /**
21  * Simple test to verify serializer (with namespaces)
22  *
23  * @author <a HREF="http://www.extreme.indiana.edu/~aslom/">Aleksander Slominski</a>
24  */

25 public class TestSerializeWithNs extends UtilTestCase {
26     private XmlPullParserFactory factory;
27     private XmlPullParser xpp;
28
29     public static void main (String JavaDoc[] args) {
30         junit.textui.TestRunner.run (new TestSuite(TestSerializeWithNs.class));
31     }
32
33     public TestSerializeWithNs(String JavaDoc name) {
34         super(name);
35     }
36
37     protected void setUp() throws XmlPullParserException {
38         factory = factoryNewInstance();
39         factory.setNamespaceAware(true);
40         // now validate that can be deserialzied
41
xpp = factory.newPullParser();
42         assertEquals(true, xpp.getFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES));
43     }
44
45     protected void tearDown() {
46     }
47
48
49     private void checkSimpleWriterResult(String JavaDoc textContent) throws Exception JavaDoc {
50         checkParserStateNs(xpp, 0, xpp.START_DOCUMENT, null, 0, null, null, null, false, -1);
51         xpp.next();
52         checkParserStateNs(xpp, 1, xpp.START_TAG, null, 0, "", "foo", null, xpp.isEmptyElementTag() /*empty*/, 0);
53         if(textContent != null) {
54             xpp.next();
55             checkParserStateNs(xpp, 1, xpp.TEXT, null, 0, null, null, textContent, false, -1);
56         }
57         xpp.next();
58         checkParserStateNs(xpp, 1, xpp.END_TAG, null, 0, "", "foo", null, false, -1);
59         xpp.next();
60         checkParserStateNs(xpp, 0, xpp.END_DOCUMENT, null, 0, null, null, null, false, -1);
61     }
62
63     public void testSimpleWriter() throws Exception JavaDoc {
64         XmlSerializer ser = factory.newSerializer();
65
66         //assert there is error if trying to write
67

68         //assert there is error if trying to write
69
try {
70             ser.startTag("", "foo");
71             fail("exception was expected of serializer if no input was set");
72         } catch(Exception JavaDoc ex) {}
73
74         ser.setOutput(null);
75
76         //assert there is error if trying to write
77
try {
78             ser.startTag("", "foo");
79             fail("exception was expected of serializer if no input was set");
80         } catch(Exception JavaDoc ex) {}
81
82         StringWriter JavaDoc sw = new StringWriter JavaDoc();
83
84         ser.setOutput(sw);
85
86         try {
87             ser.setOutput(null, null);
88             fail("exception was expected of setOutput() if output stream is null");
89         } catch(IllegalArgumentException JavaDoc ex) {}
90
91         //check get property
92

93         ser.setOutput(sw);
94
95         //assertEquals(null, ser.getOutputEncoding());
96

97         ser.startDocument("ISO-8859-1", Boolean.TRUE);
98         ser.startTag("", "foo");
99
100         //TODO: check that startTag(null, ...) is allowed
101

102         ser.endTag("", "foo");
103         ser.endDocument();
104
105
106         //xpp.setInput(new StringReader("<foo></foo>"));
107
String JavaDoc serialized = sw.toString();
108         xpp.setInput(new StringReader JavaDoc(serialized));
109
110         assertEquals(null, xpp.getInputEncoding());
111         checkSimpleWriterResult(null);
112     }
113
114
115     public void testSimpleOutputStream() throws Exception JavaDoc {
116         XmlSerializer ser = factory.newSerializer();
117
118
119         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
120         ser.setOutput(baos, "UTF-8");
121         ser.startDocument("UTF-8", null);
122         ser.startTag("", "foo");
123         final String JavaDoc text = "\"test<&>&amp;";
124         ser.text(text);
125         ser.endTag("", "foo");
126         ser.endDocument();
127
128         //check taking input form input stream
129
//byte[] binput = "<foo>test</foo>".getBytes("UTF8");
130

131         byte[] binput = baos.toByteArray();
132
133         xpp.setInput(new ByteArrayInputStream JavaDoc( binput ), "UTF-8" );
134         assertEquals("UTF-8", xpp.getInputEncoding());
135
136         //xpp.setInput(new StringReader( "<foo/>" ) );
137

138         checkSimpleWriterResult(text);
139
140     }
141
142     //TODO add test for simple namespace generation
143
public void testNamespaceGeneration() throws Exception JavaDoc {
144         XmlSerializer ser = factory.newSerializer();
145
146         StringWriter JavaDoc sw = new StringWriter JavaDoc();
147         ser.setOutput(sw);
148
149         //assertEquals(null, ser.getOutputEncoding());
150

151         ser.startDocument("ISO-8859-1", Boolean.TRUE);
152
153         ser.setPrefix("soap", "http://tm");
154         ser.startTag("", "foo");
155
156         //TODO: check that startTag(null, ...) is not allowed
157

158         ser.endTag("", "foo");
159         ser.endDocument();
160
161
162         //xpp.setInput(new StringReader("<foo></foo>"));
163
String JavaDoc serialized = sw.toString();
164         xpp.setInput(new StringReader JavaDoc(serialized));
165     }
166
167     public void testMisc() throws Exception JavaDoc {
168         XmlSerializer ser = factory.newSerializer();
169         StringWriter JavaDoc sw = new StringWriter JavaDoc();
170         ser.setOutput(sw);
171
172         assertEquals(0, ser.getDepth());
173         assertEquals(null, ser.getNamespace());
174         assertEquals(null, ser.getName());
175
176         // all comments etc
177
ser.startDocument(null, Boolean.TRUE);
178         assertEquals(0, ser.getDepth());
179         assertEquals(null, ser.getNamespace());
180         assertEquals(null, ser.getName());
181
182
183         final String JavaDoc docdecl = " foo [\n"+
184             "<!ELEMENT foo (#PCDATA|bar)* >\n"+
185             "<!ELEMENT pbar (#PCDATA) >\n"
186             +"]";
187         ser.docdecl(docdecl);
188         ser.processingInstruction("pi test");
189         final String JavaDoc iws = "\n\t";
190         ser.ignorableWhitespace(iws);
191
192         assertEquals(0, ser.getDepth());
193         assertEquals(null, ser.getNamespace());
194         assertEquals(null, ser.getName());
195
196         ser.startTag(null, "foo");
197         assertEquals(1, ser.getDepth());
198         assertEquals(null, ser.getNamespace());
199         assertEquals("foo", ser.getName());
200
201
202         //check escaping & < > " '
203
final String JavaDoc attrVal = "attrVal&<>\"''&amp;";
204         //final String attrVal = "attrVal&;";
205
ser.attribute(null, "attrName", attrVal);
206
207         assertEquals(1, ser.getDepth());
208         assertEquals(null, ser.getNamespace());
209         assertEquals("foo", ser.getName());
210
211         ser.entityRef("amp");
212         final String JavaDoc cdsect = "hello<test>\"test";
213         ser.cdsect(cdsect);
214
215         ser.setPrefix("ns1", "usri2");
216
217         assertEquals(1, ser.getDepth());
218         assertEquals(null, ser.getNamespace());
219         assertEquals("foo", ser.getName());
220
221         ser.startTag("uri1", "bar");
222         assertEquals(2, ser.getDepth());
223         assertEquals("uri1", ser.getNamespace());
224         assertEquals("bar", ser.getName());
225
226         final String JavaDoc text = "test\n\ntest";
227         char[] buf = text.toCharArray();
228         ser.text(buf, 0, buf.length);
229
230         final String JavaDoc comment = "comment B- ";
231         ser.comment(comment);
232         assertEquals(2, ser.getDepth());
233         assertEquals("uri1", ser.getNamespace());
234         assertEquals("bar", ser.getName());
235
236         assertEquals(2, ser.getDepth());
237         assertEquals("uri1", ser.getNamespace());
238         assertEquals("bar", ser.getName());
239
240
241         ser.endDocument(); // should close unclosed foo and bar start tag
242
assertEquals(0, ser.getDepth());
243         assertEquals(null, ser.getNamespace());
244         assertEquals(null, ser.getName());
245
246         // -- now check that we get back what we serialized ...
247

248         String JavaDoc serialized = sw.toString();
249         //System.out.println(getClass()+" serialized="+serialized);
250
xpp.setInput(new StringReader JavaDoc(serialized));
251         xpp.setFeature(xpp.FEATURE_PROCESS_NAMESPACES, true);
252
253         checkParserStateNs(xpp, 0, xpp.START_DOCUMENT, null, 0, null, null, null, false, -1);
254
255         xpp.nextToken();
256         checkParserStateNs(xpp, 0, xpp.DOCDECL, null, 0, null, null, false, -1);
257         String JavaDoc gotDocdecl = xpp.getText();
258         if(gotDocdecl != null) {
259             assertEquals(printable(docdecl), printable(gotDocdecl));
260         }
261
262         xpp.nextToken();
263         checkParserStateNs(xpp, 0, xpp.PROCESSING_INSTRUCTION, null, 0, null, null, "pi test", false, -1);
264
265
266         xpp.nextToken();
267         if(xpp.getEventType() == xpp.IGNORABLE_WHITESPACE) {
268             String JavaDoc expectedIws = gatherTokenText(xpp, xpp.IGNORABLE_WHITESPACE, true);
269             assertEquals(printable(iws), printable(expectedIws));
270         }
271
272         checkParserStateNs(xpp, 1, xpp.START_TAG, null, 0, "", "foo", null, false, 1);
273         checkAttribNs(xpp, 0, null, "", "attrName", attrVal);
274
275         xpp.nextToken();
276         checkParserStateNs(xpp, 1, xpp.ENTITY_REF, null, 0, null, "amp", "&", false, -1);
277
278         xpp.nextToken();
279         checkParserStateNs(xpp, 1, xpp.CDSECT, null, 0, null, null, cdsect, false, -1);
280         assertEquals(false, xpp.isWhitespace());
281
282         xpp.nextToken();
283         checkParserStateNs(xpp, 2, xpp.START_TAG, 2, "uri1", "bar", false, 0);
284
285         String JavaDoc gotText = nextTokenGathered(xpp, xpp.TEXT, false);
286         assertEquals(printable(text), printable(gotText));
287
288         //xpp.nextToken();
289
checkParserStateNs(xpp, 2, xpp.COMMENT, null, 2, null, null, comment, false, -1);
290
291         xpp.nextToken();
292         checkParserStateNs(xpp, 2, xpp.END_TAG, 2, "uri1", "bar", false, -1);
293
294         xpp.nextToken();
295         checkParserStateNs(xpp, 1, xpp.END_TAG, 0, "", "foo", false, -1);
296
297     }
298
299     private static final String JavaDoc ENV = "http://www.w3.org/2002/06/soap-envelope";
300     private static final String JavaDoc ALERTCONTROL = "http://example.org/alertcontrol";
301     private static final String JavaDoc ALERT = "http://example.org/alert";
302     private static final String JavaDoc EXPIRES = "2001-06-22T14:00:00-05:00";
303     private static final String JavaDoc MSG = "Pick up Mary at school at 2pm";
304     private static final String JavaDoc ROLE = "http://www.w3.org/2002/06/soap-envelope/role/ultimateReceiver";
305
306     // based on example from SOAP 1.2 spec http://www.w3.org/TR/soap12-part1/
307
private static final String JavaDoc SOAP12 =
308         "<env:Envelope xmlns:env=\""+ENV+"\">"+
309         "<env:Header>"+
310         "<n:alertcontrol xmlns:n=\""+ALERTCONTROL+"\""+
311         " env:mustUnderstand=\"true\""+
312         " env:role=\""+ROLE+"\">"+
313         "<n:priority>1</n:priority>"+
314         "<n:expires>"+EXPIRES+"</n:expires>"+
315         "</n:alertcontrol>"+
316         "</env:Header>"+
317         "<env:Body>"+
318         "<m:alert xmlns:m=\""+ALERT+"\" >"+
319         "<m:msg>"+MSG+"</m:msg>"+
320         "</m:alert>"+
321         "</env:Body>"+
322         "</env:Envelope>";
323
324
325     private String JavaDoc generateSoapEnvelope(String JavaDoc envPrefix,
326                                         String JavaDoc alertcontrolPrefix,
327                                         String JavaDoc alertPrefix) throws Exception JavaDoc
328     {
329         return generateSoapEnvelope(envPrefix, alertcontrolPrefix, alertPrefix,
330                                     null, null, null);
331     }
332
333     private final String JavaDoc PROPERTY_SERIALIZER_INDENTATION =
334         "http://xmlpull.org/v1/doc/properties.html#serializer-indentation";
335     private final String JavaDoc PROPERTY_SERIALIZER_LINE_SEPARATOR =
336         "http://xmlpull.org/v1/doc/properties.html#serializer-line-separator";
337     private final String JavaDoc FEATURE_SERIALIZER_ATTVALUE_USE_APOSTROPHE =
338         "http://xmlpull.org/v1/doc/features.html#serializer-attvalue-use-apostrophe";
339
340     private boolean serializerIndentationSupported;
341     private boolean serializerLineSeparatorSupported;
342     private boolean serializerUseApostropheSupported;
343
344     /** generate SOAP 1.2 envelope
345      try to use indentation
346
347      and check automtic namespace prefix declaration
348      and auto-generation of prefixes
349
350      */

351     private String JavaDoc generateSoapEnvelope(String JavaDoc envPrefix,
352                                         String JavaDoc alertcontrolPrefix,
353                                         String JavaDoc alertPrefix,
354                                         Boolean JavaDoc attvalueUseApostrophe,
355                                         String JavaDoc indentation,
356                                         String JavaDoc lineSeparator
357                                        )
358         throws Exception JavaDoc
359     {
360         XmlSerializer ser = factory.newSerializer();
361         StringWriter JavaDoc sw = new StringWriter JavaDoc();
362         ser.setOutput(sw);
363
364         if(attvalueUseApostrophe !=null) {
365             try {
366                 ser.setFeature(FEATURE_SERIALIZER_ATTVALUE_USE_APOSTROPHE,
367                                attvalueUseApostrophe.booleanValue());
368                 if(!serializerUseApostropheSupported) {
369                     PackageTests.addNote(
370                         "* feature "
371                             +FEATURE_SERIALIZER_ATTVALUE_USE_APOSTROPHE+" is supported\n");
372                     serializerUseApostropheSupported = true;
373                 }
374             } catch(Exception JavaDoc ex) {
375                 // ignore if optional feature not supported
376
}
377         }
378         if(indentation !=null) {
379             try {
380                 ser.setProperty(PROPERTY_SERIALIZER_INDENTATION, indentation);
381                 if(!serializerIndentationSupported) {
382                     PackageTests.addNote(
383                         "* property "
384                             +PROPERTY_SERIALIZER_INDENTATION+" is supported\n");
385                     serializerIndentationSupported = true;
386                 }
387             } catch(Exception JavaDoc ex) {
388                 // ignore if optional property not supported
389
}
390         }
391         if(lineSeparator !=null) {
392             try {
393                 ser.setProperty(PROPERTY_SERIALIZER_LINE_SEPARATOR, lineSeparator);
394                 if(!serializerLineSeparatorSupported) {
395                     PackageTests.addNote(
396                         "* property "
397                             +PROPERTY_SERIALIZER_LINE_SEPARATOR+" is supported\n");
398                     serializerLineSeparatorSupported = true;
399                 }
400             } catch(Exception JavaDoc ex) {
401                 // ignore if optional property not supported
402
}
403         }
404
405         // all comments etc
406
ser.startDocument(null, Boolean.TRUE);
407
408         if(envPrefix != null) ser.setPrefix(envPrefix, ENV);
409         ser.startTag(ENV, "Envelope");
410         ser.startTag(ENV, "Header");
411
412         if(alertcontrolPrefix != null) ser.setPrefix(alertcontrolPrefix, ALERTCONTROL);
413         ser.startTag(ALERTCONTROL, "alertcontrol");
414         ser.attribute(ENV, "mustUnderstand", "true");
415         ser.attribute(ENV, "role", ROLE);
416
417         ser.startTag(ALERTCONTROL, "priority");
418         ser.text("1");
419         ser.endTag(ALERTCONTROL, "priority");
420
421         ser.startTag(ALERTCONTROL, "expires");
422         ser.text(EXPIRES);
423         ser.endTag(ALERTCONTROL, "expires");
424
425         ser.endTag(ALERTCONTROL, "alertcontrol");
426
427         ser.endTag(ENV, "Header");
428
429         ser.startTag(ENV, "Body");
430
431         if(alertPrefix != null) ser.setPrefix(alertPrefix, ALERT);
432         ser.startTag(ALERT, "alert");
433
434         ser.startTag(ALERT, "msg");
435         ser.text(MSG);
436         ser.endTag(ALERT, "msg");
437
438         ser.endTag(ALERT, "alert");
439
440
441         ser.endTag(ENV, "Body");
442
443         ser.endTag(ENV, "Envelope");
444
445         ser.endDocument();
446
447         String JavaDoc s = sw.toString();
448
449         return s;
450     }
451
452     //setPrefix check that prefix is not duplicated ...
453

454     public void testSetPrefix() throws Exception JavaDoc {
455         //TODO redeclaring defult namespace
456

457
458         checkTestSetPrefixSoap(SOAP12);
459         checkTestSetPrefixSoap(generateSoapEnvelope("env", "n", "m"));
460         checkTestSetPrefixSoap(generateSoapEnvelope(null, null, "m"));
461         checkTestSetPrefixSoap(generateSoapEnvelope("env", null, "m"));
462         checkTestSetPrefixSoap(generateSoapEnvelope("env", "", ""));
463
464
465         String JavaDoc generated = generateSoapEnvelope("", "n", "m");
466         //System.err.println(getClass()+" generated="+generated);
467

468         // 1 is for one extra namespace must be added to declare attrbute mustUnderstan in SOAP-ENV namespace
469
checkTestSetPrefixSoap(generated, 1);
470
471
472         checkTestSetPrefixSoap(generateSoapEnvelope("", null, "m"),1);
473
474         //check optional pretty printing
475
checkTestSetPrefixSoap(generateSoapEnvelope("env", "n", "m", Boolean.FALSE, null, null));
476         checkTestSetPrefixSoap(generateSoapEnvelope("env", "n", "m", Boolean.TRUE, null, null));
477         checkTestSetPrefixSoap(generateSoapEnvelope("env", "n", "m", null, " ", null));
478         checkTestSetPrefixSoap(generateSoapEnvelope("env", "n", "m", null, "\t", null));
479         checkTestSetPrefixSoap(generateSoapEnvelope("env", "n", "m", null, " ", null));
480         String JavaDoc s = generateSoapEnvelope("env", "n", "m", Boolean.TRUE, " ", "\n");
481         //System.out.println(getClass()+" envelope="+generateSoapEnvelope("", "n", "m"));
482
checkTestSetPrefixSoap(s);
483     }
484
485     private void checkTestSetPrefixSoap(String JavaDoc soapEnvelope) throws Exception JavaDoc {
486         checkTestSetPrefixSoap(soapEnvelope, 0);
487     }
488
489     // run test using checkParserStateNs()
490
private void checkTestSetPrefixSoap(String JavaDoc soapEnvelope, int extraNs) throws Exception JavaDoc {
491
492         //compare that XML representation of soapEnvelope is as desired
493
assertXmlEquals(SOAP12, soapEnvelope);
494
495         xpp.setInput(new StringReader JavaDoc(soapEnvelope));
496
497         xpp.setFeature(xpp.FEATURE_PROCESS_NAMESPACES, true);
498
499         checkParserStateNs(xpp, 0, xpp.START_DOCUMENT, null, 0, null, null, null, false, -1);
500         xpp.next();
501         checkParserStateNs(xpp, 1, xpp.START_TAG, 1, ENV, "Envelope", false /*empty*/, 0);
502         xpp.nextTag();
503         checkParserStateNs(xpp, 2, xpp.START_TAG, 1, ENV, "Header", false /*empty*/, 0);
504         xpp.nextTag();
505         checkParserStateNs(xpp, 3, xpp.START_TAG,
506                            2+extraNs, ALERTCONTROL, "alertcontrol", false /*empty*/, 2);
507         checkAttribNs(xpp, 0, ENV, "mustUnderstand", "true");
508         checkAttribNs(xpp, 1, ENV, "role", ROLE);
509
510         xpp.nextTag();
511         checkParserStateNs(xpp, 4, xpp.START_TAG, 2+extraNs, ALERTCONTROL, "priority", false /*empty*/, 0);
512         String JavaDoc text = xpp.nextText();
513         assertEquals("1", text);
514         xpp.nextTag();
515         checkParserStateNs(xpp, 4, xpp.START_TAG, 2+extraNs, ALERTCONTROL, "expires", false /*empty*/, 0);
516         text = xpp.nextText();
517         assertEquals(EXPIRES, text);
518         xpp.nextTag();
519         checkParserStateNs(xpp, 3, xpp.END_TAG, 2+extraNs, ALERTCONTROL, "alertcontrol", false, -1);
520         xpp.nextTag();
521         checkParserStateNs(xpp, 2, xpp.END_TAG, 1, ENV, "Header", false, -1);
522         xpp.nextTag();
523         checkParserStateNs(xpp, 2, xpp.START_TAG, 1, ENV, "Body", false /*empty*/, 0);
524
525         xpp.nextTag();
526         checkParserStateNs(xpp, 3, xpp.START_TAG, 2, ALERT, "alert", false /*empty*/, 0);
527         xpp.nextTag();
528         checkParserStateNs(xpp, 4, xpp.START_TAG, 2, ALERT, "msg", false /*empty*/, 0);
529         text = xpp.nextText();
530         assertEquals(MSG, text);
531         xpp.nextTag();
532         checkParserStateNs(xpp, 3, xpp.END_TAG, 2, ALERT, "alert", false, -1);
533         xpp.nextTag();
534         checkParserStateNs(xpp, 2, xpp.END_TAG, 1, ENV, "Body", false, -1);
535         xpp.nextTag();
536         checkParserStateNs(xpp, 1, xpp.END_TAG, 1, ENV, "Envelope", false, -1);
537         xpp.next();
538         checkParserStateNs(xpp, 0, xpp.END_DOCUMENT, null, 0, null, null, null, false, -1);
539
540         checkTestSetPrefixSoap2(soapEnvelope);
541     }
542
543     // run test using parser.require()
544
private void checkTestSetPrefixSoap2(String JavaDoc soapEnvelope) throws Exception JavaDoc {
545         xpp.setInput(new StringReader JavaDoc(soapEnvelope));
546         xpp.setFeature(xpp.FEATURE_PROCESS_NAMESPACES, true);
547
548         xpp.require(xpp.START_DOCUMENT, null, null);
549
550         xpp.next(); // essentially moveToContent()
551
xpp.require(xpp.START_TAG, ENV, "Envelope");
552
553         xpp.nextTag();
554         xpp.require(xpp.START_TAG, ENV, "Header");
555
556         xpp.nextTag();
557         xpp.require(xpp.START_TAG, ALERTCONTROL, "alertcontrol");
558         String JavaDoc mustUderstand = xpp.getAttributeValue(ENV, "mustUnderstand");
559         assertEquals("true", mustUderstand);
560         String JavaDoc role = xpp.getAttributeValue(ENV, "role");
561         assertEquals(ROLE, role);
562
563         xpp.nextTag();
564         xpp.require(xpp.START_TAG, ALERTCONTROL, "priority");
565         String JavaDoc text = xpp.nextText();
566         assertEquals("1", text);
567         //Integer.parseInt(text);
568

569         xpp.nextTag();
570         xpp.require(xpp.START_TAG, ALERTCONTROL, "expires");
571         text = xpp.nextText();
572         assertEquals(EXPIRES, text);
573
574         xpp.nextTag();
575         xpp.require(xpp.END_TAG, ALERTCONTROL, "alertcontrol");
576
577         xpp.nextTag();
578         xpp.require(xpp.END_TAG, ENV, "Header");
579
580         xpp.nextTag();
581         xpp.require(xpp.START_TAG, ENV, "Body");
582
583         xpp.nextTag();
584         xpp.require(xpp.START_TAG, ALERT, "alert");
585
586         xpp.nextTag();
587         xpp.require(xpp.START_TAG, ALERT, "msg");
588
589         text = xpp.nextText();
590         assertEquals(MSG, text);
591
592         xpp.nextTag();
593         xpp.require(xpp.END_TAG, ALERT, "alert");
594
595         xpp.nextTag();
596         xpp.require(xpp.END_TAG, ENV, "Body");
597
598         xpp.nextTag();
599         xpp.require(xpp.END_TAG, ENV, "Envelope");
600
601         xpp.next();
602         xpp.require(xpp.END_DOCUMENT, null, null);
603     }
604
605
606     public void testConflictingDefaultNs() throws Exception JavaDoc {
607         XmlSerializer ser = factory.newSerializer();
608
609         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
610         ser.setOutput(baos, "UTF8");
611
612         ser.setPrefix("", "namesp");
613         ser.setPrefix("ns1", "namesp1");
614         ser.setPrefix("ns2", "namesp2");
615         try {
616             ser.startTag("", "foo");
617             fail("exception was expected when default namespace can not be declared");
618         } catch(IllegalStateException JavaDoc ex) {
619             //
620
}
621     }
622
623
624     public void testMultipleOverlappingNamespaces() throws Exception JavaDoc {
625         XmlSerializer ser = factory.newSerializer();
626
627         //<section xmlns='urn:com:books-r-us'>
628
// <!-- 2 --> <title>Book-Signing Event</title>
629
// <!-- 3 --> <signing>
630
// <!-- 4 --> <author title="Mr" name="Vikram Seth" />
631
// <!-- 5 --> <book title="A Suitable Boy" price="$22.95" />
632
// </signing>
633
// </section>
634

635
636         // check namespaces generation with explicit prefixes
637

638         // byte[] binput = ("<foo xmlns='namesp' xmlns:ns1='namesp1' xmlns:ns2='namesp2'>"+
639
// "<ns1:bar xmlns:ns1='x1' xmlns:ns3='namesp3' xmlns='n1'>"+
640
// "<ns2:gugu a1='v1' ns2:a2='v2' xml:lang='en' ns1:a3=\"v3\"/>"+
641
// "<baz xmlns:ns1='y1'></baz>"+
642
// "</ns1:bar></foo>").getBytes("US-ASCII");
643
ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
644         ser.setOutput(baos, "UTF8");
645
646         ser.startDocument(null, null);
647         ser.setPrefix("", "namesp");
648         ser.setPrefix("ns1", "namesp1");
649         ser.setPrefix("ns2", "namesp2");
650         ser.startTag("namesp", "foo");
651
652         ser.setPrefix("ns1", "x1");
653         ser.setPrefix("ns3", "namesp3");
654         ser.setPrefix("", "namesp1");
655         ser.startTag("x1", "bar");
656
657         ser.startTag("namesp2", "gugu");
658         ser.attribute("", "a1", "v1");
659         ser.attribute("namesp2", "a2", "v2" );
660         ser.attribute("http://www.w3.org/XML/1998/namespace", "lang", "en");
661         ser.attribute("x1", "a3", "v3");
662
663         ser.endTag("namesp2", "gugu");
664
665         ser.setPrefix("ns1", "y1");
666         ser.startTag("namesp1", "baz");
667
668         ser.endTag("namesp1", "baz");
669
670         ser.endTag("x1", "bar");
671
672         ser.endTag("namesp", "foo");
673         ser.endDocument();
674
675
676         byte[] binput = baos.toByteArray();
677
678         //System.out.println(getClass().getName()+"serialized="+new String(binput, "US-ASCII"));
679

680         xpp.setInput(new ByteArrayInputStream JavaDoc( binput ), "US-ASCII" );
681         assertEquals("US-ASCII", xpp.getInputEncoding());
682
683         checkParserStateNs(xpp, 0, xpp.START_DOCUMENT, null, 0, null, null, null, false, -1);
684
685         xpp.next();
686         checkParserStateNs(xpp, 1, xpp.START_TAG, null, 3, "namesp", "foo", null, false, 0);
687         assertEquals(0, xpp.getNamespaceCount(0));
688         assertEquals(3, xpp.getNamespaceCount(1));
689         checkNamespace(xpp, 0, null, "namesp", true);
690         checkNamespace(xpp, 1, "ns1", "namesp1", true);
691         checkNamespace(xpp, 2, "ns2", "namesp2", true);
692
693         xpp.next();
694         checkParserStateNs(xpp, 2, xpp.START_TAG, "ns1", 6, "x1", "bar", null, false, 0);
695         assertEquals(0, xpp.getNamespaceCount(0));
696         assertEquals(3, xpp.getNamespaceCount(1));
697         assertEquals(6, xpp.getNamespaceCount(2));
698         checkNamespace(xpp, 3, "ns1", "x1", true);
699         checkNamespace(xpp, 4, "ns3", "namesp3", true);
700         checkNamespace(xpp, 5, null, "namesp1", true);
701
702         xpp.next();
703         checkParserStateNs(xpp, 3, xpp.START_TAG, "ns2", 6, "namesp2", "gugu", null, true, 4);
704         assertEquals(6, xpp.getNamespaceCount(2));
705         assertEquals(6, xpp.getNamespaceCount(3));
706         assertEquals("x1", xpp.getNamespace("ns1"));
707         assertEquals("namesp2", xpp.getNamespace("ns2"));
708         assertEquals("namesp3", xpp.getNamespace("ns3"));
709         checkAttribNs(xpp, 0, null, "", "a1", "v1");
710         checkAttribNs(xpp, 1, "ns2", "namesp2", "a2", "v2");
711         checkAttribNs(xpp, 2, "xml", "http://www.w3.org/XML/1998/namespace", "lang", "en");
712         checkAttribNs(xpp, 3, "ns1", "x1", "a3", "v3");
713
714         xpp.next();
715         checkParserStateNs(xpp, 3, xpp.END_TAG, "ns2", 6, "namesp2", "gugu", null, false, -1);
716
717         xpp.next();
718         checkParserStateNs(xpp, 3, xpp.START_TAG, null, 7, "namesp1", "baz", null, xpp.isEmptyElementTag(), 0);
719         assertEquals(0, xpp.getNamespaceCount(0));
720         assertEquals(3, xpp.getNamespaceCount(1));
721         assertEquals(6, xpp.getNamespaceCount(2));
722         assertEquals(7, xpp.getNamespaceCount(3));
723         checkNamespace(xpp, 6, "ns1", "y1", true);
724         assertEquals("y1", xpp.getNamespace("ns1"));
725         assertEquals("namesp2", xpp.getNamespace("ns2"));
726         assertEquals("namesp3", xpp.getNamespace("ns3"));
727
728         xpp.next();
729         checkParserStateNs(xpp, 3, xpp.END_TAG, null, 7, "namesp1", "baz", null, false, -1);
730         assertEquals("y1", xpp.getNamespace("ns1"));
731         assertEquals("namesp2", xpp.getNamespace("ns2"));
732         assertEquals("namesp3", xpp.getNamespace("ns3"));
733
734         // check that declared namespaces can be accessed for current end tag
735
assertEquals(3, xpp.getDepth());
736         assertEquals(6, xpp.getNamespaceCount(2));
737         assertEquals(7, xpp.getNamespaceCount(3));
738
739         // chekc that namespace is accessible by direct addresssing
740
assertEquals(null, xpp.getNamespacePrefix(0));
741         assertEquals("namesp", xpp.getNamespaceUri(0));
742         assertEquals("ns1", xpp.getNamespacePrefix(1));
743         assertEquals("namesp1", xpp.getNamespaceUri(1));
744         assertEquals("ns1", xpp.getNamespacePrefix(3));
745         assertEquals("x1", xpp.getNamespaceUri(3));
746         assertEquals("ns1", xpp.getNamespacePrefix(6));
747         assertEquals("y1", xpp.getNamespaceUri(6));
748
749
750         xpp.next();
751         checkParserStateNs(xpp, 2, xpp.END_TAG, "ns1", 6, "x1", "bar", null, false, -1);
752         // check that namespace is undelcared
753
assertEquals("x1", xpp.getNamespace("ns1"));
754
755         xpp.next();
756         checkParserStateNs(xpp, 1, xpp.END_TAG, null, 3, "namesp", "foo", null, false, -1);
757
758         assertEquals("namesp1", xpp.getNamespace("ns1"));
759         assertEquals("namesp2", xpp.getNamespace("ns2"));
760         assertEquals(null, xpp.getNamespace("ns3"));
761
762         xpp.next();
763         checkParserStateNs(xpp, 0, xpp.END_DOCUMENT, null, 0, null, null, null, false, -1);
764         assertEquals(null, xpp.getNamespace("ns1"));
765         assertEquals(null, xpp.getNamespace("ns2"));
766         assertEquals(null, xpp.getNamespace("ns3"));
767
768
769     }
770
771     private void assertXmlEquals(String JavaDoc expectedXml, String JavaDoc actualXml)
772         throws Exception JavaDoc
773     {
774         XmlPullParser expect = factory.newPullParser();
775         expect.setInput(new StringReader JavaDoc(expectedXml));
776         XmlPullParser actual = factory.newPullParser();
777         actual.setInput(new StringReader JavaDoc(actualXml));
778         while(true) {
779             expect.next();
780             actual.next();
781             assertXml("inconsistent event type", expect, actual,
782                       expect.TYPES[ expect.getEventType() ],
783                       actual.TYPES[ actual.getEventType() ]
784                      );
785             if(expect.getEventType() == expect.END_DOCUMENT) {
786                 break;
787             }
788             if(expect.getEventType() == expect.START_TAG
789                || expect.getEventType() == expect.END_TAG )
790             {
791                 assertXml("tag names", expect, actual,
792                           expect.getName(), actual.getName());
793                 assertXml("tag namespaces", expect, actual,
794                           expect.getNamespace(), actual.getNamespace());
795                 if(expect.getEventType() == expect.START_TAG) {
796                     // check consisteny of attributes -- allow them to be in any order
797
int expectAttrCount = expect.getAttributeCount();
798                     assertXml("attributes count", expect, actual,
799                               ""+expectAttrCount, ""+actual.getAttributeCount());
800                     for (int i = 0; i < expectAttrCount; i++)
801                     {
802                         String JavaDoc expectAttrNamespace = expect.getAttributeNamespace(i);
803                         String JavaDoc expectAttrName = expect.getAttributeName(i);
804                         String JavaDoc expectAttrType = expect.getAttributeType(i);
805                         String JavaDoc expectAttrValue = expect.getAttributeValue(i);
806                         boolean expectAttrDefault = expect.isAttributeDefault(i);
807
808                         // find this attribute actual position
809
int actualPos = -1;
810                         for (int j = 0; j < expectAttrCount; j++)
811                         {
812                             if(expectAttrNamespace.equals(actual.getAttributeNamespace(j))
813                                && expectAttrName.equals(actual.getAttributeName(j)))
814                             {
815                                 actualPos = j;
816                                 break;
817                             }
818                         }
819                         String JavaDoc expectN = expectAttrNamespace+":"+expectAttrName;
820                         if(actualPos == -1) {
821                             fail("could not find expected attribute "+expectN
822                                      +" actual parser "+actual.getPositionDescription());
823                         }
824
825                         //and compare ...
826
assertXml("attribute "+expectN+" namespace", expect, actual,
827                                   expectAttrNamespace, actual.getAttributeNamespace(actualPos) );
828                         assertXml("attribute "+expectN+" name", expect, actual,
829                                   expectAttrName, actual.getAttributeName(actualPos) );
830                         assertXml("attribute "+expectN+" type", expect, actual,
831                                   expectAttrType, actual.getAttributeType(actualPos) );
832                         assertXml("attribute "+expectN+" value", expect, actual,
833                                   expectAttrValue, actual.getAttributeValue(actualPos) );
834                         assertXml("attribute "+expectN+" default", expect, actual,
835                                   ""+expectAttrDefault, ""+actual.isAttributeDefault(actualPos) );
836                     }
837                 }
838             } else if(expect.getEventType() == expect.TEXT) {
839                 assertXml("text content", expect, actual,
840                           expect.getText(), actual.getText());
841             } else {
842                 fail("unexpected event type "+expect.getEventType()+" "+expect.getPositionDescription());
843             }
844             //System.err.print(".");
845
}
846         //System.err.println("\nOK");
847
}
848
849     private static void assertXml(String JavaDoc formatted,
850                                   XmlPullParser pExpected, XmlPullParser pActual,
851                                   String JavaDoc expected, String JavaDoc actual
852                                  )
853     {
854         if((expected != null && !expected.equals(actual))
855            || (expected == null && actual != null))
856         {
857             fail(formatted
858                      +" expected:<"+expected+"> but was:<"+actual+">"
859                      +" (expecte parser position:"+pExpected.getPositionDescription()
860                      +" and actual parser positon:"+pActual.getPositionDescription()
861
862                 );
863         }
864     }
865 }
866
867
Popular Tags