Introduction to SOAP. SOAP protocol

Brett McLaughlin Translation by Ilya Chekmenev

SOAP is the Simple Object Access Protocol. If you have never heard of it before, then you must live in the middle of nowhere, far from civilization. It has become the latest fashion in web programming, and an integral part of web services, which are used with such fanaticism in web developments of the latest generation. If you've heard of Microsoft's .NET, or peer-to-peer "revolution," then you've heard of technologies that rely on SOAP (even if you don't know what it is). There is not one, but two SOAP implementations from Apache and Microsoft, which have thousands of pages dedicated to them on their MSDN support site (http://msdn.microsoft.com/).

In this article I will tell you what SOAP is and why it is such an important part in the development of the web programming paradigm. This will help you skip the fundamentals and get straight into working with the SOAP toolkit. Then I'll give a quick overview of existing SOAP projects and dive into Apache's implementation. This article is not intended to provide a complete picture of SOAP; my book, Java & XML, 2nd Edition, fills in many of the gaps. You will find answers to many of the questions that arose after reading this article in the book.

Introduction

First you need to understand what SOAP is. You can read the full (and quite lengthy) W3C opinion at http://www.w3.org/TR/SOAP. Then, having figured it out and discarded all the husk, you will understand that SOAP is just a protocol. It is a simple protocol (no need to write a new one to use it) based on the idea that at some point in a distributed architecture there is a need to exchange information. In addition, for systems in which there is a possibility of overloads and difficulties in processing processes, this protocol is very advantageous in that it is lightweight and requires a minimum amount of resources. Finally, it allows all operations to be carried out over HTTP, which makes it possible to bypass such tricky things as firewalls and protect yourself from listening using sockets on an incredible number of ports. The main thing is that you realize this, and everything else is details.

Of course, you would like to know these details, and I will not ignore them. There are three basic components to the SOAP specification: a SOAP envelope, a set of encryption rules, and a means of interaction between the request and response. Let's think of a SOAP message as a regular letter. Do you still remember those ancient things in envelopes with a postage stamp and the address written on the front? This analogy will help you understand the concept of SOAP as an "envelope" more clearly. Figure 12-1 depicts SOAP processes in the form of this analogy.

Figure 12-1. SOAP Message Process

Keep this picture in mind and let's look at the three components of the SOAP specification. I'll talk briefly about each of them, giving examples that best represent the concept. These three key components make SOAP so important and meaningful. Error handling, support for various encryptions, parameter serialization, and the fact that SOAP works over HTTP in most cases make it more attractive than other solutions for distributed protocols.

SOAP provides a high degree of interoperability with other applications, which I covered in more detail in my book. For now, I want to focus on the core elements of SOAP.

Envelope

A SOAP envelope is similar to a regular letter envelope. It contains information about the message that will be encrypted in the main SOAP section, including information about the recipient and sender, as well as information about the message itself. For example, the SOAP envelope header may indicate how the message should be processed. Before an application begins processing a message, it examines information about the message, including whether it can process the message at all. Unlike the situation with standard XML-RPC calls (remember? XML-RPC messages, encryption, etc., everything is combined into a single XML fragment), with SOAP the ongoing processing occurs in order to learn something about the message. A typical SOAP message may also include an encryption style that will assist the recipient in processing the message. Example 12-1 demonstrates a SOAP envelope that ends with an encoding specification.

Example 12-1: SOAP Envelope http://www-106.ibm.com/developerworks/library/x-soapbx1.html

Soapbox As you can see, the encryption is specified inside the envelope, which allows the application to determine (using the attribute value encodingStyle ), whether it can read the incoming message located in the element. Make sure the SOAP envelope namespace is correct, or the SOAP servers that receive your message will report a version mismatch error and you will not be able to communicate with them.

Encryption

The second important element of SOAP is the ability to encrypt custom data types. With RPC (and XML-RPC), encryption can only be performed on predefined data types that are supported in the XML-RPC toolkit you downloaded. Encrypting other types of data requires you to modify the RPC server and client yourself. With SOAP, an XML schema can be used quite easily to specify new data types (using the structure complexType, discussed in Chapter 2 of my book), and these new types can be represented in XML as part of the main section of SOAP. Thanks to XML Schema integration, you can encrypt any type of data in a SOAP message by logically describing it in an XML Schema.

Call

The best way to understand how a SOAP call works is to compare it to something you're familiar with, such as XML-RPC. If you recall, the XML-RPC call looks similar to the code snippet presented in Example 12-2.

Example 12-2. Call to XML-RPC

// Specifying the XML processor (parser) to use XmlRpc.setDriver("org.apache.xerces.parsers.SAXParser"); // Specifying the server to which the connection is made XmlRpcClient client = new XmlRpcClient("http://rpc.middleearth.com"); // Creating parameters Vector params = new Vector(); params.addElement(flightNumber); params.addElement(numSeats); params.addElement(creditCardType); params.addElement(creditCardNum); // Request Boolean boughtTickets = (Boolean)client.execute("ticketCounter.buyTickets", params); // Process the response

I created a simple program for ordering airline tickets. Now take a look at Example 12-3, which demonstrates a SOAP call.

Example 12-3. Call to SOAP

// Creating parameters Vector params = new Vector(); params.addElement(new Parameter("flightNumber", Integer.class, flightNumber, null)); params.addElement(new Parameter("numSeats", Integer.class, numSeats, null)); params.addElement(new Parameter("creditCardType", String.class, creditCardType, null)); params.addElement(new Parameter("creditCardNumber", Long.class, creditCardNum, null)); // Creating a Call object Call call = new Call(); call.setTargetObjectURI("urn:xmltoday-airline-tickets"); call.setMethodName("buyTickets"); call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC); call.setParams(params); // Call Response res = call.invoke(new URL("http://rpc.middleearth.com"), ""); // Process the response

As you can see, the actual call represented by the object Call, memory resident. It allows you to specify the call target, call method, encryption style, parameters, and many other parameters not presented in this example. This is a more flexible mechanism than the XML-RPC method, allowing you to explicitly specify a set of different parameters that are implicitly defined in XML-RPC. Later in this article, you'll learn more about the call process, including how SOAP handles invalid requests, the error hierarchy, and, of course, the call results returned.

After such a brief introduction, you already know enough to be interested in this funny thing. Now let me introduce you to the SOAP implementation I'm going to use. I will explain the reasons why I chose it and look at some code examples.

Settings

Now that you've learned the basics of the concept, it's time for the fun part: programming. To do this, you will need a convenient project or product, which is easier to find than it might seem at first glance. If you need a Java project that provides SOAP capabilities, you don't have to look long to find one. There are two groups of products: commercial and free. As in my book, I will avoid mentioning commercial products. This is not at all because they are bad (on the contrary, some of them are excellent), but because I would like any reader to be able to try any of the examples given. This is due to accessibility, which many commercial products do not have. You must pay to use them, or temporarily use them for a limited period of time after downloading.

Thus, we smoothly approached open source projects. From this area I can name only one product: Apache SOAP. It is located at http://xml.apache.org/soap and provides SOAP toolkit for Java. At the time of writing, version 2.2 was released, which you can download from the Apache website. It is this version that I will use in the examples for this article.

Other Alternatives

Before moving on to installing and configuring Apache SOAP, I will answer a few questions that might have crept into your mind. I think I have explained quite clearly the reasons why I do not use commercial products. However, you may be thinking of some other open source or related projects that you might like to use, and you're surprised I haven't commented on them.

What about IBM SOAP4J?

First on the list of alternatives is an implementation from IBM: SOAP4J. IBM's work formed the basis of the Apache SOAP project, just as IBM's XML4J grew into what is now known as the Apache Xerces XML parser project. It is assumed that the IBM implementation will be redesigned, merging with Apache SOAP. Much the same thing happened with IBM's XML4J: now it only provides packaging in Xerces. This only highlights the trends - large manufacturers often support and use OpenSource projects, in this case both projects (Apache and IBM) use the same code base .

Is Microsoft out of the game?

Of course no. Microsoft and its SOAP implementation, as well as the entire .NET movement (discussed in more detail in my book), are quite significant. I really wanted to spend most of my time looking at Microsoft's SOAP implementation in detail, but it only supports COM objects and it doesn't support Java. Due to these reasons, such a description could not be included in an article about Java and XML. However, Microsoft (despite all the complaints we, as developers, have about this company) has done important work in the field of web services, and you will make a mistake if you dismiss it without thinking, guided only by raw emotions. If you have a need to work with COM or Visual Basic components, I highly recommend that you try using the Microsoft SOAP toolkit, available at http://msdn.microsoft.com/library/default.asp?url=/nhp/Default.asp ?contentid=28000523 along with many other SOAP resources.

What is Axis?

Those of you who follow Apache activities must have heard of Apache Axis. Axis is a next-generation SOAP toolkit also developed under the Apache XML umbrella. SOAP (a specification, not a specific implementation), which has been developing rapidly and radically lately, is very difficult to follow. Trying to create a version of SOAP that fully meets current requirements as they evolve is also quite challenging. As a result, the current version of Apache SOAP offers a solution limited by its design. Having decided that it was not worth trying to completely redesign the existing tool, the Apache developers began creating a project based on the new code. Thus Axis was born. SOAP's name also changed, first from SOAP to XP and then to XMLP. Then the specification name was dropped from the name of the new SOAP and the name "Axis" was born. But now it looks like the W3C is going back to the name of the SOAP specification (version 1.2 or 2.0), so things may still change and there will be even more confusion!

Think of IBM SOAP4J as an architecture?1 of the SOAP toolkit. What about Apache SOAP (discussed in this article) as an architecture?2. And Axis represents the ?3 architecture, a new generation architecture. This project uses SAX while Apache SOAP is DOM based. In addition, Axis, unlike Apache SOAP, provides a more user-friendly approach to user interaction. After listing these advantages, you might be wondering why I didn't choose Axis as my subject of study. It would just be a little premature. Currently, only version 0.51 of Axis is being prepared for release. This is not a beta yet, or even an alpha version. I'd love to talk about Axis' new features, but you'd have no chance of convincing your management that you can use sub-alpha open source software for your critical system needs. So I decided to focus on something that you are real you can use already Today- Apache SOAP. I think that by the time the final version of Apache Axis is released, I will update this material in the next edition of my book. Until then, let's focus on the solution that is already available.

Installation

There are two possible forms of SOAP installation. The first is to start a SOAP client using the SOAP API to communicate with a server that can accept SOAP messages. The second way is to run a SOAP server that can receive messages from a SOAP client. In this section I have described both procedures.

Client

To use the SOAP client, you need to first download Apache SOAP, available at http://xml.apache.org/dist/soap. I downloaded version 2.2 in binary format (from the subdirectory version-2.2). Then you must unzip the contents of the archive into a directory on your computer. In my case it was the directory javaxml2 (c:\javaxml2 on my Windows computer /javaxml2 on my Mac OS X computer). As a result, the files were unzipped into /javaxml2/soap-2_2. You will also need to download the JavaMail package available from Sun http://java.sun.com/products/javamail/. It will be required to support the SMTP transfer protocol used by Apache SOAP. Then download the Java Beans Activation Framework (JAF), also available from Sun http://java.sun.com/products/beans/glasgow/jaf.html. Based on the assumption that you already have Xerces or another XML parser installed and ready to use.

Note: Make sure your XML parser is JAXP compliant and uses the namespace correctly. Chances are your parser meets these requirements. If you have problems, it's best to revert to using Xerces.

Note: Use the latest versions of Xerces. Version 1.4 and higher will do. There are a number of bugs with SOAP and Xerces 1.3(.1), so I advise against using this combination.

Unzip the JavaMail and JAF packages and then include their jar files in your classpath as well as the library soap.jar. Each of these jar files must be located either in the root directory of the corresponding program, or in a subdirectory /lib. When finished your variable classpath should look something like this:

$ echo $CLASSPATH /javaxml2/soap-2_2/lib/soap.jar:/javaxml2/lib/xerces.jar: /javaxml2/javamail-1.2/mail.jar:/javaxml2/jaf-1.0.1/activation.jar

For Windows it will look like this:

c:\>echo %CLASSPATH% c:\javaxml2\soap-2_2\lib\soap.jar;c:\javaxml2\lib\xerces.jar; c:\javaxml2\javamail-1.2\mail.jar;c:\javaxml2\jaf-1.0.1\activation.jar

And finally add the directory javaxml2/soap-2_2/ in your classpath to run SOAP examples. I've described the setup for several examples in this chapter.

Server

To create a SOAP-compatible set of server components, you first need a servlet engine. As in previous chapters, I used Apache Tomcat (available at http://jakarta.apache.org/) as an example for this chapter. You will need to add everything the client needs in classpath server. The easiest way to do this is to reset soap.jar, activation.jar And mail.jar, as well as your parser, into the libraries directory of your servlet engine. For Tomcat, this is the /lib directory, which contains libraries for automatic loading. If you want to provide support for scripts (which are not discussed in this chapter, but are in the Apache SOAP examples), you need to put bsf.jar(available at http://oss.software.ibm.com/developerworks/projects/bsf) and js.jar(available at http://www.mozilla.org/rhino/) to the same directory.

Note: If you're using Xerces with Tomcat, you'll need to repeat the trick I covered in Chapter 10. Rename parser.jar V z_parser.jar, A jaxp.jar V z_jaxp.jar to make sure that xerces.jar and the included version of JAXP is loaded before any other parser or JAXP implementation.

Then restart your servlet engine, after which you are ready to write SOAP server components.

Router Servlet and Admin Client

Apart from the basic operations, Apache SOAP includes a router servlet as well as an admin client. Even if you don't intend to use them, I recommend that you install them to test that SOAP is installed correctly. This process depends on which servlet engine you are using, so I will limit the installation process to Tomcat. Installation instructions for some other servlet engines can be found at http://xml.apache.org/soap/docs/index.html.

Installation under Tomcat is very simple: just take the file soap.war from directory soap-2_2/webapps and drop it into the directory $TOMCAT_HOME/webapps- and that’s it! To check the installation, enter the address in your browser http://localhost:8080/soap/servlet/rpcrouter. You should receive a response similar to that shown in Figure 12-2.

Figure 12-2. Router RPC Servlet

Although the message appears to be an error message, it indicates that everything is working correctly. You should get the same response if you point your browser to the administrator's client address: http://localhost:8080/soap/servlet/messagerouter.

To finish testing the server and client, make sure you have followed all instructions completely. Then run the following Java class as shown below to support your servlet URL for the RPC router servlet:

C:\>java org.apache.soap.server.ServiceManagerClient http://localhost:8080/soap/servlet/rpcrouter list Deployed Services:

You should get an empty list of services as shown above. If you receive any messages, please review the long list of possible errors available at http://xml.apache.org/soap/docs/trouble/index.html. This is the most comprehensive list of problems you might encounter. If you receive an empty list, this means that the setup is complete and you are ready to start looking at the examples given in this chapter.

Let's get started

There are three main stages in writing any SOAP-based systems. Having listed them, I will briefly discuss each of them:

  • Choosing between SOAP-RPC and SOAP messages;
  • Writing or gaining access to a SOAP service;
  • Writing or accessing a SOAP client.

The first step is to choose whether you will use SOAP for RPC calls (in which a remote procedure is executed on the server), or messages (in which the client simply sends pieces of information to the server). I discuss these processes in detail below. Once you have made this decision, you will need to access or create your own service. Of course, since we're all Java professionals, this chapter covers how to create your own. And finally, you need to write a client for this service, that's all!

RPC or Messaging?

Your first task has nothing to do with programming and is more of a design nature. You need to choose whether you will use the RPC or messages service. We will assume that you are familiar with RPC (for example, by reading one of the chapters of my book). The client executes a remote procedure on the server and then receives a response. In this scenario, SOAP acts as an enhanced XML-RPC system that provides better error handling and transfer of complex data types over the network. You're already familiar with this concept, and since RPC systems are easier to write in SOAP, I'll start with them. This article describes how to create an RPC service, an RPC client, and put the system into action.

Another way of working SOAP is based on message exchange. Instead of performing remote procedures, it is used only for exchanging information. As you can guess, this is a powerful tool that does not require the client to know the individual methods of any server. It also makes modeling of remote systems more isolated by allowing data packets (packets in the figurative sense, not in the network sense) to be sent to other systems. At the same time, other systems do not need to know about the operations that were performed with this data. This style is more complex than RPC programming, so I will not describe it here. You will find it in my book, along with other details of business-to-business interaction. First, get acquainted with SOAP-RPC programming.

Like most design problems, making this decision is up to you. Analyze your application and try to determine why you need to use SOAP. If you have a server and a set of clients that perform specific business functions on demand, then RPC is more suitable for you. In complex systems in which data exchange is more than just performing specific business functions on demand, the use of SOAP messages is much preferable.

RPC service

Now that the formalities are over, it is time to act. As you know, in RPC you will need classes whose methods will be executed remotely.

Code snippets

I'll start by looking at some code snippets for the server. These fragments are classes with methods that are executed for RPC clients. I used code from my book as examples. Instead of using simple classes, I chose a more complex example to demonstrate the capabilities of SOAP as clearly as possible. So, I used the CD class as an example. First we define the element map for each non-standard parameter type. For attribute As you can see, the encryption is specified inside the envelope, which allows the application to determine (using the attribute value, at least in Apache SOAP 2.2. you must specify the value http://schemas.xmlsoap.org/soap/encoding/ . This is currently the only supported encoding. You need to specify the namespace for the user-defined type and then the class name prefixed with the namespace for that type. In our case, for these purposes I used a fictitious namespace and a simple prefix " x". Then using the attribute javaType, set the real name of the Java class (for this case - javaxml2.CD). And finally, kuralesil with attributes java2XMLClassName And xml2JavaClassName. With their help, a class is specified that is converted from Java to XML and vice versa. I used the amazingly handy BeanSerializer class, also included with Apache SOAP. If your custom parameter is in JavaBean format, this serializer and deserializer will save you from having to write your own. You need a class with a default constructor (remember, for the CD class I defined a simple, parameterless constructor), and publish all the data of this class using methods setXXX And getXXX. Because class CD perfectly satisfies all these requirements, BeanSerializer works perfect.

Note: What class CD meets requirements BeanSerializer. doesn't matter much. Most classes are easily converted to this format. Therefore, I advise avoiding writing your own serializers and deserializers. This is an extra headache (nothing complicated, but too painstaking) and I recommend that you save your energy and use bean conversion in your custom parameters. In many cases, bean conversions only require a default constructor (no parameters) in your class.

Now let's recreate jar file and reinstall our service:

(gandalf)/javaxml2/Ch12$ java org.apache.soap.server.ServiceManagerClient http://localhost:8080/soap/servlet/rpcrouter xml/CDCatalogDD.xml

Attention: If you leave your servlet engine running and rehost a service at the same time, you will need to restart the servlet engine to enable the new classes for the SOAP service and rehost the service.

Now all that remains is to modify the client to use new classes and methods. Example 12-10 contains a modified version of the client class CDAdder. Changes made to the previous version are highlighted.

Example 12-10: Updated CDAdder class

package javaxml2; import java.net.URL; import java.util.Vector; import org.apache.soap.Constants; import org.apache.soap.Fault; import org.apache.soap.SOAPException; import org.apache.soap.encoding.SOAPMappingRegistry; import org.apache.soap.encoding.soapenc.BeanSerializer; import org.apache.soap.rpc.Call; import org.apache.soap.rpc.Parameter; import org.apache.soap.rpc.Response; import org.apache.soap.util.xml.QName; public class CDAdder( public void add(URL url, String title, String artist, String label) throws SOAPException ( System.out.println("Adding a CD with the title "" + title + "" artist "" + artist + "" studio " + label); CD cd = new CD(title, artist, label); // Create a call object Call Call call = new Call(); call.setSOAPMappingRegistry(registry); call.setTargetObjectURI("urn:cd-catalog"); call.setMethodName("addCD"); call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);// Setting parameters Vector params = new Vector(); params.addElement(new Parameter("cd", CD.class, cd, null)); call.setParams(params); // Processing the Invoke call Response response; response = call.invoke(url, ""); if (!response.generatedFault()) ( System.out.println("Add CD completed successfully."); ) else ( Fault fault = response.getFault(); System.out.println(Error: " + fault.getFaultString ()); public static void main(String args) ( if (args.length != 4) ( System.out.println("Template: java javaxml2.CDAdder " + "\"[CD Title]\" \"[Artist Name]\ " \"[Studio CD]\""); return; try ( // URL of the SOAP server to which the connection is made URL url = new URL(args);

// Get values ​​for new CD String title = args; CD:

String artist = args;

String label = args; BeanSerializer// Add the CD CDAdder adder = new CDAdder(); CD adder.add(url, title, artist, label); ) catch (Exception e) ( e.printStackTrace(); ) ) ) The only really interesting change is in class mapping // Map this type so it can be used with SOAP SOAPMappingRegistry registry = new SOAPMappingRegistry(); BeanSerializer serializer = new BeanSerializer(); registry.mapTypes(Constants.NS_URI_SOAP_ENC, new QName("urn:cd-catalog-demo", "cd"), CD.class, serializer, serializer); This is how a user parameter can be encoded and transmitted over the network. I have already told you how the class can be used to process parameters in JavaBean format, such as class. I used a placement descriptor to indicate these to the server, although now I need to tell the client to use this serializer and deserializer. This function is performed by the class SOAPMappingRegistry) and finally an instance of the class for serialization and deserialization. For this example, both cases will involve an instance BeanSerializer. Once all these settings have been entered into the registry, notify the object Call using the method setSOAPMapping-Registry().

You can run this class as shown earlier, adding a CD, and everything should work as expected:

C:\javaxml2\build>java javaxml2.CDAdder http://localhost:8080/soap/servlet/rpcrouter "Tony Rice" "Manzanita" "Sugar Hill" Adding a CD titled "Tony Rice" by Sugar Hill's "Manzanita" Successfully adding a CD.

I left the class modification CDLister for you. Everything is produced according to the same template. To test yourself, you can refer to the example files for my book, which already contain these updated classes.

Note: You can decide that because the class CDLister does not directly interact with the object CD(returned by method list() the type matters Hashtable), then you don't need to make any changes. However, the returned class Hashtable contains object instances CD. If SOAP doesn't know how to deserialize them, the client will throw an error. In this case, to solve the problem you must specify in the object Call copy ) catch (Exception e) ( e.printStackTrace(); ) ) ).

Efficient error handling

Now that you've seen custom objects and made RPC calls and such, let me talk about a less exciting topic: error handling. With any network transaction, many failures can occur. The service does not start, there is an error in the server, the object cannot be found, classes are missing and many other problems. So far I have simply used the method fault.getString() to generate error messages. But this method may not always be useful. To see it in action, uncomment the constructor CDCatalog:

public CDCatalog() ( //catalog = new Hashtable(); // Create a directory addCD(new CD("Nickel Creek", "Nickel Creek", "Sugar Hill"));

addCD(new CD("Let it Fall", "Sean Watkins", "Sugar Hill")); addCD(new CD("Aerial Boundaries", "Michael Hedges", "Windham Hill")); addCD(new CD("Taproot", "Michael Hedges", "Windham Hill")); Hashtable)

(gandalf)/javaxml2/build$ java javaxml2.CDLister http://localhost:8080/soap/servlet/rpcrouter View the current CD directory. Error: Unable to resolve target object: null

This is not at all the information that can help in identifying and correcting an error. Nevertheless, the framework copes well with error handling. Do you remember DOMFaultListener, which you specified as the value of the element faultListener? The time has come for him to enter the game. Object returned in case of error Fault contains the DOM (Document Object Model) org.w3c.dom.Element with detailed information about the error. First add an import expression to your source code java.util.Iterator:

import java.net.URL; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.Vector; import org.apache.soap.Constants; import org.apache.soap.Fault; import org.apache.soap.SOAPException; import org.apache.soap.encoding.SOAPMappingRegistry; import org.apache.soap.encoding.soapenc.BeanSerializer; import org.apache.soap.rpc.Call; import org.apache.soap.rpc.Parameter; import org.apache.soap.rpc.Response; import org.apache.soap.util.xml.QName;

Now let's make changes to handle errors in the list() method:

if (!response.generatedFault()) ( Parameter returnValue = response.getReturnValue(); Hashtable catalog = (Hashtable)returnValue.getValue(); Enumeration e = catalog.keys(); while (e.hasMoreElements()) ( String title = (String)e.nextElement(); CD cd = (CD)catalog.get(title); System.out.println(" "" + cd.getTitle() + "" artist " + cd.getArtist() + " studios " + cd.getLabel()); ) else ( Fault fault = response.getFault(); System.out.println("Error: " + fault.getFaultString()); Vector entries = fault.getDetailEntries();

for (Iterator i = entries.iterator(); i.hasNext();) ( org.w3c.dom.Element entry = (org.w3c.dom.Element)i.next(); System.out.println(entry .getFirstChild().getNodeValue()); Using method getDetailEntries() you get access to the SOAP service and the raw data server supporting the problem. The code re-processes them (usually there is only one element, but it requires close attention) and intercepts the DOM Element

, contained in each entry. Essentially, here's the XML you're working with: SOAP-ENV:Server.BadTargetObjectURI Cannot resolve target: null

In other words, the Fault object gives you access to the part of the SOAP envelope that contains errors. In addition, Apache SOAP provides a Java stack trace when errors occur, providing the detailed information needed to correct them. Intercepting an element stackTrace and printing out the node value Text from this element your client can print the server stack trace. By compiling these changes and restarting the client you will get the following result:

C:\javaxml2\build>java javaxml2.CDLister http://localhost:8080/soap/servlet/rpcr outer View the current CD directory. Error: Cannot resolve target: null java.lang.NullPointerException in javaxml2.CDCatalog.addCD(CDCatalog.java:24) in javaxml2.CDCatalog. (CDCatalog.java:14) in java.lang.Class.newInstance0(Native Method) in java.lang.Class.newInstance(Class.java:237)

It's not much better, but at least you can see some tidbits of information that an exception occurred addCD(new CD("Aerial Boundaries", "Michael Hedges", "Windham Hill")); and even find out the line numbers in the server classes in which this problem occurred. The result of these latest changes has given you a clear picture of the error handling problem. Now you should check your server classes for errors. Yes, I almost forgot, before that don’t forget to change your class back CDCatalog to get rid of the errors we intentionally introduced for clarity!

  1. There is a lot of talk about running SOAP over other protocols such as SMTP (or even Jabber). The SOAP standard does not yet provide for this, but similar capabilities may be added in the future. Therefore, do not be surprised if you encounter active discussions on this topic.

Lyrical part.

Imagine that you have implemented or are implementing a certain system that should be accessible from the outside. Those. there is a certain server with which you need to communicate. For example a web server.

This server can perform many actions, work with the database, perform some third-party requests to other servers, do some calculations, etc. live and possibly develop according to the scenario known to him (i.e. according to the developers’ scenario). It is not interesting for a person to communicate with such a server, because he may not be able/want to provide beautiful pages with pictures and other user-friendly content. It is written and works to work and provide data when asked to it, without worrying that it is human readable, the client will deal with it himself.

Other systems, accessing this server, can already dispose of the data received from this server at their own discretion - process, accumulate, issue to their clients, etc.

Well, one of the options for communicating with such servers is SOAP. SOAP xml message exchange protocol.

Practical part.

A web service (this is the name of what the server provides and what clients use) makes it possible to communicate with the server with clearly structured messages. The fact is that the web service does not accept any data. The web service will respond with an error to any message that does not comply with the rules. The error, by the way, will also be in xml form with a clear structure (which is not true about the text of the message).

WSDL (Web Services Description Language). The rules by which messages are composed for the web service are also described using xml and also have a clear structure. Those. If a web service provides the ability to call a method, it must allow clients to know what parameters are used for this method. If the web service expects a string for Method1 as a parameter and the string should be named Param1, then these rules will be specified in the web service description.

Not only simple types, but also objects and collections of objects can be passed as parameters. The description of an object comes down to a description of each component of the object. If an object consists of several fields, then each field is described, its type, name (what are the possible values). Fields can also be of a complex type, and so on until the description of the types ends with simple ones - string, boolean, number, date... However, some specific types may turn out to be simple, it is important that clients can understand what values ​​they may contain.

For clients, it is enough to know the url of the web service; the wsdl will always be nearby, from which you can get an idea of ​​the methods and their parameters that this web service provides.

What are the advantages of all these bells and whistles:

  • In most systems, the description of methods and types occurs automatically. Those. the programmer on the server just needs to say that this method can be called through a web service, and the wsdl description will be generated automatically.
  • The description, which has a clear structure, is readable by any soap client. Those. whatever the web service, the client will understand what data the web service receives. Using this description, the client can build its own internal structure of object classes, the so-called. binding" and. As a result, the programmer using the web service has to write something like (pseudocode):

    NewUser:=TSoapUser.Create("Vasya","Pupkin","admin"); soap.AddUser(NewUser);

  • Automatic validation.

    • xml validation. xml must be well-formed. Invalid xml - immediately an error to the client, let him sort it out.
    • schema-validation. xml must have a certain structure. xml does not match the schema - immediately an error to the client, let him sort it out.
    • Data verification is carried out by the soap server so that data types and restrictions match the description.
  • Authorization and authentication can be implemented using a separate method. natively. or using http authorization.
  • Web services can work both via the soap protocol and via http, that is, through get requests. That is, if the parameters are simple data (without structure), then you can simply call the usual get www.site.com/users.asmx/GetUser?Name=Vasia or post. However, this is not everywhere and not always.
  • ... see on Wikipedia

There are also a lot of disadvantages:

  • Unreasonably large message size. Well, here the very nature of xml is such that the format is redundant, the more tags, the more useless information. Plus soap adds its redundancy. For intranet systems, the issue of traffic is less acute than for the internet, so soap for local networks is more in demand, in particular Sharepoint has a soap web service with which you can communicate with success (and some limitations).
  • Automatically changing the description of a web service can break all clients. Well, it’s like this for any system, if backward compatibility with old methods is not supported, everything will fall off...
  • Not a minus, but a drawback. All method calls must be atomic. For example, when working with a database, we can start a transaction, execute several queries, then rollback or commit. There are no transactions in soap. One request, one answer, the conversation is over.
  • Dealing with the description of what is on the server side (is everything described correctly?) and what is on the client (what was described to me here?) can be quite difficult. There were several times when I had to deal with the client side and convince the server programmer that his data was described incorrectly, but he couldn’t understand anything about it at all, because automatic generation and he shouldn’t, it’s a matter of software. And the error, naturally, was in the method code; the programmer simply did not see it.
  • Practice shows that web service developers are terribly far from the people who use these web services. In response to any request (valid from the outside), an incomprehensible error “Error 5. Everything is bad” may come. It all depends on the conscience of the developers :)
  • I'm sure I still don't remember something...

As an example, there is an open web service belavia:

  • http://86.57.245.235/TimeTable/Service.asmx - entry point, there is also a text description of methods for third-party developers.
  • http://86.57.245.235/TimeTable/Service.asmx?WSDL - wsdl description of methods and types of received and returned data.
  • http://86.57.245.235/TimeTable/Service.asmx?op=GetAirportsList - description of a specific method with an example of the type of xml request and xml response.

You can manually create and send a request like:

POST /TimeTable/Service.asmx HTTP/1.1 Host: 86.57.245.235 Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: "http://webservices.belavia.by/GetAirportsList" ru

the answer will come:

HTTP/1.1 200 OK Date: Mon, 30 Sep 2013 00:06:44 GMT Server: Microsoft-IIS/6.0 X-Powered-By: ASP.NET X-AspNet-Version: 4.0.30319 Cache-Control: private, max -age=0 Content-Type: text/xml; charset=utf-8 Content-Length: 2940

PS Previously, the Aeroflot web service was opened, but after 1C added soap support to 8ku, a bunch of 1C beta testers successfully installed it. Now something has changed there (I don’t know the address, you can look it up if you’re interested).
ZZY Disclaimer. He spoke at the everyday level. You can kick.

History of creation

With the advent of personal computers, the need to combine them arose. At first there were simple cable connections, then network protocols appeared that united computers running on the same OS; with the development of technology, the need to have one OS on all computers disappeared and it became possible to combine computers running different OSes. The Internet has changed the speed of movement along the path of unification.

But even today, not all integration problems have been solved; unfortunately, there was no single protocol for communication between Internet applications and services. To solve this problem, companies such as Microsoft, DevelopMentor, UserLand Software, IBM and Lotus Development teamed up and as a result of their joint activities, the Simple Object Access Protocol was created. A simple object access protocol describes a standard for remote procedure calls based on XML (Extensible Markup Language). - extensible markup language). SOAP is designed to greatly simplify the development of cross-language applications and business integration tools. The beginning was made with SOAP 1.0, which required the HTTP protocol to operate.

After the appearance of the initial version of SOAP, created, as already noted, by the joint efforts of Microsoft, DevelopMentor and UserLand, IBM and Lotus joined in the development of the product. As a result, the specification has undergone a significant overhaul to better suit the integration of heterogeneous environments. The main difference between the next version of SOAP 1.1 and the initial version was the transition from Microsoft's XML-Data to XML Schema. In addition, in the new version the specification no longer depends on transport protocols. SOAP 1.0 required the HTTP protocol, while for SOAP 1.1 the type of transport does not matter: you can use email or massage queving links to forward messages. Companies that had already adopted SOAP 1.0 found themselves tied to Microsoft's non-standard technology. However, a number of promising products from this corporation, including BizTalk Server and SQL Server 7.0, also rely on XML-Data. With the advent of version 1.1, the circle of supporters of the SOAP protocol is expanding

The original version of SOAP 1.1 submitted to the IETF Internet Technical Task Force was based on the XML-Data technology proposed by Microsoft in January 1998. However, during the W3C standards review process, the underlying structure was replaced by XML Schema. The World Wide Web Consortium was asked to consider SOAP 1.1 as a potential standard.

The latest version of the Simple Object Access Protocol (SOAP) specification is available on the web server serving MSDN™ Developer Program members (http://msdn.microsoft.com/). SOAP is an open, standards-based protocol that defines, based on XML (Extensible Markup Language), a common format for communication between any Internet applications and services. This version extends SOAP's capabilities for asynchronous communications to include support not only for HTTP, but also for Internet protocols such as SMTP, FTP, and TCP/IP. The latest version of the SOAP specification has received widespread support from companies such as ActiveState Tool Corp., Ariba Inc., BORN Information Services Inc., Commerce One Inc., Compaq Computer Corp., DevelopMentor Inc., Extensibility Inc., IBM, IONA Technologies PLC, Intel Corp., Lotus Development Corp., ObjectSpace Inc., Rogue Wave Software Inc., Scriptics Corp., Secret Labs AB, UserLand Software and Zveno Pty. Ltd. The SOAP specification provides a common mechanism for integrating services across the Internet and/or intranets, regardless of the operating system, object model, or programming language used. Based on the Internet standards XML and HTTP, SOAP allows any new or existing applications to communicate with each other. Web sites that support SOAP can become Web services that are accessible purely programmatically and do not require human intervention. A single infrastructure that enables direct interaction between Internet-facing applications opens up new opportunities for integrating services and devices—no matter where they are on the Internet.

Web Services and SOAP

Web services and SOAP are designed to solve the problems of cross-platform application communication. This article will help you gain insight into these new promising technologies.

What is SOAP

Currently used technologies for remote method calling (DCOM, CORBA/IIOP and RMI) are quite difficult to configure and organize interaction. This entails problems in the operation and functioning of distributed systems (security problems, transport through firewalls, etc.). The existing problems were successfully solved by the creation of SOAP (Simple Object Access Protocol), a simple XML-based protocol for exchanging messages in distributed environments (WWW). It is designed for creating web services and calling methods remotely. SOAP can be used with different transport protocols, including HTTP, SMTP, etc.

What are web services

Web services are functionality and data exposed for use by external applications that interact with the services through standard protocols and data formats. Web services are completely independent of the implementation language and platform. Web services technology is the cornerstone of Microsoft's .NET programming model. To demonstrate the capabilities of SOAP, I used the recently released implementation of SOAP Toolkit version 2.0 from Microsoft. It should be noted that the current version of Toolkit is noticeably different from the previous one (Microsoft SOAP Toolkit for Visual Studio 6.0) and from the beta version of SOAP Toolkit 2.0.

Mechanism of interaction between client and server

  1. The client application instantiates the SOAPClient object
  2. SOAPClient reads web service method description files (WSDL and Web Services Meta Language - WSML). These files can also be stored on the client.
  3. The client application, using the late binding capabilities of the SOAPClient object, calls a service method. SOAPClient generates a request packet (SOAP Envelope) and sends it to the server. Any transport protocol can be used, but HTTP is typically used.
  4. The packet takes a Listener server application (can be an ISAPI application or an ASP page), creates a SOAPServer object and passes the request packet to it
  5. SOAPServer reads the web service description, loads the description and request packet into XML DOM trees
  6. SOAPServer calls a method of the object/application implementing the service
  7. The results of method execution or error description are converted by the SOAPServer object into a response packet and sent to the client
  8. The SOAPClient object parses the received packet and returns to the client application the results of the service or a description of the error that occurred.

A WSDL file is an XML document that describes the methods provided by a web service. Also parameters of methods, their types, names and location of the service Listener. The SOAP Toolkit wizard automatically generates this document.

SOAP Envelope (Package) - an XML document that contains a request/response for executing a method. It is most convenient to consider it as a postal envelope in which information is enclosed. The Envelope tag must be the root element of the package. The Header element is optional, but the Body element must be present and be a direct child of the Envelope element. If a method execution error occurs, the server generates a packet containing a Fault element in the Body tag, which contains a detailed description of the error. If you use the high-level interfaces SOAPClient and SOAPServer, then you do not have to go into the intricacies of the package format, but, if you wish, you can use low-level interfaces or even create a package by hand.

The SOAP Toolkit object model makes it possible to work with low-level API objects:

  • SoapConnector - Provides work with the transport protocol for exchanging SOAP packets
  • SoapConnectorFactory - Provides a method for creating a connector for the transport protocol specified in the WSDL file (tag)
  • SoapReader - Reads SOAP messages and builds XML DOM trees
  • SoapSerializer - Contains methods for creating a SOAP message
  • IsoapTypeMapper, SoapTypeMapperFactory - Interfaces that allow you to work with complex data types

Using high-level API objects, you can only transfer data of simple types (int, srting, float ...), but the SOAP 1.1 specification allows you to work with more complex data types, such as arrays, structures, lists, and combinations thereof. To work with such types, you have to use the IsoapTypeMapper and SoapTypeMapperFactory interfaces.

In general, today there are standard XML data exchange protocols:

  • XML-RPC– you pass the package and indicate which method on the server you want to call.
  • REST- there are some objects on the server. Each object is characterized by some kind of identifier. Each element has its own url. You can do the following with any element: insert, delete, update, select. You simply send the desired request to the server (for example, insert such and such an element). Client-server exchange is based on either JSON or XML.

SOAP (service oriented architecture, a set of loosely coupled services interacting with each other) is based on RPC. The main advantage of RPC is the small number of network resources (entry points) and the many methods involved. Despite this advantage, RPC is an outdated protocol that has a number of disadvantages:

  • The validity of the XML-RPC message cannot be verified. The old protocol was created before schemas (methods of validating data) were standardized in XML. Those. The server accepts requests, it must ensure that the requests are for it and that the data is consistent. In XML-RPC, data types are declared for this, but this is a data type check, and data consistency is not checked (that you received a structure with all the necessary parameters).
  • You cannot create combined messages.
  • You cannot use space and time (appeared after the creation of RPC).
  • You cannot expand the message, i.e. add additional information.

All these shortcomings were solved in XML Schema. This is the industry standard for describing XML documents. Those. it is a way to model arbitrary data. An XML schema can describe a model (relationships between elements and attributes, and their structure), data types (characterizes data types) and a dictionary (names of elements and attributes).

Based on all the shortcomings of XML-RPC, the SOAP protocol was created.

SOAP(Simle Object Access Protocol) - access protocol to an object (to the entry point). Today it is the main industry standard for building distributed applications.

It represents extensions to the XML-RPC language. Those. it is built on the principle: 1 entry point and any methods. The protocol itself in terms of transport (how to transfer data) gives a wide choice: SMTP, FTP, HTTP, MSMQ.

SOAP underlies the implementation of XML web services (XML web services). The disadvantage of SOAP is that it is difficult to learn.

SOAP is based on the exchange of messages between a client and a server (synchronously and asynchronously). Each message carries information about the data (what data is transmitted and received). SOAP describes in advance the entire structure of a message using XML schemas: what should be in the message, how it will be transmitted. This makes it possible, without knowing the server, to understand what is happening there, and allows the server to check whether this message is for it.

XML schema

The purpose of a schema is to describe the structure of the data, i.e. what we have. All data is divided into simple and complex types (scalars and structures). A simple type (string, number, boolean, date) will never contain anything inside. And a structure (object) can contain properties.

Basic SOAP Operations

  • Not just simple client-server information exchange. But also automatic server recognition and search for this server, i.e. the client may not even know anything about the server. Those. the client first searches for the server, finds suitable services, understands what methods are there, what the server has, and calls it.
  • The server publishes its information (location, what methods it supports) so that the client finds this server. Publishing occurs in the UDDI directory.

Structure of SOAP messages:

  • SOAP Envelope - this includes the entire message. Consists of a header and a body.
  • SOAP Header (header) - additional information (authorization, for example).
  • SOAP Body (body) - the message itself.
  • SOAP Fault (error) is a method of transmitting an error from the server to the client.

WSDL

WSDL(Web Services Description Language) - language for describing web services. Used in SOAP. This is a kind of document that describes everything: what namespaces were used, what data schemes were used, what types of messages the server expects from the client, what envelopes belong to which method, what methods exist, what address to send to, etc. Actually, WSDL is a web service. It is enough for the client to study the contents of this document; he already knows everything about the server.

Any server must publish WSDL.

WSDL consists of blocks:

  • Definition of the service itself, i.e. entry point, port is indicated.
  • Methods format. The entry point is linked to operations, i.e. what methods does it support? The type of call and transmission method are indicated. Inside each method there is an explanation of the form in which the data is transmitted - in the form of SOAP.
  • Binding methods to a message.
  • Description of the messages themselves.

As discussed in the previous chapter, Web services communicate with clients and each other by sending messages in XML. The tags of this XML implementation, the rules for formatting the XML document, and the order in which documents are exchanged are defined by the SOAP protocol. The SOAP protocol was created in 1998 by a team of developers led by Dave Winer, who worked at Microsoft Corporation and Userland. The name of the protocol - "Simple Object Access Protocol" - reflects its original purpose - to access the methods of remote objects. The purpose of the protocol has changed; it is now a protocol for any interaction between Web services and components of loosely coupled distributed applications. It is no longer quite simple, and it doesn’t say anything about objects. Many developers suggest calling it "Service Oriented Architecture Protocol", leaving the previous abbreviation. To stop these attempts, the SOAP 1.2 specification states that the word "SOAP" will no longer be spelled out in any way.

At the end of 1999, the development of the protocol was transferred to the W3C consortium (http:// www.w3.org/).

In May 2000, the consortium released its version of SOAP 1.1. A message written using the SOAP protocol is formatted as an XML document that actively uses namespaces. SOAP 1.1 XML element names refer to the namespace identifier http://schemas.xmlsoap.org/soap/envelope/.

The second draft of SOAP 1.2 was released in 2001, its namespace at that time was called http://www.w3.org/2001/06/soap-envelope.

Note that it is the namespace identifier, not the 1.1 or 1.2 number, that determines the SOAP version. The server will not consider the SOAP message and will return an error message if it notices

namespace mismatch.

As I write this, SOAP 1.1 remains working. Version 1.2 cannot leave the preparatory stage, but is already used, for example, in SOAP::Lite, Apache SOAP 2.3, Apache Axis. Therefore, in this chapter I will outline version 1.2, noting its differences from version 1.1.

The working SOAP specification is always stored at http://www.w3.org/TR/SOAP/. Documents located at this address are replaced with new ones when the working version is replaced.

The SOAP draft is continually updated and the namespace identifier changes. The newest draft version at the time of writing was located at http://www.w3.org/TR/soapl2-partl/, and the namespace it used was http://www.w3.org/2002/06/soap- envelope. Note that the SOAP 12 specification consists of two parts: part 1 and part2. The second part of the specification - the application - contains rules for recording complex data types. The specification has another part of partO - examples of messages compiled according to the rules of SOAP 1.2.

SOAP message structure

The specification defines a SOAP message as an XML document that does not contain a document type declaration or processing instructions. The root element of this XML document is called . An element can have attributes that define namespaces,

and other attributes provided with prefixes. The root element contains one optional element containing the message header, and one required element , in which the contents of the message are recorded. Version 1.1 allowed after the body to write down arbitrary elements, their names had to be prefixed. Version 1.2 prohibits writing anything after the element . In short, the general structure of a SOAP message is:

xmlns:env="http://www.w3.org/2002/06/soap-envelope">

< ! - Блоки заголовка ->

Element

, if it is in the message, is written first in the body of the element . In addition to the xmlns attributes, it may contain an actor attribute, which indicates the URI address of the specific SOAP server to which the message is intended.

The fact is that a SOAP message can pass through several SOAP servers or through several applications on the same server. These applications pre-process the message header blocks and transmit it to each other. All of these servers and/or applications are called SOAP nodes. The SOAP specification does not define rules for passing a message through a chain of servers. For this purpose, other protocols are being developed, for example, Microsoft WS-Routing.

The actor attribute specifies the target SOAP node - the one that is located at the end of the chain and will process the entire header. Meaning

The actor attribute indicates that the header will be processed by the first server that receives it. The actor attribute can appear in separate header blocks, indicating the node that handles this block. After processing, the block is removed from the SOAP message.

In version 1.2, the actor attribute is replaced by the role attribute because in this version of SOAP, each node plays one or more roles. The specification currently defines three SOAP node roles.

The role of http://^^.w3.org/2002/06/soap-envelope/role/ultimateReceiver is played by the final, target node that will process the header.

The role http://www.w3.org/2002/06/soap-envelope/role/next is played by the intermediate or target node. Such a node can play other, additional roles.

The role http://www.w3.org/2002/06/soap-envelope/role/none should not be played by any SOAP node.

Distributed applications, based on their needs, can add other roles to these roles, for example, introduce an intermediate server that verifies the digital signature and define this role for it with some URI string.

The value of the role attribute can be any URI string indicating the role of the node to which this header block is intended. The default value for this attribute is the empty value, that is, just a pair of quotes, or the URI string http://\vw\v.w3.org/2002/06/soap-envelope/rale/ultimateReceiver.

The value of the role attribute indicates that the block should be processed by a node playing the role specified by the same string.

Another element attribute

, called urnstUnderstand, takes the values ​​o or 1. Its default value is o. If the mustunderstand attribute is equal to 1, then the SOAP node, when processing the element, must take into account its syntax defined in the document schema, or not process the message at all. This increases the accuracy of message processing.

In SOAP version 1.2, instead of the number o, you need to write the word false, and instead of the number 1, write the word true.

In the header body

You can nest arbitrary elements, previously called header entries. In version 1.2 these are called header blocks. Their names are necessarily marked with prefixes. Header blocks may contain role or actor and mustunderstand attributes. Their action will only apply to this block. This allows individual header blocks to be processed by intermediate SOAP nodes, those whose role matches the role specified by the role attribute. Listing 3.1 shows an example of such a block.

Listing 3.1. Header with one block

xmlns:t="http://some.com/transaction" env:role=

"http://www.w3.org/2002/06/soap-envelope/role/ultimateReceiver" env:mustUnderstand="1">

Elements nested within header blocks are no longer called blocks. They cannot contain the role, actor, and mustunderstand attributes.

Element must be written immediately after the element

, if it is in the message, or first in the SOAP message if the header is missing. To element You can nest arbitrary elements; the specification does not define their structure in any way. However, one element is defined containing an error message.

Error message

If a SOAP server, while processing a SOAP message received by it, notices an error, it will stop processing and send a SOAP message to the client, in the body of which it will write one element with an error message.

In the message written in the body of the SOAP 1.1 element, the following is highlighted:

There are four parts described by the following subelements.

Error code - a message indicating the type of error. It is intended for a program that handles errors.

Description of the error - a verbal description of the type of error intended for a person.

Location of the error - the URI of the server that noticed the error. Useful when a message goes through a chain of SOAP nodes to clarify the nature of the error. Intermediate SOAP nodes are required to record this element; the target SOAP server is not required to do so.

Error details - describe errors encountered in the body message, but not in its title. If no errors are found during processing of the body, then this element is missing.

For example:

xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">

env:MustUnderstand SOAP Must Understand Error

SOAP version 1.2 changed the content of the element As described in

namespace http://www.w3.org/2002/06/soap-envelope, it includes two required elements and three optional elements.

Required elements.

Error code . It contains a required sub-element<:value>with an error code and an optional sub-element , containing, again, the element with a clarifying error code and element , and then everything is repeated recursively.

Reason for error . Contains an optional xml attribute: lang, indicating the message language (see Chapter D), and an arbitrary number of nested elements describing the error.

Optional elements.

? - the URI of the intermediate SOAP node that noticed the error.

? - the role of the SOAP node that noticed the error.

? - description of the error noticed while processing the body message, but not the title.

Listing 3.2 shows an error message that occurred when attempting to execute a procedure. The error is that the names of the procedure's arguments are written incorrectly in the SOAP message and the procedure cannot understand them.

Listing 3.2. Error message

xmlns:env="http://www.w3.org/2002/06/soap-envelope" xmlns:rpc=’http://www.w3.org/2002/06/soap-rpc’>

env:Sender

rpc:BadArgumentsc/env:Value>

Ptocessing ETror

xmlns:e="http://www.example.org/faults"> №me does not match 999

Types of errors

The list of error codes is constantly changing and expanding. Version 1.1 defines four types of errors.

VersionMismatch - namespace is unrecognized. It may be out of date or its name may be misspelled.

MustUnderstand - A header block marked with a mustUnderstand attribute with a value of 1 does not conform to its syntax as defined in the document schema.

Client - the XML document containing the message is malformed and for this reason the server cannot process it. The client should change the message.

Server - the server cannot process the correctly recorded message due to its internal reasons.

Version 1.2 defines five types of errors.

VersionMismatch - namespace is unrecognized. It may be out of date, or its name may be misspelled, or there may be an XML element name in the message that is not defined in that namespace. The server writes the element to the response header , enumerating nested elements correct namespace names understood by the server. The server response is shown in Listing 3.3.

MustUnderstand - A header block marked with the mustunderstand attribute set to true does not conform to its syntax as defined in the document schema. The server writes the following elements to the response header: , whose qname attribute contains the name of the incorrect block. Listing 3.4 contains an example of the response that the server would make if the header in Listing 3.1 was misspelled.

DataEncodingUnknown - the message contained incomprehensible data, perhaps it was written in an unknown encoding.

Sender - the XML document containing the message is malformed and for this reason the server cannot process it. The client should change the message.

Receiver - the server cannot process the correctly recorded message for its own internal reasons, for example, the required XML parser is missing.

The server can add some of its own types to these error types. Usually

they detail standard types and messages about them appear in elements , as shown above in Listing 3.2.

? Listing 3.3. Server response with an error message like VersionMismatch

xmlns:env="http://www.w3.org/2002/06/soap-envelope">

xmlns:upg="http://www.w3.org/2002/06/soap-upgrade">

xmlns:nsl="http://www.w3.org/2002/06/soap-envelope"/>

xmlns:ns2="http://schemas.xmlsoap.org/soap/envelope/"/>

env:VersionMismatch

Version Mismatch

ListongZ.4. Server response with an error message like MustUnderstand

xmlns:t=’http://some.com/transaction’ />

env:MustUnderstand

One or more mandatory headers not understood

Literature:

Khabibullin I. Sh. Development of Web services using Java. - St. Petersburg: BHV-Petersburg, 2003. - 400 p.: ill.