16.4 Advanced kSOAPNow we have seen the basic features of kSOAP. In addition, kSOAP offers limited support for SOAP arrays and document validation. We discuss these two features in this section. 16.4.1 ArraysOne of the important data types in any programming language is the array. kSOAP reads a SOAP array into a Java java.util.Vector object. Method Vector.elementAt(i) extracts the array's nth object. Depending on the arrayType, this object could be a SoapObject, a SoapPrimitive, a default Java type, or a marshaled Java object. 16.4.2 Validate Documents Using SoapTemplateIn the above examples, we take in only SOAP documents and parse them into SoapObjects as they are. However, in many cases, we require the response message to follow certain formats and wish the parser to validate it during the parsing. For example, we might require that the n:transaction-type SOAP elements in the stock trade response (Listing 16.8) contain an xsd:string value Symbol, an xsd:int value Share, an xsd:boolean value Buy, and an xsd:float value Price.
Our old friend, the ClassMap class, can validate the message. We must add into the ClassMap object a SoapObject template associated with the current parser. The SoapObject template is an empty SoapObject with information about the parent SOAP type, children (properties) element names, and their Java types. Again, the children can be templates themselves, which allows us to construct arbitrarily complex templates. We add the SoapObject template by calling the ClassMap.addTemplate() method (Listing 16.10). Listing 16.10. Validate and parse the stock trade responseXmlParser xp = new XmlParser (reader); ClassMap cm = new ClassMap (Soap.VER12); // Register Marshal for "xsd:dateTime" type Marshal md = new MarshalDate (); md.register (cm); // Register the template for validation SoapObject so = new SoapObject ("http://myns", "transaction"); so.addProperty ("Symbol", new String (")); so.addProperty ("Share", new Integer (0)); so.addProperty ("Buy", new Boolean (true)); so.addProperty ("Price", new SoapPrimitive ("xsd", "float", ")); cm.addTemplate (so); SoapEnvelope envelope = new SoapEnvelope (cm); envelope.parse (xp); SoapObject orderStatus = (SoapObject) envelope.getResult(); // ... ... If the parsing succeeds, we can proceed to extract data from orderStatus, as illustrated in Listing 16.9. If the SOAP message's n:transaction element fails to conform to the corresponding SoapObject template, the parser throws an exception and stops. |