Writing Web Service Clients Using Axis2's Primary APIs

This section presents complex yet powerful XML based client API which is intended for advanced users. However, if you are a new user we recommend using code generation given in the Advance User's Guide.

Web services can be used to provide a wide-range of functionality to the user from simple, less time consuming operations such as "getStockQuote" to time consuming business services. When we utilize (invoke using client applications) these Web services we cannot use simple generic invocation paradigms that suite all the timing complexities involved in the service operations. For example, if we use a single transport channel (such as HTTP) to invoke a Web service with an IN-OUT operation that takes a long time to complete, then most often we may end up with "connection time outs". On the other hand, if there are simultaneous service invocations that we need to perform from a single client application, then the use of a "blocking" client API will degrade the performance of the client application. Similarly, there are various other consequences such as One-Way transports that come into play when we need them. Let's try to analyze some common service invocation paradigms.

Many Web service engines provide users with a Blocking and Non-Blocking client APIs.

Both these mechanisms work in the API level. Let's name the asynchronous behavior that we can get using the Non-Blocking API as API Level Asynchrony.

Both these mechanisms use single transport connections to send the request and to receive the response. They severely lag the capability of using two transport connections for the request and the response (either One-Way or Two-Way). So both these mechanisms fail to address the problem of long running transactions (the transport connection may time-out before the operation completes). A possible solution would be to use two separate transport connections for request and response. The asynchronous behavior that we gain using this solution can be called Transport Level Asynchrony.

By combining API Level Asynchrony & Transport Level Asynchrony we can obtain four different invocation patterns for Web services as shown in the following table.

API (Blocking/Non-Blocking)

Dual Transports (Yes/No)

Description

Blocking

No

The simplest and more familiar invocation pattern

Non-Blocking

No

Using callbacks or polling

Blocking

Yes

This is useful when the service operation is IN-OUT in nature but the transport used is One-Way (e.g. SMTP)

Non-Blocking

Yes

This is can be used to gain the maximum asynchronous behavior. Non blocking in the API level and also in the transport level

Axis2 provides the user with all these possibilities to invoke Web services.

Following section present clients that use different possibilities presented above to invoke a Web Service using ServiceClients. All samples mentioned in this guide are located at the "samples\userguide\src" directory of the binary distribution.

This section presents four types of clients.

  1. Request-Response, Blocking Client
  2. One Way Client
  3. Request-Response, Non-Blocking that uses one transport connection
  4. Request-Response, Non-Blocking that uses two transport connections

Request-Response, Blocking Client

Axis2 provides the user with several invocation patterns for Web services, ranging from pure blocking single channel invocations to non-blocking dual channel invocations. Let's first see how we can write a client to invoke "echo" operation of "MyService" using the simplest blocking invocation. The client code you need to write is as follows.

  try {
            OMElement payload = ClientUtil.getEchoOMElement();
                        
            Options options = new Options();
            options.setTo(targetEPR); // this sets the location of MyService service
            
            ServiceClient serviceClient = new ServiceClient();
            serviceClient.setOptions(options);

            OMElement result = serviceClient.sendReceive(payload);
            
            System.out.println(result);

        } catch (AxisFault axisFault) {
            axisFault.printStackTrace();
        } 
}

1. The lines highlighted in green lines show the set of operations that you need to perform in order to invoke a Web service.

2. The rest is used to create the OMElement that needs to be sent and display the response OMElement.

To test this client, use the provided ant build file that can be found in the "Axis2_HOME/samples/userguide" directory. Run the "run.client.blocking" target. If you can see the response OMElement printed in your command line, then you have successfully tested the client.

One Way Client

In the Web service "MyService" we had an IN-ONLY operation with the name "ping" (see Creating a New Web Service). Let's write a client to invoke this operation. The client code is as follows:

 try {
       OMElement payload = ClientUtil.getPingOMElement();
       Options options = new Options();
       options.setTo(targetEPR);
       ServiceClient serviceClient = new ServiceClient();
       serviceClient.setOptions(options);
       serviceClient.fireAndForget(payload);
        /**
         * We have to block this thread untill we send the request , the problem
         * is if we go out of the main thread , then request wont send ,so
         * you have to wait some time :)
         */
       Thread.sleep(500);
     } 
catch (AxisFault axisFault) {
            axisFault.printStackTrace();
     }

Since we are accessing an IN-ONLY operation we can directly use the fireAndForget() in ServiceClient to invoke this operation. This will not block the invocation and will return the control immediately back to the client. You can test this client by running the target "run.client.ping" of the ant build file at "Axis2Home/samples/userguide".

We have now invoked the two operations in our service. Are we done? No! There's a lot more to explore. Let's see some other ways to invoke the same operations.

Request-Response, Non-Blocking that uses one transport connection

In the "EchoBlockingClient" once the serviceClient.sendReceive(payload); is called, the client is blocked till the operation is complete. This behavior is not desirable when there are many Web service invocations to be done in a single client application or within a GUI. A solution would be to use a Non-Blocking API to invoke Web services. Axis2 provides a callback based non-blocking API for users.

A sample client for this can be found under "Axis2_HOME/samples/userguide/src/userguide/clients" with the name "EchoNonBlockingClient". If we consider the changes that users may have to do with respect to the "EchoBlockingClient" that we have already seen, it will be as follows:

serviceClient.sendReceiveNonblocking(payload, callback);

The invocation accepts a callback object as a parameter. Axis2 client API provides an abstract Callback with the following methods:

public abstract void onComplete(AsyncResult result);
public abstract void onError(Exception e);
public boolean isComplete() {}

The user is expected to implement the "onComplete " and "onError " methods of their extended call back class. The Axis2 engine calls the "onComplete" method once the Web service response is received by the Axis2 Client API (ServiceClient). This will eliminate the blocking nature of the Web service invocation and provide users with the flexibility to use Non Blocking API for Web service Clients.

To run the sample client ("EchoNonBlockingClient") you can simply use the run.client.nonblocking target of the ant file found at the "Axis2_HOME/samples/userguide" directory.

Request-Response, Non-Blocking that uses two transport connections

The solution provided by the Non-Blocking API has one limitation when it comes to Web service invocations which take a long time to complete. The limitation is due to the use of single transport connections to invoke the Web service and to retrieve the response. In other words, client API provides a non blocking invocation mechanism for users, but the request and the response come in a single transport (Two-Way transport) connection (like HTTP). Long running Web service invocations or Web service invocations using One-Way transports (like SMTP) cannot be utilized by simply using a non blocking invocation.

The trivial solution is to use separate transport connections (either One-Way or Two-Way) for the request and response. The next problem that needs to be solved is the correlation (correlating the request and the response). WS-Addressing provides a neat solution to this using <wsa:MessageID> and <wsa:RelatesTo> headers. Axis2 provides support for addressing based correlation mechanism and a complying Client API to invoke Web services with two transport connections. (Core of Axis2 does not depend on WS-Addressing, but contains a set of parameters like in addressing that can be populated in any means. WS-Addressing is one of the uses that may populate them. Even the transports can populate these. Hence Axis2 has the flexibility to use different versions of addressing)

Users can select between Blocking or Non-Blocking APIs for the Web service clients with two transport connections. By simply using a boolean flag, the same API can be used to invoke Web services (IN-OUT operations) using two separate transport connections. Let's see how it's done using an example. Following code fragment shows how to invoke the same "echo" operation using Non-Blocking API with two transport connections. The ultimate asynchrony!!

  try {
            OMElement payload = ClientUtil.getEchoOMElement();

            Options options = new Options();
            options.setTo(targetEPR);
            options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
            options.setUseSeparateListener(true);
            options.setAction("urn:echo");  // this is the action mapping we put within the service.xml

            //Callback to handle the response
            Callback callback = new Callback() {
                public void onComplete(AsyncResult result) {
                    System.out.println(result.getResponseEnvelope());
                }

                public void onError(Exception e) {
                    e.printStackTrace();
                }
            };
            //Non-Blocking Invocation            
            sender = new ServiceClient();            
            sender.engageModule(new QName(Constants.MODULE_ADDRESSING));
            sender.setOptions(options);            
            sender.sendReceiveNonBlocking(payload, callback);            
            //Wait till the callback receives the response.            
            while (!callback.isComplete()) {                
             Thread.sleep(1000);            
            }            
            //Need to close the Client Side Listener.        
            } catch (AxisFault axisFault) {            
              axisFault.printStackTrace();
            } catch (Exception ex) {
              ex.printStackTrace();
            } finally {
            try {
                sender.cleanup();
            } catch (AxisFault axisFault) {
                //have to ignore this
            }
        }

The boolean flag (value true) in the options.setUseSeparateListener(...) method informs the Axis2 engine to use separate transport connections for request and response. Finally sender.cleanup() informs the Axis2 engine to stop the client side listener started to retrieve the response.

To run the sample client ("EchoNonBlockingDualClient") you can simply use the "run.client.nonblockingdual" target of the ant file found at the "Axis2_HOME/samples/userguide/" directory.