Friday, March 23, 2007

Invoking Axis2 web service dynamically

Using Axis2 client api you can easily invoke an Axis2 web service easily. Steps are described below

First you have to create and deploy a service. For simplicity I create a service which echos.

public class SimpleService
{
public String echo(String msg)
{
return msg;
} //end of method echo
} //end of class SimpleService

Compile the java file and get the SimpleService.class file
2.Now we have to package it as an axis service
now create a file called services.xml
services.xml should contain the following lines of code

<service name="SimpleService">

<description>

This service is to get the running Axis version

</description>

<parameter name="ServiceClass">SimpleService</parameter>

<operation name="echo">

<messageReceiver class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />

</operation>

</service>

Axis2 expects services to be packaged accoring to a certain format.The package muct be a .jar file with the compiled java classes and a META-INF directory which will hold the services.xml file. The jar file can be name .aar to distinguish it as an Axis2 service archive. It's important to note that the part of the file name before .aar is the service name. Create a temp directory in the same location where the SimpleService.java file exists

[Linux]
mkdir temp

Now compile the SimpleService.java class and move the SimpleService.class file to the temp directory

javac SimpleService.java -d temp/

create a META-INF directory within the "temp" directory and copy the service.xml file inot the META-INF directory. Change directory to the temp directory and user the jar command as follows to creat ehe srevice archive named SimplService .aar

jar -cvf SimpleService.aar *

Here i'm using the simple Http server comes with Axis2. Now put the created archive into the services directory , which resides in the repository directory.

Now start the server
[linux]
cd bin
sh axis2server.sh

now open a web browser and you can find the service just deployed when entering the url
http://localhost:8080/axis2 int to the web browser.

Invoking the service dynamically

package kan;

import javax.xml.namespace.QName;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.rpc.client.RPCServiceClient;

public class SimpleServiceClient {
public static void main(String[] args1) throws AxisFault {
RPCServiceClient serviceClient = new RPCServiceClient();
Options options = serviceClient.getOptions();
EndpointReference targetEPR = new EndpointReference( "http://localhost:8080/axis2/services/SimpleService");
options.setTo(targetEPR);
QName opecho = new QName("http://ws.apache.org/axis2", "echo");
Object[] args = new Object[1] ;
args[0] = new String("Hell0 I'm Kanchana");
System.out.println(serviceClient.invokeBlocking(opecho,args));
}//end of main
}//end of class

No comments: