Home > Articles > Programming > Java

This chapter is from the book

Objects in XML: The SOAP Data Model

As you saw in Chapter 2, XML has an extremely rich structure—and the possible contents of an XML data model, which include mixed content, substitution groups, and many other concepts, are a lot more complex than the data/objects in most modern programming languages. This means that there isn't always an easy way to map any given XML Schema into familiar structures such as classes in Java. The SOAP authors recognized this problem, so (knowing that programmers would like to send Java/C++/VB objects in SOAP envelopes) they introduced two concepts: the SOAP data model and the SOAP encoding. The data model is an abstract representation of data structures such as you might find in Java or C#, and the encoding is a set of rules to map that data model into XML so you can send it in SOAP messages.

Object Graphs

The SOAP data model g is about representing graphs of nodes, each of which may be connected via directional edges to other nodes. The nodes are values, and the edges are labels. Figure 3.6 shows a simple example: the data model for a Product in SkatesTown's database, which you saw earlier.

Figure 3.6Figure 3.6 An example SOAP data model






In Java, the object representing this structure might look like this:

class Product {
  String description;
  String sku;
  double unitPrice;
  String name;
  String type;
  int numInStock;
}

Nodes may have outgoing edges, in which case they're known as compound values, or only incoming edges, in which case they're simple values. All the nodes around the edge of the example are simple values. The one in the middle is a compound value.

When the edges coming out of a compound value node have names, we say the node represents a structure. The edge names (also known as accessors) are the equivalent of field names in Java, each one pointing to another node which contains the value of the field. The node in the middle is our Product reference, and it has an outgoing edge for each field of the structure.

When a node has outgoing edges that are only distinguished by position (the first edge, the second edge, and so on), the node represents an array. A given compound value node may represent either a structure or an array, but not both.

Sometimes it's important for a data model to refer to the same value more than once—in that case, you'll see a node with more than one incoming edge (see Figure 3.7). These values are called multireference values, or multirefs.

Figure 3.7Figure 3.7 Multireference values

The model in this example shows that someone named Joe has a sister named Cheryl, and they both share a pet named Fido. Because the two pet edges both point at the same node, we know it's exactly the same dog, not two different dogs who happen to share the name Fido.

With this simple set of concepts, you can represent most common programming language constructs in languages like C#, JavaScript, Perl, or Java. Of course, the data model isn't very useful until you can read and write it in SOAP messages.

The SOAP Encoding

When you want to take a SOAP data model and write it out as XML (typically in a SOAP message), you use the SOAP encoding g. Like most things in the Web services world, the SOAP encoding has a URI to identify it, which for SOAP 1.2 is http://www.w3.org/2003/05/soap-encoding. When serializing XML using the encoding rules, it's strongly recommended that processors use the special encodingStyle attribute (in the SOAP envelope namespace) to indicate that SOAP encoding is in use, by using this URI as the value for the attribute. This attribute can appear on headers or their children, bodies or their children, and any child of the Detail element in a fault. When a processor sees this attribute on an element, it knows that the element and all its children follow the encoding rules.

SOAP 1.1 Difference: encodingStyle

In SOAP 1.1, the encodingStyle attribute could appear anywhere in the message, including on the SOAP envelope elements (Body, Header, Envelope). In SOAP 1.2, it may only appear in the three places mentioned in the text.

The encoding is straightforward: it says when writing out a data model, each outgoing edge becomes an XML element, which contains either a text value (if the edge points to a terminal node) or further subelements (if the edge points to a node which itself has outgoing edges). The earlier product example would look something like this:

<product soapenv:encodingStyle="http://www.w3.org/2003/05/soap-encoding">
  <sku>947-TI</sku>
  <name>Titanium Glider</name>
  <type>skateboard</type>
  <desc>Street-style titanium skateboard.</desc>
  <price>129.00</price>
  <inStock>36</inStock>
</product>

If you want to encode a graph of objects that might contain multirefs, you can't write the data in the straightforward way we've been using, since you'll have one of two problems: Either you'll lose the information that two or more encoded nodes are identical, or (in the case of circular references) you'll get into an infinite regress. Here's an example: If the structure from Figure 3.7 included an edge called owner back from the pet to the person, we might see a structure like the one in Figure 3.8.

If we tried to encode this with a naïve system that simply followed edges and turned them into elements, we might get something like this:

<person soapenv:encodingStyle="http://www.w3.org/2003/05/soap-encoding">
 <name>Joe</name>
 <pet>
  <name>Fido</name>
  <owner>
   <name>Joe</name>
   <pet>
    --uh oh! stack overflow on the way!--

Figure 3.8Figure 3.8 An object graph with a loop

Luckily the SOAP encoding has a way to deal with this situation: multiref encoding. When you encode an object that you want to refer to elsewhere, you use an ID attribute to give it an anchor. Then, instead of directly encoding the data for a second reference to that object, you can encode a reference to the already-serialized object using the ref attribute. Here's the previous example using multirefs:

<person id="1" soapenv:encodingStyle="http://www.w3.org/2003/05/soap-encoding">
 <name>Joe</name>
 <pet id="2">
  <name>Fido</name>
  <owner ref="#1"/> <!-- refer to the person -->
 </pet>
</person>

Much nicer. Notice that in this example you see an id of 2 on Fido, even though nothing in this serialization refers to him. This is a common pattern that saves time on processors while they serialize object graphs. If they only put IDs on objects that were referred to multiple times, they would need to walk the entire graph of objects before writing any XML in order to figure that out. Instead, many serializers always put an ID on any object (any nonsimple value) that might potentially be referenced later. If there is no further reference, then you've serialized an extra few bytes—no big deal. If there is, you can notice that the object has been written before and write out a ref attribute instead of reserializing it.

SOAP 1.1 Differences: Multirefs

The href attribute that was used to point to the data in SOAP 1.1 has changed to ref in SOAP 1.2.

Multirefs in SOAP 1.1 must be serialized as independent elements, which means as immediate children of the SOAP:Body element. This means that when you receive a SOAP body, it may have multiref serializations either before or after the real body element (the one you care about). Here's an example:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding">
 <soap:Body>
 <!-- Here is the multiref -->
 <multiRef id="obj0" soapenc:root="0" xsi:type="myNS:Part"
soapenv:encodingStyle="http://www.w3.org/2003/05/soap-encoding"> <sku>SJ-47</sku> </multiRef> <!-- Here is the method element --> <myMultirefMethod soapenc:root="1" soapenv:encodingStyle= "http://www.w3.org/2003/05/soap-encoding"> <arg href="#obj0"/> </myMultirefMethod> <!-- The multiref could also have appeared here --> </soap:Body> </soap:Envelope>

This is the reason for the SOAP 1.1 root attribute (which you can see in the example). Multiref serializations typically have the root attribute set to 0; the real body element has a root="1" attribute, meaning it's the root of the serialization tree of the SOAP data model. When serializing a SOAP message 1.1, most processors place the multiref serializations after the main body element; this makes it much easier for the serialization code to do its work. Each time they encounter a new object to serialize, they automatically encode a forward reference instead (keeping track of which IDs go with which objects), just in case the object was referred to again later in the serialization. Then, after the end of the main body element, they write out all the object serializations in a row. This means that all objects are written as multirefs whenever multirefs are enabled, which can be expensive (especially if there aren't many multiple references). SOAP 1.2 fixes this problem by allowing inline multirefs. When serializing a data model, a SOAP 1.2 engine is allowed to put an ID attribute on an inline serialization, like this:

<SOAP:Body>
  <method>
   <arg1 id="1" xsi:type="xsd:string">Foo</arg1>
   <arg2 href="#1"/>
 </method>
</SOAP:Body>

Now, making a serialized object available for multireferencing is as easy as dropping an id attribute on it. Also, this approach removes the need for the root attribute, which is no longer present in SOAP 1.2.

Encoding Arrays

The XML encoding for an array in the SOAP object model looks like this:

<myArray soapenc:itemType="xsd:string"
     soapenc:arraySize="3">
 <item>Huey</item>
 <item>Duey</item>
 <item>Louie</item>
</myArray>

This represents an array of three strings. The itemType attribute on the array element tells us what kind of things are inside, and the arraySize attribute tells us how many of them to expect. The name of the elements inside the array (item in this example) doesn't matter to SOAP processors, since the items in an array are only distinguishable by position. This means that the ordering of items in the XML encoding is important.

The arraySize attribute defaults to "*," a special value indicating an unbounded array (just like [] in Java—an int[] is an unbounded array of ints).

Multidimensional arrays are supported by listing each dimension in the arraySize attribute, separated by spaces. So, a 2x2 array has an arraySize of "2 x 2." You can use the special "*" value to make one dimension of a multidimensional array unbounded, but it may only be the first dimension. In other words, arraySize="* 3 4" is OK, but arraySize="3 * 4" isn't.

Multidimensional arrays are serialized as a single list of items, in row-major order (across each row and then down). For this two-dimensional array of size 2x2

    	0			1
    	Northwest	Northeast
    	Southwest	Southeast

the serialization would look like this:

<myArray soapenc:itemType="xsd:string"
     soapenc:arraySize="2 2">
 <item>Northwest</item>
 <item>Northeast</item>
 <item>Southwest</item>
 <item>Southeast</item>
</myArray>

SOAP 1.1 Differences: Arrays

One big difference between the SOAP 1.1 and SOAP 1.2 array encodings is that in SOAP 1.1, the dimensionality and the type of the array are conflated into a single value (arrayType), which the processor needs to parse into component pieces. Here are some 1.1 examples:

arrayType Value

Description

xsd:int[5]

An array of five integers

xsd:int[][5]

An array of five integer arrays

xsd:int[,][5]

An array of five two-dimensional arrays of integers

p:Person[5]

An array of five people

xsd:string[2,3]

A 2x3, two-dimensional array of strings

In SOAP 1.2, the itemType attribute contains only the types of the array elements. The dimensions are now in a separate arraySize attribute, and multidimensionality has been simplified.

SOAP 1.1 also supports sparse arrays (arrays with missing values, mostly used for certain kinds of database updates) and partially transmitted arrays (arrays that are encoded starting at an offset from the beginning of the array). To support sparse arrays, each item within an array encoding can optionally have a position attribute, which indicates the item's position in the array, counting from zero. Here's an example:

<myArray soapenc:arrayType="xsd:string[3]">
 <item soapenc:position="[1]">I'm the second element</item>
</myArray>

This would represent an array that has no first value, the passed string as the second element, and no third element. The same value can be encoded as a partially transmitted array by using the offset attribute, which indicates the index at which the encoded array begins:

<myArray soapenc:arrayType="xsd:string[3]" soapenc:offset="[1]">
 <item>I'm the second element</item>
</myArray>

Due to several factors, including not much uptake in usage and interoperability problems when they were used, these complex array encodings were removed from the SOAP 1.2 version.

Encoding-Specific Faults

SOAP 1.2 defines some fault codes specifically for encoding problems. If you use the encoding (which you probably will if you use the RPC conventions, described in the next section), you might run into the faults described in the following list. These all are subcodes to the code env:Sender, since they all relate to problems with the sender's data serialization. These faults aren't guaranteed to be sent—they're recommended, rather than mandated. Since these faults typically indicate problems with the encoding system in a SOAP toolkit, rather than with user code, you likely won't need to deal with them directly unless you're building a SOAP implementation yourself:

  • MissingID—Generated when a ref attribute in the received message doesn't correspond to any of the id attributes in the message

  • DuplicateID—Generated when more than one element in the message has the same id attribute value

  • UntypedValue—Optional; indicates that the type of node in the received message couldn't be determined by the receiver

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020