Friday

dynamic client for a web service in Apache Axis 2

After a discussion with a friend, who he was asked to crate a client for some Axis web services, i noticed various problems on requirements gathering (even the simple one concerning, the case of where and how the client will use the service). Though an as simple and dirty solution proposed to him (use the soapUI to create the client stubs from the proper test-cases) i have see that the issue could take a number of alternative ways.

In Apache Axis2, the are several ways to write a client for a web service. One approach would be to use WSDL2Java, the code generation tool provided with Axis2 generate a stub for the web service and use that stub to consume the web service.

Other option is to write a dynamic client. This is how you can write a dynamic client for a web service.

First we will expose a simple POJO as a web service, in order to create its client:


package org.wso2.training;

public class CalculatorService {

public int add (int a, int b) {
return a + b;
}

public int multiply(int a, int b) {
return a * b;
}

}

Exposing this as a web service is a matter of 2 lines of code ...

    AxisServer axisServer = new AxisServer();
axisServer.deployService(CalculatorService.class.getName());


Now, the WSDL for this web service will be available at

http://localhost:6060/axis2/services/CalculatorService?wsdl

Now we must see how we can write a dynamic client for this web service (my friend should start from this point):


//Create a service client for given WSDL service by passing the following four parameters
//ConfigurationContext - we keep it as null
//wsdlURL - The URL of the WSDL document to read
//wsdlServiceName The QName of the WSDL service in the WSDL document
//portName The name of the WSDL 1.1 port to create a client for.

RPCServiceClient dynamicClient = new RPCServiceClient(null, new URL(
"http://localhost:6060/axis2/services/CalculatorService?wsdl"), new QName(
"http://training.wso2.org", "CalculatorService"),
"CalculatorServiceHttpSoap12Endpoint");

// We provide the parameters as an object array and return types as an class array
Object[] returnArray = dynamicClient.invokeBlocking(new QName("http://training.wso2.org","add"),
new Object[] { 1, 2 }, new Class[] { Integer.class });

System.out.println("1 + 2 = " + returnArray[0]);

returnArray = dynamicClient.invokeBlocking(new QName("http://training.wso2.org","multiply"),
new Object[] { 1, 2 }, new Class[] { Integer.class });

System.out.println("1 X 2 = " + returnArray[0]);

.




and this snipett of code should suffice in order to be able to incorporate it into the custom client application to use it and handle the returnArray proper to the business needs.

No comments: