Skip to main content

If you don't have an IBM ID and password, register here.

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. This profile includes the first name, last name, and display name you identified when you registered with developerWorks. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

Tip: Better SOAP interfaces with header elements

Header elements and the AXIS toolkit

Benoit Marchal (bmarchal@pineapplesoft.com), Consultant, Pineapplesoft
Benoit Marchal is a Belgian consultant. He is the author of XML by Example, Second Edition and other XML books. Benoit is available to help you with XML projects. You can contact him at bmarchal@pineapplesoft.com or through his personal site at marchal.com.

Summary:  In this tip, Benoit Marchal discusses how to design modular, flexible, and extensible service interfaces with SOAP headers.

View more content in this series

Date:  29 Oct 2003
Level:  Intermediate

Comments:  

SOAP, the Simple Object Access Protocol, is an evolving W3C standard. Developed by IBM, Microsoft, DevelopMentor, and UserLand Software for the exchange of information over a network, SOAP stands at the point where three technologies -- Remote Procedure Call (RPC), XML, and Web applications -- are converging. The combination is new so developers are still learning how to deploy it most effectively. In most first-generation applications, SOAP is a replacement for another RPC standard such as RMI or CORBA. But as this tip illustrates, SOAP can offer more.

Intranet and Internet services

Who develops the clients and the servers is determined by whether they're being deployed on an intranet or on the Internet. On an intranet, the developers for the client and server are either on the same team or are on teams that are closely related. This translates into very strong ties between the client and server.

When it comes to the Internet, things are different. The client and server are often developed by different companies altogether. As a result, they won't have as many opportunities to synchronize their work. To make things worse, if the service is successful, multiple clients and servers will implement it.

As an example, consider the Google search engine (see Resources), a service that benefits many applications interfacing with it. For instance, I use an XML editor to write my articles. When I research a topic, I find it convenient to run searches directly from the editor. Likewise for e-mail -- it's common to search for a contact address on a corporate Web site. The search often starts with Google, so my address book also benefits from implementing the service. And what about a photo editor? It's common to search for background information on a subject or to search for new techniques, so the photo editor could interface with Google. That's three possible clients for the service already -- and Google is not the only search engine, so you could have more than one server implementation as well.

Since the client and server are developed independently, the definition of the service interface is very important. The service interface (not unlike an API) is the basis for cooperation between the two teams. It specifies the roles of the client and the server -- the methods and their parameters. The interface must be flexible, modular, and extensible.

To encourage modularity and extensibility, SOAP organizes its requests into two parts: the header and the body. The header is typically used for technical parameters of the request such as session management, authentication, and transaction, while the body contains the actual request.


Header elements in AXIS

Handlers

For simplicity, I chose to process the header in the server itself. AXIS offers a more flexible alternative through handlers. A handler processes certain header elements on behalf of the server, and the coding is very similar.

To illustrate how to implement header extensions, I'll use AXIS, the Apache SOAP toolkit. The sample service is trivial: It adds up two integers. The service interface has only one method, add(), which takes two integers as parameters.

Imagine that the server can prioritize requests: High priority requests will get a faster answer than low priority ones. How do you extend the service interface? While you could extend the add() method with a third priority parameter, it's not a good idea, primarily because doing so breaks existing clients and servers. In addition, it pollutes the interface with a technical parameter. Not every server is able to honour the priority, and not every client has a notion of priority. A better solution is to move the technical parameter to the header, where it belongs.

Listing 1 is a SOAP server that recognizes a priority header element. The service uses the MessageContext object to retrieve an instance of a Message object that represents the request. Next, it searches for a priority element in the header. The service sleeps for more or less time, depending on the priority (sleeping emulates low priority requests in this example). Note that the service accepts requests with no priority. Finally it sets the processed flag so AXIS knows the element has been dealt with (this flag is essential if the element has a mustUnderstand attribute). The server is compatible with those clients that do not implement the priority mechanism.


Listing 1. A server processes a header extension
                
import java.util.*;
import org.apache.axis.*;
import org.apache.axis.message.*;

public class HeaderService
{
   public int add(int op1, int op2)
      throws Exception
   {
      MessageContext context = MessageContext.getCurrentContext();
      Message message = context.getRequestMessage();
      SOAPEnvelope envelope = message.getSOAPEnvelope();
      SOAPHeaderElement element =
         envelope.getHeaderByName("http://psol.com/2003/tips/header",
                                  "priority");
      if(element != null)
      {
         Integer priority =
            (Integer)element.getValueAsType(Constants.XSD_INT);
         // lower priority requests are delayed to simulate priorities
         switch(priority.intValue())
         {
            case 0:
               Thread.sleep(40000);
               break;
            case 1:
               Thread.sleep(30000);
               break;
            case 2:
               Thread.sleep(20000);
               break;
            case 3:
               Thread.sleep(10000);
               break;
            case 4:
               Thread.sleep(5000);
               break;
            default:
               // top speed, no sleeping
               break;
         }
         element.setProcessed(true);
      }
      else
         // unless the service requests a priority, it runs very low
         Thread.sleep(50000);
      return op1 + op2;
   }
}

Listing 2 is the client. If a priority argument is in the command line, it creates a SOAPHeaderElement object and passes it to the Call object. Again, this client is compatible with servers that do not implement the priority mechanism.


Listing 2. Corresponding client
                
import java.net.*;
import org.apache.axis.client.*;
import org.apache.axis.message.*;
import org.apache.axis.encoding.*;
import javax.xml.rpc.ParameterMode;

public class HeaderClient
{
   public static void main(String [] args)
   {
      if(args.length < 2)
      {
         System.out.println("HeaderClient op1 op2 [-priority:0-5]");
         return;
      }
      try
      {
         Integer op1 = new Integer(args[0]),
                 op2 = new Integer(args[1]);
         URL endpoint =
            new URL("http://localhost:8080/axis/HeaderService.jws");
         Service service = new Service();
         Call call = (Call)service.createCall();
         call.setTargetEndpointAddress(endpoint);
         call.setOperationName("add");
         call.addParameter("op1",XMLType.XSD_INT,ParameterMode.IN);
         call.addParameter("op2",XMLType.XSD_INT,ParameterMode.IN);
         call.setReturnType(XMLType.XSD_INT);
         if(args.length > 2 && args[2].startsWith("-priority:"))
         {
            Integer priority = new Integer(args[2].substring(10));
            if(priority.intValue() < 0 || priority.intValue() > 5)
               priority = new Integer(3);
            SOAPHeaderElement element =
               new SOAPHeaderElement("http://psol.com/2003/tips/header",
                                     "priority");
            element.setObjectValue(priority);
            call.addHeader(element);
            System.out.println("Request priority = " + priority);
         }
         else
            System.out.println("No priority set for request");
         Integer result = (Integer)call.invoke(new Object[] { op1, op2 });
         System.out.println(op1 + " + " + op2 + " = " + result);
      }
      catch (Exception x)
      {
         System.err.println(x.toString());
      }
   }
}


Conclusion

SOAP promotes the design of modular and extensible service interfaces through the header element. While this tip demonstrates how to build premium services (faster response) on top of a regular service interface, the technique also applies to other technical parameters.


Resources

About the author

Benoit Marchal

Benoit Marchal is a Belgian consultant. He is the author of XML by Example, Second Edition and other XML books. Benoit is available to help you with XML projects. You can contact him at bmarchal@pineapplesoft.com or through his personal site at marchal.com.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in

If you don't have an IBM ID and password, register here.


Forgot your IBM ID?


Forgot your password?
Change your password


By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. This profile includes the first name, last name, and display name you identified when you registered with developerWorks. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)


By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=XML
ArticleID=12335
ArticleTitle=Tip: Better SOAP interfaces with header elements
publish-date=10292003
author1-email=bmarchal@pineapplesoft.com
author1-email-cc=dwxed@us.ibm.com

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

For articles in technology zones (such as Java technology, Linux, Open source, XML), Popular tags shows the top tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), Popular tags shows the top tags for just that product zone.

For articles in technology zones (such as Java technology, Linux, Open source, XML), My tags shows your tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), My tags shows your tags for just that product zone.

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).