KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > test > message > TestMessageElement


1 /*
2  * Copyright 2002-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 test.message;
18
19 import org.apache.axis.Message;
20 import org.apache.axis.MessageContext;
21 import org.apache.axis.server.AxisServer;
22 import org.apache.axis.client.AxisClient;
23 import org.apache.axis.encoding.DeserializationContext;
24 import org.apache.axis.message.EnvelopeBuilder;
25 import org.apache.axis.message.MessageElement;
26 import org.apache.axis.message.PrefixedQName;
27 import org.apache.axis.soap.SOAPConstants;
28 import org.apache.axis.soap.MessageFactoryImpl;
29 import org.apache.axis.utils.XMLUtils;
30 import org.w3c.dom.Document JavaDoc;
31 import org.xml.sax.Attributes JavaDoc;
32 import org.xml.sax.InputSource JavaDoc;
33 import test.AxisTestBase;
34
35 import javax.xml.namespace.QName JavaDoc;
36 import javax.xml.soap.MessageFactory JavaDoc;
37 import javax.xml.soap.Name JavaDoc;
38 import javax.xml.soap.SOAPBody JavaDoc;
39 import javax.xml.soap.SOAPBodyElement JavaDoc;
40 import javax.xml.soap.SOAPElement JavaDoc;
41 import javax.xml.soap.SOAPEnvelope JavaDoc;
42 import javax.xml.soap.SOAPMessage JavaDoc;
43 import javax.xml.soap.SOAPPart JavaDoc;
44 import javax.xml.soap.Text JavaDoc;
45 import java.io.ByteArrayInputStream JavaDoc;
46 import java.io.ByteArrayOutputStream JavaDoc;
47 import java.io.ObjectInputStream JavaDoc;
48 import java.io.ObjectOutputStream JavaDoc;
49 import java.io.StringReader JavaDoc;
50 import java.io.OutputStream JavaDoc;
51 import java.util.Iterator JavaDoc;
52
53 import junit.framework.TestSuite;
54 import junit.textui.TestRunner;
55
56 /**
57  * Test {@link MessageElement} class.
58  *
59  * @author Glyn Normington (glyn@apache.org)
60  */

61 public class TestMessageElement extends AxisTestBase {
62
63     public TestMessageElement(String JavaDoc name) {
64         super(name);
65     }
66
67     // Test JAXM methods...
68
public void testParentage() throws Exception JavaDoc {
69         SOAPElement JavaDoc parent = new MessageElement("ns", "parent");
70         SOAPElement JavaDoc child = new MessageElement("ns", "child");
71         child.setParentElement(parent);
72         assertEquals("Parent is not as set", parent, child.getParentElement());
73     }
74
75     public void testAddChild() throws Exception JavaDoc {
76         SOAPConstants sc = SOAPConstants.SOAP11_CONSTANTS;
77         EnvelopeBuilder eb = new EnvelopeBuilder(Message.REQUEST, sc);
78         DeserializationContext dc = new DeserializationContext(null, eb);
79         MessageElement parent = new MessageElement("parent.names",
80                                                 "parent",
81                                                 "parns",
82                                                 null,
83                                                 dc);
84         Name c1 = new PrefixedQName("child1.names", "child1" ,"c1ns");
85         SOAPElement JavaDoc child1 = parent.addChildElement(c1);
86         SOAPElement JavaDoc child2 = parent.addChildElement("child2");
87         SOAPElement JavaDoc child3 = parent.addChildElement("child3.names", "parns");
88         SOAPElement JavaDoc child4 = parent.addChildElement("child4",
89                                                     "c4ns",
90                                                     "child4.names");
91         SOAPElement JavaDoc child5 = new MessageElement("ns", "child5");
92         parent.addChildElement(child5);
93         SOAPElement JavaDoc c[] = {child1, child2, child3, child4, child5};
94         
95         Iterator JavaDoc children = parent.getChildElements();
96         for (int i = 0; i < 5; i++) {
97             assertEquals("Child " + (i+1) + " not found",
98                          c[i],
99                          children.next());
100         }
101         assertTrue("Unexpected child", !children.hasNext());
102        
103         Iterator JavaDoc c1only = parent.getChildElements(c1);
104         assertEquals("Child 1 not found", child1, c1only.next());
105         assertTrue("Unexpected child", !c1only.hasNext());
106     }
107
108     public void testDetachNode() throws Exception JavaDoc {
109         SOAPConstants sc = SOAPConstants.SOAP11_CONSTANTS;
110         EnvelopeBuilder eb = new EnvelopeBuilder(Message.REQUEST, sc);
111         DeserializationContext dc = new DeserializationContext(null, eb);
112         SOAPElement JavaDoc parent = new MessageElement("parent.names",
113                                                 "parent",
114                                                 "parns",
115                                                 null,
116                                                 dc);
117         SOAPElement JavaDoc child1 = parent.addChildElement("child1");
118         SOAPElement JavaDoc child2 = parent.addChildElement("child2");
119         SOAPElement JavaDoc child3 = parent.addChildElement("child3");
120
121         child2.detachNode();
122         SOAPElement JavaDoc c[] = {child1, child3};
123         
124         Iterator JavaDoc children = parent.getChildElements();
125         for (int i = 0; i < 2; i++) {
126             assertEquals("Child not found",
127                          c[i],
128                          children.next());
129         }
130         assertTrue("Unexpected child", !children.hasNext());
131     }
132
133     public void testGetCompleteAttributes() throws Exception JavaDoc {
134         MessageElement me =
135             new MessageElement("http://www.wolfram.com","Test");
136         me.addNamespaceDeclaration("pre", "http://www.wolfram2.com");
137         Attributes JavaDoc attrs = me.getCompleteAttributes();
138         assertEquals(attrs.getLength(), 1);
139     }
140     
141     public void testAddNamespaceDeclaration() throws Exception JavaDoc {
142         MessageElement me =
143             new MessageElement("http://www.wolfram.com","Test");
144         me.addNamespaceDeclaration("pre", "http://www.wolfram2.com");
145         me.addAttribute(
146             "http://www.w3.org/2001/XMLSchema-instance",
147             "type",
148             "pre:test1");
149         boolean found = false;
150         Iterator JavaDoc it = me.getNamespacePrefixes();
151         while(!found && it.hasNext()){
152             String JavaDoc prefix = (String JavaDoc)it.next();
153             if (prefix.equals("pre") &&
154                 me.getNamespaceURI(prefix).equals("http://www.wolfram2.com")) {
155                 found = true;
156             }
157         }
158         assertTrue("Did not find namespace declaration \"pre\"", found);
159     }
160     
161     public void testQNameAttrTest() throws Exception JavaDoc {
162         MessageElement me =
163             new MessageElement("http://www.wolfram.com","Test");
164         me.addAttribute(
165             "http://www.w3.org/2001/XMLSchema-instance",
166             "type",
167             new QName("http://www.wolfram2.com", "type1"));
168         MessageElement me2 =
169             new MessageElement("http://www.wolfram.com", "Child", (Object JavaDoc)"1");
170         me2.addAttribute(
171             "http://www.w3.org/2001/XMLSchema-instance",
172             "type",
173             new QName("http://www.w3.org/2001/XMLSchema", "int"));
174         me.addChildElement(me2);
175         String JavaDoc s1 = me.toString();
176         String JavaDoc s2 = me.toString();
177         assertEquals(s1, s2);
178     }
179     
180     public void testMessageElementNullOngetNamespaceURI() throws Exception JavaDoc{
181         String JavaDoc data="<anElement xmlns:ns1=\"aNamespace\" HREF=\"unknownProtocol://data\"/>";
182         data="<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Body>"+
183              data+"</SOAP-ENV:Body></SOAP-ENV:Envelope>";
184         MessageContext ctx=new MessageContext(new AxisClient());
185         DeserializationContext dser = new DeserializationContext(
186                                            new org.xml.sax.InputSource JavaDoc(new StringReader JavaDoc(data)),
187                                            ctx,
188                                            Message.REQUEST);
189         dser.parse();
190         MessageElement elem=dser.getEnvelope().getBodyByName("","anElement");
191         assertEquals("aNamespace",elem.getNamespaceURI("ns1"));
192         assertEquals("ns1",elem.getPrefix("aNamespace"));
193     }
194     
195     public void testSOAPElementMessageDoesNotHavePrefix() throws Exception JavaDoc {
196             String JavaDoc A_TAG = "A";
197             String JavaDoc A_PREFIX = "a";
198             String JavaDoc A_NAMESPACE_URI = "http://schemas.com/a";
199             String JavaDoc AA_TAG = "AA";
200
201             MessageFactory JavaDoc messageFactory = MessageFactory.newInstance();
202             SOAPMessage JavaDoc message = messageFactory.createMessage();
203             SOAPPart JavaDoc part = message.getSOAPPart();
204             SOAPEnvelope JavaDoc envelope = part.getEnvelope();
205             SOAPBody JavaDoc body = envelope.getBody();
206
207             envelope.getHeader().detachNode();
208
209             Name aName = envelope.createName(A_TAG, A_PREFIX, A_NAMESPACE_URI);
210             SOAPBodyElement JavaDoc aBodyElement = body.addBodyElement(aName);
211             aBodyElement.addChildElement(AA_TAG, A_PREFIX);
212             String JavaDoc data = envelope.toString();
213
214             MessageContext ctx = new MessageContext(new AxisClient());
215             DeserializationContext dser = new DeserializationContext(
216                     new org.xml.sax.InputSource JavaDoc(new StringReader JavaDoc(data)),
217                     ctx,
218                     Message.REQUEST);
219             dser.parse();
220             MessageElement elem = dser.getEnvelope().getBodyByName(A_NAMESPACE_URI, A_TAG);
221             Iterator JavaDoc iterator = elem.getChildElements();
222             while(iterator.hasNext()){
223                 MessageElement childElem = (MessageElement)iterator.next();
224                 Name name = childElem.getElementName();
225                 assertEquals(A_NAMESPACE_URI, name.getURI());
226                 assertEquals(AA_TAG, name.getLocalName());
227             }
228     }
229
230     public void testSerializable() throws Exception JavaDoc
231     {
232         MessageElement m1 =
233             new MessageElement("http://www.wolfram.com","Test");
234         
235         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
236         ObjectOutputStream JavaDoc oos = new ObjectOutputStream JavaDoc(baos);
237
238         oos.writeObject(m1);
239         oos.flush();
240         oos.close();
241
242         ByteArrayInputStream JavaDoc bais = new ByteArrayInputStream JavaDoc(baos.toByteArray());
243         ObjectInputStream JavaDoc ois = new ObjectInputStream JavaDoc(bais);
244         MessageElement m2 = (MessageElement)ois.readObject();
245
246         assertEquals("m1 is not the same as m2", m1, m2);
247         assertEquals("m2 is not the same as m1", m2, m1);
248     }
249     
250     public void testElementConstructor() throws Exception JavaDoc {
251         String JavaDoc xmlIn = "<h:html xmlns:xdc=\"http://www.xml.com/books\"\n" +
252                        " xmlns:h=\"http://www.w3.org/HTML/1998/html4\">\n" +
253                        " <h:head><h:title>Book Review</h:title></h:head>\n" +
254                        " <h:body>\n" +
255                        " <xdc:bookreview>\n" +
256                        " <xdc:title>XML: A Primer</xdc:title>\n" +
257                        " <h:table>\n" +
258                        " <h:tr align=\"center\">\n" +
259                        " <h:td>Author</h:td><h:td>Price</h:td>\n" +
260                        " <h:td>Pages</h:td><h:td>Date</h:td></h:tr>\n" +
261                        " <!-- here is a comment -->\n" +
262                        " <h:tr align=\"left\">\n" +
263                        " <h:td><xdc:author>Simon St. Laurent</xdc:author></h:td>\n" +
264                        " <h:td><xdc:price>31.98</xdc:price></h:td>\n" +
265                        " <h:td><xdc:pages>352</xdc:pages></h:td>\n" +
266                        " <h:td><xdc:date>1998/01</xdc:date></h:td>\n" +
267                        " <h:td><![CDATA[text content]]></h:td>\n" +
268                        " </h:tr>\n" +
269                        " </h:table>\n" +
270                        " </xdc:bookreview>\n" +
271                        " </h:body>\n" +
272                        "</h:html>";
273         
274         Document JavaDoc doc = XMLUtils.newDocument(new ByteArrayInputStream JavaDoc(xmlIn.getBytes()));
275         MessageElement me = new MessageElement(doc.getDocumentElement());
276         String JavaDoc xmlOut = me.getAsString();
277         this.assertXMLEqual(xmlIn,xmlOut);
278     }
279     
280     public void testElementConstructor2() throws Exception JavaDoc {
281         String JavaDoc xmlIn = "<!-- This file can be used to deploy the echoAttachments sample -->\n" +
282                 "<!-- using this command: java org.apache.axis.client.AdminClient attachdeploy.wsdd -->\n" +
283                 "\n" +
284                 "<!-- This deploys the echo attachment service. -->\n" +
285                 "<deployment xmlns=\"http://xml.apache.org/axis/wsdd/\" xmlns:java=\"http://xml.apache.org/axis/wsdd/providers/java\" xmlns:ns1=\"urn:EchoAttachmentsService\" >\n" +
286                 " <service name=\"urn:EchoAttachmentsService\" provider=\"java:RPC\" >\n" +
287                 " <parameter name=\"className\" value=\"samples.attachments.EchoAttachmentsService\"/>\n" +
288                 " <parameter name=\"allowedMethods\" value=\"echo echoDir\"/>\n" +
289                 " <operation name=\"echo\" returnQName=\"returnqname\" returnType=\"ns1:DataHandler\" >\n" +
290                 " <parameter name=\"dh\" type=\"ns1:DataHandler\"/>\n" +
291                 " </operation>\n" +
292                 "\n" +
293                 " <typeMapping deserializer=\"org.apache.axis.encoding.ser.JAFDataHandlerDeserializerFactory\"\n" +
294                 " languageSpecificType=\"java:javax.activation.DataHandler\" qname=\"ns1:DataHandler\"\n" +
295                 " serializer=\"org.apache.axis.encoding.ser.JAFDataHandlerSerializerFactory\"\n" +
296                 " encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"\n" +
297                 " />\n" +
298                 " </service>\n" +
299                 "\n" +
300                 "</deployment>";
301         
302         Document JavaDoc doc = XMLUtils.newDocument(new ByteArrayInputStream JavaDoc(xmlIn.getBytes()));
303         MessageElement me = new MessageElement(doc.getDocumentElement());
304         String JavaDoc xmlOut = me.getAsString();
305         System.out.println(xmlOut);
306         this.assertXMLEqual(xmlIn,xmlOut);
307     }
308
309     public void testElementConstructorUsingNamespaces() throws Exception JavaDoc {
310         String JavaDoc xmlIn = "<ns1:document xmlns:ns1=\"urn:someURI\">\n" +
311                        " <ns2:child-element xmlns:ns2=\"urn:someOtherURI\">\n" +
312                        " some text nodes insides\n" +
313                        " </ns2:child-element>\n" +
314                        "</ns1:document>";
315
316         Document JavaDoc doc = XMLUtils.newDocument(new ByteArrayInputStream JavaDoc(xmlIn.getBytes()));
317         MessageElement me = new MessageElement(doc.getDocumentElement());
318         String JavaDoc xmlOut = me.getAsString();
319         System.out.println(xmlOut);
320         // check that the String version of the XML are the same :
321
// I ensure that the namespaces declaration have not been moved
322
// this is needed when some elements are signed :
323
// we sign an element (get a Hashcode)
324
// if the serialization change that element, the Hashcode will
325
// change and the signature check will fail.
326
this.assertEquals(xmlIn, xmlOut);
327     }
328     /**
329      * Test setting the text value on a MessageElement in various ways.
330      *
331      * @throws Exception on error
332      */

333     public void testSetValue() throws Exception JavaDoc
334     {
335         MessageElement me;
336         final QName name = new QName( "urn:xyz", "foo", "xyz" );
337         final String JavaDoc value = "java";
338         // Test #1: set value via MessageElement(name, value) constructor
339
me = new MessageElement( name, value );
340         assertEquals( value, me.getValue() );
341         assertEquals( value, me.getObjectValue() );
342         // Test #2a: set value via setValue(value)
343
me = new MessageElement( name );
344         me.setValue( value );
345         assertEquals( value, me.getValue() );
346         assertEquals( value, me.getObjectValue() );
347         // Test #2b: call setValue(value) on SOAPElement w/ more than one child (illegal)
348
me = new MessageElement( name );
349         me.addTextNode("cobol");
350         me.addTextNode("fortran");
351         try
352         {
353             me.setValue( value );
354             fail("setValue() should throw an IllegalStateException when called on a SOAPElement with more than one child");
355         }
356         catch ( RuntimeException JavaDoc re )
357         {
358             assertTrue(re instanceof IllegalStateException JavaDoc);
359         }
360         // Test #2c: call setValue(value) on SOAPElement w/ a non-Text child (illegal)
361
me = new MessageElement( name );
362         me.addChildElement("pascal");
363         try
364         {
365             me.setValue( value );
366             fail("setValue() should throw an IllegalStateException when called on a SOAPElement with a non-Text child");
367         }
368         catch ( RuntimeException JavaDoc re )
369         {
370             assertTrue(re instanceof IllegalStateException JavaDoc);
371         }
372         // Test #2d: set value via setValue(value) on Text child
373
me = new MessageElement( name );
374         me.addTextNode( "c++" );
375         Object JavaDoc child = me.getChildren().get(0);
376         assertTrue( child instanceof Text JavaDoc );
377         ((Text JavaDoc)child).setValue( value );
378         assertEquals( value, me.getValue());
379         assertEquals( null, me.getObjectValue());
380         // Test #3: set value via setObjectValue(value)
381
me = new MessageElement( name );
382         me.setObjectValue( value );
383         assertEquals( value, me.getValue());
384         assertEquals( value, me.getObjectValue());
385         // Test #4: set value via addTextNode(value)
386
me = new MessageElement( name );
387         me.addTextNode( value );
388         assertEquals( value, me.getValue());
389         assertEquals( null, me.getObjectValue());
390         // Test #5: set value via dser.parse()
391
SOAPMessage JavaDoc msg = MessageFactoryImpl.newInstance().createMessage();
392         msg.getSOAPBody().addChildElement(new org.apache.axis.message.SOAPBodyElement(name, value));
393         OutputStream JavaDoc os = new ByteArrayOutputStream JavaDoc( );
394         msg.writeTo(os);
395         DeserializationContext dser = new DeserializationContext(new InputSource JavaDoc(new StringReader JavaDoc(os.toString())), new MessageContext(new AxisServer()),Message.REQUEST);
396         dser.parse();
397         me = (MessageElement) dser.getEnvelope().getBodyElements().get( 0 );
398         assertEquals( value, me.getValue());
399         assertEquals( value, me.getObjectValue());
400     }
401
402     public void testGetNodeValue() throws Exception JavaDoc {
403         String JavaDoc data = null;
404
405         data = "<anElement xmlns:ns1=\"aNamespace\"/>";
406         
407         assertTrue(getNodeValueContext(data) == null);
408         assertTrue(getNodeValueDOM(data) == null);
409
410         data = "<anElement xmlns:ns1=\"aNamespace\">FooBar</anElement>";
411         
412         assertEquals("FooBar", getNodeValueContext(data));
413         assertEquals("FooBar", getNodeValueDOM(data));
414          
415         data = "<anElement xmlns:ns1=\"aNamespace\">A&gt;B</anElement>";
416         
417         assertEquals("A>B", getNodeValueContext(data));
418         assertEquals("A>B", getNodeValueDOM(data));
419
420         data = "<anElement xmlns:ns1=\"aNamespace\"><bElement>FooBar</bElement></anElement>";
421         
422         assertTrue(getNodeValueContext(data) == null);
423         assertTrue(getNodeValueDOM(data) == null);
424
425         data = "<anElement xmlns:ns1=\"aNamespace\"><bElement>FooBar</bElement>Mixed</anElement>";
426         
427         // SAAJ 1.2 requires "Mixed" for this case.
428
assertEquals("Mixed", getNodeValueContext(data));
429         assertEquals("Mixed", getNodeValueDOM(data));
430 // assertTrue(getNodeValueContext(data) == null);
431
// assertTrue(getNodeValueDOM(data) == null);
432

433         data = "<anElement xmlns:ns1=\"aNamespace\">Foo<bElement>FooBar</bElement>Mixed</anElement>";
434         
435         assertEquals("Foo", getNodeValueContext(data));
436         assertEquals("Foo", getNodeValueDOM(data));
437     }
438
439     private String JavaDoc getNodeValueDOM(String JavaDoc data) throws Exception JavaDoc {
440         Document JavaDoc doc =
441             XMLUtils.newDocument(new org.xml.sax.InputSource JavaDoc(new StringReader JavaDoc(data)));
442         MessageElement elem = new MessageElement(doc.getDocumentElement());
443
444         assertTrue(elem.getDeserializationContext() == null);
445         return elem.getValue();
446     }
447
448     private String JavaDoc getNodeValueContext(String JavaDoc data) throws Exception JavaDoc {
449         String JavaDoc env =
450             "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Body>" +
451             data +
452             "</SOAP-ENV:Body></SOAP-ENV:Envelope>";
453         
454         MessageContext ctx = new MessageContext(new AxisClient());
455         DeserializationContext dser = new DeserializationContext(
456                            new org.xml.sax.InputSource JavaDoc(new StringReader JavaDoc(env)),
457                            ctx,
458                            Message.REQUEST);
459         dser.parse();
460
461         MessageElement elem = dser.getEnvelope().getFirstBody();
462         assertTrue(elem.getDeserializationContext() != null);
463         return elem.getValue();
464     }
465
466
467     public static void main(String JavaDoc[] args) throws Exception JavaDoc {
468         new TestRunner().doRun( new TestMessageElement( "TestMessageElement" ) );
469     }
470 }
471
Popular Tags