Handling web services with apache axis
1 / 71

Handling Web Services with Apache AXIS - PowerPoint PPT Presentation

  • Uploaded on

Handling Web Services with Apache AXIS. Web-Service Review. By Examples. POST /wsprimegenerator.exe/soap/IPrimeGenerator HTTP/1.0 Content-Type: text/xml; charset=utf-8 Host: www.jusufdarmawan.com SOAPAction: "urn:UnitIPrimeGenerator-IPrimeGenerator#primegenerator" Content-Length: 527

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

PowerPoint Slideshow about ' Handling Web Services with Apache AXIS' - nickan

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

Web service review

Web-Service Review

By Examples ...

POST /wsprimegenerator.exe/soap/IPrimeGenerator HTTP/1.0

Content-Type: text/xml; charset=utf-8

Host: www.jusufdarmawan.com


Content-Length: 527

<?xml version="1.0" encoding="UTF-8"?>









<valstart xsi:type="xsd:string">12</valstart>

<valend xsi:type="xsd:string">120</valend>




A request to www.jusufdarmawan.com

HTTP/1.0 200 OK

Date: Mon, 09 May 2005 20:58:35 GMT

Content-Length: 619

Content-Type: text/xml

Server: Microsoft-IIS/5.0

X-Powered-By: ASP.NET

<?xml version="1.0" encoding='UTF-8'?>


xmlns:SOAP- ENV="http://schemas.xmlsoap.org/soap/envelope/"








<return xsi:type="xsd:string">13,17,19,23,29,31, 37, 41,43, 47,





The Response

POST /soap HTTP/1.0

SOAPAction: ""

Content-Length: 520

<?xml version="1.0" encoding="UTF-8"?>









<country1 xsi:type="xsd:string">Euro</country1>

<country2 xsi:type="xsd:string">Israel</country2>




A request to services.xmethods.net

HTTP/1.0 200 OK

Date: Sat, 07 May 2005 23:26:21 GMT

Content-Length: 492

Content-Type: text/xml

<?xml version='1.0' encoding='UTF-8'?>










<Result xsi:type='xsd:float'>5.5825</Result>




The Response

A WSDL Example

<?xml version="1.0"?>







<message name="getRateRequest">

<part name="country1" type="xsd:string"/>

<part name="country2" type="xsd:string"/>


<message name="getRateResponse">

<part name="Result" type="xsd:float"/>


<portType name="CurrencyExchangePortType">

<operation name="getRate">

<input message="tns:getRateRequest" name="getRate"/>

<output message="tns:getRateResponse" name="getRateResponse"/>



<soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>

<operation name="getRate">

<soap:operation soapAction=""/>

<input name="getRate">

<soap:body use="encoded" namespace="urn:xmethods-CurrencyExchange"



<output name="getRateResponse">

<soap:body use="encoded" namespace="urn:xmethods-CurrencyExchange"





<service name="CurrencyExchangeService">

<documentation>Returns the exchange rate between the two currencies</documentation>

<port name="CurrencyExchangePort" binding="tns:CurrencyExchangeBinding">

<soap:address location="http://services.xmethods.net:80/soap"/>




Wsdl elements
WSDL Elements








Port Type


A pache e x tensible i nteraction s ystem axis

Apache EXtensible Interaction System(Axis)

What is axis
What is AXIS

  • Axis is essentially a SOAP engine – a framework for constructing SOAP processors

    • client side

    • server side

  • Axis implements the interfaces of JAX-RPC (XML-based remote procedure calls in Java)

  • AXIS =Apache EXtensible Interaction System

Apache axis included tools
Apache AXIS: Included Tools

  • A simple stand-alone server

  • A Web application that resides in Servlet engines, such as Tomcat

  • Standalone tools for Web-service invocation

    • Java/C components

  • Extensive support for the Web Service Description Language(WSDL)

    • E.g., tools for generating Java classes (stubs) from WSDL and vice versa

  • … and more

Remote method invocation is not new
Remote Method Invocation is not New

  • java.rmi has been in Java since Java’s early versions

  • In Java RMI, objects can invoke methods of objects that reside on a remote computer

    • (RMI = Remote Method Invocation)

  • So, what has been changed?

    • Using HTTP for communication

    • Using agreed protocols, Java can invoke methods that were not written in Java (e.g., .NET methods) and vice versa

    • A complex registry procedure has been required in RMI

What we would like to create
What We Would Like to Create

  • Client applications: applications that can call a remote Web service

  • Services: methods that can be called by remote applications

  • Service descriptions: WSDL files that describe our methods

Calling web services
Calling Web Services

  • By now, we already know how to invoke a remote Web service in Java:

    • Open a socket to the remote server

    • Through the socket, send a SOAP request wrapped by a HTTP request

    • Parse the response (e.g., using SAX/DOM)

  • However, this approach is cumbersome, and most of it can be automated

    • This is the whole point of using standards…

Invoking services with apache
Invoking Services with Apache

  • Axis includes comfortable tools for managing calls to Web services

  • The programmer configures the request for the Web service using a friendly API

    • with, or without considering the WSDL

  • According to the configuration, a method invocation is transformed into a SOAP request that is sent to the remote server

Invoking services with axis
Invoking Services with Axis

  • To invoke an operation of a Web service, do the following:

    • Construct a Service instance

    • Using the Service instance, generate a Call instance

    • Configure the Call instance

    • Invoke the call

Example currency exchange
Example: Currency Exchange

import org.apache.axis.client.*;

import javax.xml.namespace.QName;

import javax.xml.rpc.ParameterMode;

import javax.xml.rpc.encoding.XMLType;

publicclass CurrencyExchange {

publicstaticvoid main(String[] args) throwsException {



String endpointUrl = "http://services.xmethods.net:80/soap";

String nsuri = "urn:xmethods-CurrencyExchange";

Service service = new Service();

Call call = (Call) service.createCall();

Example currency exchange cont
Example: Currency Exchange (cont)


call.setOperationName(new QName(nsuri,"getRate"));

call.addParameter("country1", XMLType.SOAP_STRING,


call.addParameter("country2", XMLType.SOAP_STRING,



Object ret = call.invoke(newObject[] {"Euro","Israel"});




Using the wsdl
Using the WSDL

  • Axis can read a given WSDL and configure the service as much as possible from that WSDL

  • Instead of using the default constructor, construct the service using the following constructor:

    Service(String wsdlLocation, QName serviceName)

  • When there is only one port, we can obtain it automatically

  • In this approach, you usually need to know the following about the service:

    • the WSDL URL, the service name, the namespace uri, the operation name and the expected arguments

public class CurrencyExchange2 {

publicstaticvoid main(String[] args)throwsException{



String wsdl ="http://www.xmethods.net/sd/2001/CurrencyExchangeService.wsdl";

QName sName =new QName("http://www.xmethods.net/sd/CurrencyExchangeService.wsdl",


String oName ="getRate";

Service service =new Service(wsdl, sName);

QName port =(QName)service.getPorts().next();

Call call =(Call)service.createCall(port, oName);



publicclass PrimeNumbers {

publicstaticvoid main(String[] args)throwsException{



String wsdl ="http://www50.brinkster.com/vbfacileinpt/np.asmx?wsdl";

QName sName =new QName("http://www50.brinkster.com/vbfacileinpt/np","pnum");

String oName ="GetPrimeNumbers";

Service service =new Service(wsdl, sName);

QName port = (QName)service.getPorts().next();

Call call = (Call)service.createCall(port, oName);

System.out.println(call.invoke(new Object[] {100}));


The wsdl2java application
The WSDL2Java Application

  • Axis provides a mechanism for communicating with a Web service using stubs

  • That is, generation of regular Java classes that have an interface similar to that of the Web service and implementation that wraps Web service management

  • Invoke class WSDL2Java in order to create the required Java classes

Generated classes
Generated Classes

  • WSDL2Java generates the following:

    • A service interface and a service implementation (locator) for each service

    • A stub class for each binding

    • An interface for each port type

      • This interface contains methods that correspond to the operations of the port type

    • A class for each complex type

Using the generated classes
Using The Generated Classes

import com.brinkster.www50.vbfacileinpt.np.*;

publicclass PrimeNumbers2 {

publicstaticvoid main(String[] args)throwsException {



PnumSoap ps =new PnumLocator().getpnumSoap();




Axis installation
AXIS Installation

  • Axis works inside a Servlet container (e.g., Tomcat)

  • You should add to your Tomcat libs some jar files: axis.jar, saaj.jar, wsdl4j.jar, …

  • You need to include several jar files in your CLASSPATH

  • This has already been done for you!

    • The needed CLASSPATH definitions where added to dbi.cshrc

    • The needed jar files are in $CATALINA_HOME/lib/

Axis installation cont









The directory that you need to copy

Classes were added for you

AXIS Installation (cont)

  • You need to copy the Axis application to your Tomcat's application directory:

    cp -r ~dbi/tomcat/axis/ $CATALINA_BASE/webapps

Creating a web service
Creating a Web Service

Next, we will see how we can create and publish a Web service using the Axis plugin in Tomcat

1 generate the implementing class
1. Generate the Implementing Class

package myws;

publicclass Power {

publicint power(int a, int n) {

return (int)Math.pow(a,n);



$CATALINA_BASE/webapps/axis/WEB-INF/ classes/myws/Power.class

2 deploy the service using web service deployment descriptor
2. Deploy the Service using Web Service Deployment Descriptor

<deployment xmlns="http://xml.apache.org/axis/wsdd/"


<service name="mypower" provider="java:RPC">

<parameter name="className" value="myws.Power"/>

<parameter name="scope" value="application"/>

<parameter name="allowedMethods" value="*"/>




java org.apache.axis.client.AdminClient

-hlocalhost -p8080 services.wsdd

That s it you can call the service
That's it! You Can Call the Service. Descriptor

import org.apache.axis.client.*;

publicclass PowerClient {

publicstaticvoid main(String[] argv)throwsException {

String endpoint =


Call call = (Call) new Service().createCall();



Object value = call.invoke(newObject[]

{newInteger(2), newInteger(5)});

System.out.println(2+"^"+5 +"=" + value);



How does it work
How Does it Work? Descriptor

  • The AXIS plugin is simply a Web application that resides in Tomcat (under webapps/)

  • The Servlet AxisServlet of this application is responsible for invoking services

  • All URLs of the form /services/* are mapped to the AxisServlet

    • Where is that written?

How does it work cont
How Does it Work? (cont) Descriptor

  • The wsdd file defines mappings between a Web service elements to a Java class elements

    • I.e., names, methods, etc.

  • The class AdminClient sends a request to the application to register the service based on the wsdd content

  • When a SOAP request arrives, the AxisServlet object parses the request and invokes the corresponding method of the class associated with the service URL

The deployment descriptor
The Deployment Descriptor Descriptor

<deployment xmlns="http://xml.apache.org/axis/wsdd/"


<service name="mypower" provider="java:RPC">

<parameter name="className" value="myws.Power"/>

<parameter name="scope" value="application"/>

<parameter name="allowedMethods" value="*"/>




The scope of the object
The Scope of the Object Descriptor

  • Request (the default): a new object is created for each request, the service instance is available for the duration of the request (regardless of forwarding)

  • Session: a new object is created for each new session and the service instance is available for the entire session

  • Application: a singleton shared service instance is used to serve all invocations

Undeploying a service
Undeploying a Service Descriptor

<undeployment xmlns="http://xml.apache.org/axis/wsdd/">

<service name="mypower"/>



java org.apache.axis.client.AdminClient

-hlocalhost -p8080 undeploy.wsdd

Implementing classes
Implementing Classes Descriptor

  • The class that implements the Web service must be accessible to the Axis Servlet

  • Hence, this class should reside in a package in


  • Of course, all helper classes should be accessible to the Axis application too

The service wsdl
The Service WSDL Descriptor

  • Axis automatically provides a WSDL for each deployed service

  • To get the WSDL, use the service URL with the empty argument wsdl


Power service wsdl
Power-Service WSDL Descriptor

<?xmlversion="1.0" encoding="UTF-8"?>








xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<wsdl:message name="powerResponse">

<wsdl:part name="powerReturn" type="xsd:int"/>


<wsdl:message name="powerRequest">

<wsdl:part name="a" type="xsd:int"/>

<wsdl:part name="n" type="xsd:int"/>


<wsdl:portType name= Descriptor"Power">

<wsdl:operation name="power" parameterOrder="a n">

<wsdl:input message="impl:powerRequest" name="powerRequest"/>

<wsdl:output message="impl:powerResponse" name="powerResponse"/>



<wsdl:binding Descriptorname="mypowerSoapBinding"type="impl:Power">

<wsdlsoap:binding style="rpc"


<wsdl:operation name="power">

<wsdlsoap:operation soapAction=""/>

<wsdl:input name="powerRequest">



namespace="http://myws" use="encoded"/>


<wsdl:output name="powerResponse">



namespace="http://localhost/axis/services/mypower" use="encoded"/>




<wsdl:service name= Descriptor"PowerService">

<wsdl:port binding="impl:mypowerSoapBinding"







Jws files
jws Files Descriptor

  • There is a fast and easy way of crating a service:

    • Create a Java class myClass.java

    • Rename your class to end with jws: myClass.jws

    • Put the jws file directly under the directory $CATALINA_BASE/webapps/axis/ (the application’s root)

    • That is all. Now you can call the service!

Example a calculator service
Example: a Calculator Service Descriptor

publicclass SimpleCalculator {

publicint add(int i1, int i2) {

return i1 + i2;


publicint subtract(int i1, int i2) {

return i1 - i2;




Service URL:


Example a calculator service1
Example: a Calculator Service Descriptor

publicclass CalculatorClient {

publicstaticvoid main(String[] argv)throwsException {

String endpoint =


Call call = (Call) new Service().createCall();



Object value = call.invoke(newObject[] {new

Integer(4), newInteger(6)});




How does it work1
How does it Work? Descriptor

  • On the first time the jws file is being called, it is compiled into a class

    • WEB-INF/jwsClasses/SimpleCalculator.class

  • Axis then considers the URL of the jws as one of a regular web service

    • Default configurations are assumed

  • Sounds like any other technology we know?

When not to use jws files
When not to Use jws Files Descriptor

  • When you do not have the Java source code

  • When you don’t want to expose your code

  • When you want to use custom type mappings

  • When you want to use other configuration options

Axis type mappings

Axis Type Mappings Descriptor

Axis type mappings1
Axis Type Mappings Descriptor

  • Axis uses mappings between SOAP types and Java classes and primitive types

  • Serialization and deserialization are executed by objects of the interfaces Serializer and Deserializer (provided by Axis), respectively

    • For example, SimpleSerializer, SimpleDeserializer, DateDeserializer, ArraySerializer

Axis Type Mapping

Complex type example service side

<service name=" Descriptortovector" provider="java:RPC">

<parameter name="className" value="myws.VectorService"/>

<parameter name="scope" value="application"/>

<parameter name="allowedMethods" value="getAsVector"/>



Complex Type Example - Service Side

package myws;

import java.util.*;

publicclass VectorService {

publicVector getAsVector(int[] array) {

Vector result = newVector();

for(int i=0; i<array.length; ++i)

result.add("Number " + array[i]);

return result;




Input in the wsdl
Input in The WSDL Descriptor

<complexType name="ArrayOf_xsd_int">


<restriction base="soapenc:Array">

<attribute ref="soapenc:arrayType" wsdl:arrayType="xsd:int[]"/>




<wsdl:message name="getAsVectorRequest">

<wsdl:part name="array" type="impl:ArrayOf_xsd_int"/>


Output in the wsdl
Output in The WSDL Descriptor

<complexType name="Vector">


<element maxOccurs="unbounded" minOccurs="0"

name="item" type="xsd:anyType"/>



<wsdl:message name="getAsVectorResponse"

<wsdl:part name="getAsVectorReturn"



Complex type example client side
Complex Type Example - Client Side Descriptor

import java.util.*;

import org.apache.axis.client.*;

publicclass VectorClient {

publicstaticvoid main(String[] argv)throwsException {

String endpoint = "http://localhost:7000/axis/services/tovector";

Call call = (Call) new Service().createCall();



int[] array = {3,7};

Vector value =

(Vector)call.invoke(newObject[] {array});




A snapshot from the request
A Snapshot from the Request Descriptor



<arg0 xsi:type="soapenc:Array"







A snapshot from the response
A Snapshot from the Response Descriptor



<getAsVectorReturn href="#id0"/>


<multiRef id="id0" soapenc:root="0"





<item xsi:type="soapenc:string">Number 3</item>

<item xsi:type="soapenc:string">Number 7</item> </multiRef>

Java beans
Java Beans Descriptor

  • Java Beans are simply objects of classes that follow some (natural) coding conventions:

    • An empty constructor

    • A readable property has a matching getter

    • A writable property has a matching setter

  • A property has name and a type

  • The getter of property prop: typegetProp()

  • The setter of property prop: void setProp(type)

An example1

property DescriptorfirstName

Property lastName

Property id

An Example

package myws;

publicclass Person {

privateString firstName, lastName;

privateint personID;

publicString getFirstName() {return firstName;}

publicvoid setFirstName(String firstName) {

this.firstName = firstName;}

publicString getLastName() {return lastName;}

publicvoid setLastName(String lastName) {

this.lastName = lastName;


publicvoid setId(int id) {personID = id;}

publicint getId(int id) {return personID;}


Using beans in web services
Using Beans in Web Services Descriptor

  • A Web service can use beans in its definition

    • either in its input or output

  • For that, you need to tell the Axis engine that the corresponding object needs to be serialized as a bean

  • In this serialization, every accessible property (i.e., one that has a getter/setter) is specified

  • Where, in the file system, should the bean class reside?

A service example
A Service Example Descriptor

package myws;

publicclass PersonService {

public Person createPerson() {

Person person = new Person();




return person;



The wsdd
The WSDD Descriptor

<deployment xmlns="http://xml.apache.org/axis/wsdd/"


<service name="person" provider="java:RPC">

<parameter name="className"


<parameter name="scope" value="application"/>

<parameter name="allowedMethods" value="*"/>

<beanMapping qname="ns:person"





Using beans in clients
Using Beans in Clients Descriptor

  • To use a bean on the client side, you need to configure service to deserialize the SOAP type into a Java bean

  • For that, we use the class BeanDeserializer provided by Axis

  • Note that client and server beans need not be the same class

    • What should they have in common?

public Descriptorclass PersonClient {

publicstaticvoid main(String[] argv) throwsException {

String endpoint = "http://localhost/axis/services/person";

Call call = (Call) new Service().createCall();



QName qn =

new QName("http://www.cs.huji.ac.il/~dbi/xsd", "person");

BeanDeserializerFactory bdf = new


call.registerTypeMapping(MyPerson.class, qn, null, bdf);

MyPerson value = (MyPerson)call.invoke(newObject[] {});




Identical to Person

Exception handling

Exception Handling Descriptor

Exception in service calls
Exception in Service Calls Descriptor

  • Several problems can cause exception to be thrown when a service is being invoked

  • For example

    • the server cannot be connected

    • the server does not find the requested URL

    • the request is inappropriate (no such operation, invalid arguments, etc.)

    • the implementing service method has thrown an exception

Service exception
Service Exception Descriptor

  • When the implementing service throws an exception, a SOAP fault response is returned by the server

  • The client invocation method translates this response to a java.rmi.RemoteException after parsing the response

An example2
An Example Descriptor

package myws;

publicclass ExceptionService {

publicvoid throwException() throwsIllegalStateException {


("I only throw an exception!");


<service name="exception" provider="java:RPC">

<parameter name="className"


<parameter name="allowedMethods" value="*"/>



public Descriptorclass ExceptionClient {

publicstaticvoid main(String[] argv){

String endpoint = "http://localhost:80/axis/services/exception";

try {

Call call = (Call) new Service().createCall();



Object value = call.invoke(newObject[] {});



catch(RemoteException exp) {

System.err.println("WS invocation error: " +



catch(Exception exp) {

System.err.println("Error: " + exp.getMessage());}}}

A snapshot from the response1
A Snapshot from the Response Descriptor




<faultstring>java.lang.IllegalStateException:I only throw an