Apache Axis2 User's Guide

hipshorseheadsServers

Nov 17, 2013 (3 years and 7 months ago)

226 views

Apache Axis2 User's Guide


creative consultants

Ch.1 Introducing
Axis2



This section introduces Axis2 and its structure, including an
explanation of various directories/files included in the latest
Axis2

download.


Content


What is Axis2?


What's under the hood?


How Axis2 handles SOAP messages


Axis2 Distributions


The Axis2 Standard Binary Distribution


Axis2.war Directory Hierarchy


Axis2 Documents Distribution


Axis2 and Clients


creative consultants

What is Axis2?



The Apache Axis2 project is a Java
-
based implementation of both the client and
server sides of the Web services equation. Designed to take advantage of the
lessons learned from Apache Axis 1.0, Apache Axis2 provides a complete object
model and a modular architecture that makes it easy to add functionality and
support for new Web services
-
related specifications and recommendations.


Axis2 enables you to easily perform the following tasks:


Send SOAP messages


Receive and process SOAP messages


Create a Web service out of a plain Java class


Create implementation classes for both the server and client using WSDL


Easily retrieve the WSDL for a service


Send and receive SOAP messages with attachments


Create or utilize a REST
-
based Web service


Create or utilize services that take advantage of the

WS
-
Security
,

WS
-
ReliableMessaging
,

WS
-
Addressing
,
WS
-
Coordination
, and

WS
-
Atomic
Transaction

recommendations


Use Axis2's modular structure to easily add support for new recommendations as
they emerge


Many more features exist as well, but this user guide concentrates on showing you
how to accomplish the first five tasks on this list.


creative consultants

What's Under the Hood?



To understand Axis2 and what it does, you must have a good idea of the
life cycle of a Web services message. Typically, it looks something like this:




creative consultants


The

sending

application

creates

the

original

SOAP

message,

an

XML

message

that

consists

of

headers

and

a

body
.

(For

more

information

on

SOAP,

see

"
Introduction

to

Services
"
.
)

If

the

system

requires

the

use

of

WS*

recommendations

such

as

WS
-
Addressing

or

WS
-
Security,

the

message

may

undergo

additional

processing

before

it

leaves

the

sender
.

Once

the

message

is

ready,

it

is

sent

via

a

particular

transport

such

as

HTTP,

JMS,

and

so

on
.


The

message

works

its

way

over

to

the

receiver,

which

takes

in

the

message

via

the

transport

listener
.

(In

other

words,

if

the

application

doesn't

have

an

HTTP

listener

running,

it's

not

going

to

receive

any

HTTP

messages
.
)

Again,

if

the

message

is

part

of

a

system

that

requires

the

use

of

WS
-
Security

or

other

recommendations,

it

may

need

additional

processing

for

the

purpose

of

checking

credentials

or

decrypting

sensitive

information
.

Finally,

a

dispatcher

determines

the

specific

application

(or

other

component,

such

as

a

Java

method)

for

which

the

message

was

intended,

and

sends

it

to

that

component
.

That

component

is

part

of

an

overall

application

designed

to

work

with

the

data

being

sent

back

and

forth
.

How Axis2 Handles SOAP Messages



Axis2 can handle processing for both the sender and the receiver in a transaction.
From the Axis2 perspective, the structure looks like this
:


creative consultants

On each end, you have an application designed to deal with the (sent or received)
messages. In the middle, you have Axis2, or rather, you

can

have Axis2
.

The value of Web services is that the sender and receiver
don't
even have to be on the
same platform, much less running the same application. Assuming that Axis2 is
running on both sides, the process looks like this:


The sender creates the SOAP message.


Axis "handlers" perform any necessary actions on that message such as encryption
of WS
-
Security related messages.


The transport sender sends the message.


On the receiving end, the transport listener detects the message.


The transport listener passes the message on to any handlers on the receiving side.


Once the message has been processed in the "pre
-
dispatch" phase, it is handed off
to the dispatchers, which pass it on to the appropriate application.



In

Axis
2
,

these

actions

are

broken

down

into

"phases",

with

several

pre
-
defined

phases,

such

as

the

"pre
-
dispatch",

"dispatch,"

and

"message

processing",

being

built

into

Axis
2
.

Each

phase

is

a

collection

of

"handlers"
.

Axis
2

enables

you

to

control

what

handlers

go

into

which

phases,

and

the

order

in

which

the

handlers

are

executed

within

the

phases
.

You

can

also

add

your

own

phases

and

handlers
.


Handlers

come

from

"modules"

that

can

be

plugged

into

a

running

Axis
2

system
.

These

modules,

such

as

Rampart,

which

provides

an

implementation

of

WS
-
Security,

and

Sandesha,

which

provides

an

implementation

of

WS
-
ReliableMessaging,

are

the

main

extensibility

mechanisms

in

Axis
2
.


creative consultants

Axis2 Distributions



Axis2 is released in several

distributions
. Which one you need depends on what
you'll be doing with it.


The Axis2 Standard Binary Distribution


If you're developing services and applications, you'll need the Axis2 Standard
Binary Distribution. The distribution includes all the necessary *.jar files, as well as
a variety of scripts that ease development. It has the following structure.


creative consultants

Code Listing 1: Axis2 Standard Binary Distribution

bin


axis2.bat


axis2.sh



axis2server.bat



axis2server.sh



java2wsdl.bat



java2wsdl.sh



wsdl2java.bat



wsdl2java.sh



setenv.sh

lib



activation
-
1.1.jar



...



XmlSchema.jar



repository modules



modules.list



addressing
-
1.1.mar



..

services



services.list



version.aar



..



samples



... webapp



...



conf axis2.xml


LICENSE.txt

README.txt

NOTICE.txt INSTALL.txt


release
-
notes.html

creative consultants


The bin directory includes a number of useful scripts. They include axis2.bat (or
axis2.sh), which enables you to easily execute a Java command without having to
manually add all the Axis2 jar files to the classpath, java2wsdl.bat (and .sh) and
wsdl2java.bat (and .sh), which enable you to easily generate Java code from a
WSDL file and vice versa, and axis2server.bat (and sh), a simple Web server that
enables you to build Axis2's capability to send and receive messages into your own
application.


As expected, the lib directory includes all the necessary .jar files. Services and
modules are added to the repository directory. Axis2 comes with a standard
module implementing WS
-
Addressing, and you can add any other necessary
module such as Rampart to the repository/modules directory.


conf directory includes the axis2.xml which is the global deployment descriptor.


Finally, the samples directory includes all the sample code distributed with Axis2.
See the list of

samples and their descriptions
.


creative consultants

axis2.war Distribution Directory Hierarchy


axis2.war is available in

WAR (Web Archive) Distribution
. The server side of Axis2 ships as a J2EE application,
and has the following structure shown in Code Listing 2
.

Code Listing 2: Server Side of Axis2

axis2
-
web

META
-
INF


WEB
-
INF



classes


conf



axis2.xml


lib



activation.jar



...



xmlSchema.ja
r


modules



modules.list



addressing.mar



...



soapmonitor.mar

services



services.list



aservice.aar



...



version.aar


web.xml


creative consultants


Starting

at

the

top,

axis
2
-
web

is

a

collection

of

JSPs

that

make

up

the

Axis
2

administration

application
,

through

which

you

can

perform

any

needed

actions

such

as

adding

services

and

engaging

and

dis
-
engaging

modules
.

The

WEB
-
INF

directory

represents

the

actual

Axis
2

application,

including

all

the

*
.
jar

files,

any

included

modules,

and

even

the

deployed

services

themselves
.


The

classes

directory

holds

any

class

or

property

files

that

are

needed

by

Axis
2

itself,

such

as

log
4
j
.
properties
.

Any

actual

services

to

be

handled

by

the

system

reside

in

the

services

directory

in

the

form

of

an

axis

archive,

or

*
.
aar

file
.

This

file

contains

any

classes

related

to

the

service,

as

well

as

the

services
.
xml

file,

which

controls

any

additional

requirements,

such

as

the

definition

of

message

senders

and

message

receivers
.


The

main

file

in

all

this

is

axis
2
.
xml,

which

controls

how

the

application

deals

with

received

messages
.

It

defines

message

receivers

and

transport

receivers,

as

well

as

defining

transport

senders

and

determining

which

modules

are

active
.

It

also

defines

the

order

of

phases,

and

the

handlers

to

be

executed

within

each

phase
.


You

can

control

all

of

this

information

through

the

use

of

the

Web

application,

but

if

you

restart

the

Axis
2

application,

these

changes

are

lost

and

the

server

goes

back

to

the

definitions

in

the

axis
2
.
xml

file
.


Axis
2

also

provides

a

third

distribution,

the

source

distribution
,

which

enables

you

to

generate

this

.
war

file

yourself
.


creative consultants

Axis2 Documentation Distribution Directory
Hierarchy


The Documents distribution includes all Axis2 documentation including the xdcos and
javadocs. It has the following structure:

Code Listing 3: Axis2 Documents Distribution

docs



javadocs



xdocs

LICENSE.txt

README.txt

release
-
notes.html

creative consultants

The javadocs directory includes all the standard

API documentation

for the Axis2
API, with other documentation (like this document) in the xdocs directory.

Axis2 and Clients



Now that explains how Axis2 behaves as part of a Web application. What about a
standalone client that is not part of a J2EE application? In that case, a sender can
use the Axis2 default properties, in other words, no special handlers, and so on.
But you also have the option to tell the client to load its own copy of the axis2.xml
file and behave accordingly.


creative consultants

Ch.2 Installing and testing client code

The
Short Story:


Install Apache Axis2 in a suitable container, such as Apache Tomcat, by copying the axis2.war file to the
webapps directory.


Install the service into the Axis2 application by copying the *.aar file into the Axis2 services directory.


Install the client on the system on which you want to run it, and make sure all the Axis2 libraries are on the
CLASSPATH.


Run the client
.


The Long Story:


Start by installing a suitable container, such as

Apache Tomcat
. Any J2EE server will do. To install Apache
Axis2 on the server,

download

the Axis2 WAR distribution and place the axis2.war file in the server's
webapps directory. The server will then expand the distribution into its proper structure, as seen in
the

earlier section
.


Apache Axis2 services come bundled as *.aar files, which contain all the pieces necessary to define the
service, such as the necessary classes and libraries and the services.xml file that defines the service's
behavior. You can install the service using the

Web administration application
, but to make things simple
for now, copy the *.aar file into the Axis2 services directory. For example, to install the MyService service
distributed as one of the Axis2 samples, copy the file
<AXIS2_HOME>/samples/userguide/build/MyService.aar file, which is built using the

ant

command, from
<AXIS2_HOME>/samples/userguide, to the directory <J2EE_HOME>/webapps/axis2/WEB
-
INF/services.


Your client can come in any number of forms, from a collection of files to a single *.jar file. The important
thing is to ensure that all the appropriate classes are on the classpath. In addition to the classes that
pertain to the actual client, you must also add the Axis2 .jar files into the CLASSPATH. Normally you will do
this by downloading and unpacking the

Axis2 Standard Distribution

and adding the *.jar files in the lib
directory to your CLASSPATH, or you also have the option of running your client using the axis2.bat (or
axis2.sh) script, which takes care of it for you. For example, you can run a client with the command:



axis2
org.apache.axis2.axis2userguide.Client.


creative consultants

Ch. 3
Introduction to Services



Code Listing 4: Example SOAP
Message


<?xml version='1.0' ?>

<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap
-
envelope"

xmlns:wsa="http://www.w3.org/2005/03/addressing">


<env:Header>



<wsa:MessageID>


http://ws.apache.org/9C21DE32
-
DB42
-
1228
-
C42E
-
66CB101421AD


</wsa:MessageID>


<wsa:ReplyTo>


<wsa:Address>http://example.com/projects/clientApp</wsa:Address>


</wsa:ReplyTo>



<wsa:To>http://example.com/axis2/publishingService</wsa:To>



<wsa:Action>http://example.com/axis2/addDocument</wsa:Action>



</env:Header>


<env:Body>



<addDocument>


<docTitle>What I Did On My Summer Vacation</doctitle>


<docSubtitle>Children's Essays from Accross the World</docSubtitle>


<docLocation>contentRepos/summerVac.doc</docLocation>


</addDocument>



</env:Body>

</env:Envelope>

creative consultants


This XML document consists of the outer element or the SOAP
Envelope, and its contents. The SOAP Envelope is in the SOAP
namespace, http://www.w3.org/2003/05/soap
-
envelope, prefixed
as env: and contains up to two children. This envelope is a standard
format that pertains to every single SOAP message sent and
received by any SOAP Web service.


The contents of the Envelope consists of two parts; the first being
the SOAP headers
-
the contents of the env:Header element. These
headers, such as the WS
-
Addressing elements shown here, provide
additional information about the message and how it should be
handled. A SOAP message may carry headers relating to several
aspects of the message, or it may carry no headers at all. These
headers are typically processed by the message handlers.


The second and arguably the most important part of the message is
the payload, which consists of the contents of the env:Body
element. This is the actual message intended for the receiver, and it
is the information that the main application will ultimately process.


creative consultants

Message Exchange Patterns



Although all SOAP messages carry the same structure, the ways in which they are used can
be combined into a number of different "message exchange patterns", or MEPs. The two
major message exchange patterns are:


In
-
Out: in this MEP, the client sends a SOAP message to the server, which processes the
message and sends a response back. This is probably the most commonly used MEP, and is
useful for tasks such as searching for information or submitting information in situations in
where acknowledgment is important.


In
-
Only: In this MEP, the client sends a message to the server without expecting a response.
You may use this MEP for activities such as pinging a server to wake it up, reporting logging
information for which you do not need an acknowledgment and so on.


Within these two MEPs, you also have several variables to consider:


Blocking versus non
-
blocking: When the client sends a message, the application may wait to
receive a response before moving on, or it may simply send a message and move on by
specifying a callback action to be completed when the response is received.


Number of parameters: Ultimately, a message sent from a client to server is intended to
execute a particular action. That action may not require any parameters, or it may require
one or more parameters. These parameters must be encoded as part of the payload of the
message.


Taking all these options into consideration, you can create virtually any MEP. For example,
you can create an Out
-
Only system by reversing roles for the In
-
Only MEP. Apache Axis2 also
includes support for less prominent MEPs, such as Robust
-
In
-
Only.


creative consultants

Ch.4
Creating Clients


Choosing a Client Generation Method


Generating Clients


Axis Data Binding (ADB
)

creative consultants

Choosing a Client Generation Method



Axis2 gives you several options when it comes to mapping WSDL to objects when
generating clients. Three of these options are Axis2 DataBinding Framework, XMLBeans,
and JiBX databinding. All of these methods involve using databinding to create Java
objects out of the XML structures used by the service, and each has its pros and cons.
You can also generate XML in
-
out stubs that are not based on databinding.


Axis2 Databinding Framework (ADB): ADB is probably the simplest method of
generating an Axis2 client. In most cases, all of the pertinent classes are created as
inner classes of a main stub class. ADB is very easy to use, but it does have limitations. It
is not meant to be a full schema binding application, and has difficulty with structures
such as XML Schema element extensions and restrictions.


XMLBeans: Unlike ADB, XMLBeans is a fully functional schema compiler, so it doesn't
carry the same limitations as ADB. It is, however, a bit more complicated to use than
ADB. It generates a huge number of files, and the programming model, while being
certainly usable, is not as straightforward as ADB.


JiBX: JiBX is a complete databinding framework that actually provides not only WSDL
-
to
-
Java conversion, as covered in this document, but also Java
-
to
-
XML conversion. In some
ways, JiBX provides the best of both worlds. JiBX is extremely flexible, enabling you to
choose the classes that represent your entities, but it can be complicated to set up. On
the other hand, once it is set up, actually using the generated code is as easy as using
ADB.


In the end, for simple structures, ADB will likely be enough for you. If, on the other hand
you need more power or flexibility, whether you choose XMLBeans or JiBX depends on
how much power or flexibility you need and your tolerance for complexity.


creative consultants

Generating Clients



The process for generating and using a client varies slightly
depending on the method of generation you choose. In all
three cases in this document, clients are generated from the
same WSDL file (see

Code Listing 5
).


Note that the document defines four operations, DoInOnly,
NoParameters, TwoWayOneParameterEcho, and
MultipleParametersAddItem. Each of the clients will include
methods for calling each of these operations.


creative consultants

Axis Data Binding (ADB)



To create a client using ADB, execute the following steps:


The short story:


To create a client using ADB, execute the following steps:



The short story:



Download and unpack the Apache Axis2 Standard Distribution, if you have not done it already.


Create the client stub with the following command:


%AXIS2_HOME%
\
bin
\
WSDL2Java
-
uri Axis2UserGuide.wsdl
-
p org.apache.axis2.axis2userguide
-
d
adb
-
s


Create the client (for example, Client.java), a Java application that uses the generated stub, and
save it in the org/apache/axis2/axis2userguide directory.


Build the client by typing: ant jar.client.


Assuming you have a corresponding service, run the client by adding the generated
Axis2UserGuideService
-
test
-
client.jar file located in build/lib to the classpath and type: java
org.apache.axis2.axis2userguide.Clientand
unpack the Apache Axis2 Standard Distribution, if you
have not done it already.


Create the client stub with the following command
:%AXIS2_HOME%
\
bin
\
WSDL2Java
-
uri
Axis2UserGuide.wsdl
-
p org.apache.axis2.axis2userguide
-
d adb
-
s


Create the client (for example, Client.java), a Java application that uses the generated stub, and
save it in the org/apache/axis2/axis2userguide directory.


Build the client by typing: ant jar.client.


Assuming you have a corresponding service, run the client by adding the generated
Axis2UserGuideService
-
test
-
client.jar file located in build/lib to the classpath and type: java
org.apache.axis2.axis2userguide.Client


creative consultants


The long story:


If you have not done it already,

The long story:



If you have not done it already, download and unpack the Apache Axis2
Standard Distribution. The Axis2 WAR Distribution does not include the
necessary utilities for generating code, such as WSDL2Java.



In the ADB method of generating clients, all the functionalities of the services
are contained in a single class called a stub. The stub contains inner classes
corresponding to all the necessary objects defined in the WSDL file, such as, in
the case of this WSDL, DoInOnlyRequestMessage. Once you have the stub, you
will be able to create a client by simply referring to these classes and their
methods. To generate the client, issue the following command in Code Listing
6.

and unpack the Apache Axis2 Standard Distribution. The Axis2 WAR
Distribution does not include the necessary utilities for generating code, such
as WSDL2Java.


In the ADB method of generating clients, all the functionalities of the services
are contained in a single class called a stub. The stub contains inner classes
corresponding to all the necessary objects defined in the WSDL file, such as, in
the case of this WSDL, DoInOnlyRequestMessage. Once you have the stub, you
will be able to create a client by simply referring to these classes and their
methods. To generate the client, issue the following command in Code Listing
6.


creative consultants

Code Listing 6
-

Generating the Client



%AXIS2_HOME%
\
bin
\
WSDL2Java
-
uri Axis2UserGuide.wsdl
-
p
org.apache.axis2.axis2userguide
-
d adb

s


This command analyzes the WSDL file and creates the stub in the package
org.apache.axis2.axis2userguide. The options specify that you want the ADB data
binding method (
-
d), and synchronous or blocking, methods (
-
s). In other words, when
the client makes an In
-
Out call to the service, it will wait for a response before
continuing.


Once you run this command, you will see two new items in the directory. The first is the
build.xml file, which contains the instructions for

Ant

to compile the generated classes.
The second is the src directory, which contains the actual
Axis2UserGuideServiceStub.java file. If you open this file, you will see a collection of
inner classes for each of the items in the WSDL file. You'll also see a number of calls to
the Axis2 client API, including those that use AXIOM to build and analyze the incoming
and outgoing messages.


Now you need a client to make use of this code. To create a client, create a new class
and save it as Client.java in the org/apache/axis2/axis2userguide directory. It should
contain the following code in

Code Listing 7
.


Note that using the service is simply a matter of creating and populating the
appropriate type of request using the names defined in the WSDL file, and then using
the stub to actually send the request to the appropriate method. For example, to call
the DoInOnly operation, you create a DoInOnlyRequest, use its setMessageString()
method to set the contents of its messageString element, and pass it as an argument to
stub.DoInOnly().


To build the client, type: ant jar.client


creative consultants


This action creates two new directories, build and test. The test directory will be empty, but
the build directory contains two versions of the client. The first version, in the lib directory, is
a .jar file that contains the client class and the stub. The second, in the classes directory, is
just raw classes.


Make sure all the jar files in the Axis2 lib directory are in the classpath.


If you have a service corresponding to this client you can run the client by adding the jar file
to your classpath and typing: java org.apache.axis2.axis2userguide.Client


(If you don't have such a service,, refer to the

Building services

document.)


You should see the response in the console window of your servlet container. It should look
something like this:


ADB is not your only option for generating Web service clients. Other options
include

XmlBeans
,

JiBX

and JAXBRI.

creative consultants

Building Services


Getting Comfortable with Available Options


Creating a Service from Scratch


Deploying Plain Old Java Objects


Deploying and Running an Axis2 Service Created from WSDL


creative consultants


Getting
Comfortable with the Available Options



Axis2
provides a number of ways to create a service, such as:


Create a service and build it from scratch. In this case, you build your service class
to specifically access AXIOM OMElement objects, then create the services.xml file
and package it for deployment.


Deploy Plain Old Java Objects (POJOs) as a service.


Generate the service from WSDL. Just as you can generate clients with WSDL, you
can also generate the skeleton of a service.



We have three options let us have a look

creative consultants

Creating a Service from Scratch


Creating a service from scratch is not the most convenient way to do it, but it does
give you the most control. The process involves several steps.

The short story:


Create
the service class with each operation that is represented by a method that
takes an org.apache.axiom.om.OMElement object as its argument. (An OMElement is
how the AXIs2 Object Model (AXIOM) represents an XML element.)

Create the service descriptor, services.xml, which defines the class to be used by the
service and the appropriate message receivers.

Create the .aar file, with the classes in their proper locations based on the package
and the services.xml file in the META
-
INF directory.

Deploy the .aar file by using the

Web Administration application

or by copying it to the
Axis2 services directory.

The long story:


Start
by creating the service class, a plain Java class that uses classes from the
Axis2 libraries (see Code Listing 8).


creative consultants

Code Listing 8
-
Creating the Service Class


package org.apache.axis2.axis2userguide;

import javax.xml.stream.XMLStreamException;

import org.apache.axiom.om.OMAbstractFactory;

import org.apache.axiom.om.OMElement;

import org.apache.axiom.om.OMFactory;

import org.apache.axiom.om.OMNamespace;

public class SampleService {


public OMElement sayHello(OMElement element)


throws XMLStreamException {


element.build();


element.detach();


String rootName = element.getLocalName();


System.out.println("Reading "+rootName+" element");


OMElement childElement = element.getFirstElement();


String personToGreet = childElement.getText();


OMFactory fac = OMAbstractFactory.getOMFactory();


OMNamespace omNs = fac.createOMNamespace(


"http://example1.org/example1", "example1");


OMElement method = fac.createOMElement("sayHelloResponse",

omNs);


OMElement value = fac.createOMElement("greeting", omNs);


value.addChild(fac.createOMText(value, "Hello,

"+personToGreet));


method.addChild(value);



return method;


}


private void ping(){


}

}

creative consultants


Make

sure

to

include

Axis
2

libraries

in

your

class

path

when

compiling

the

source
.



Axis
2

uses

AXIOM,

or

the

AXIs

Object

Model,

a

DOM

(Document

Object

Model)

-
like

structure

that

is

based

on

the

StAX

API

(

Streaming

API

for

XML)
.

Methods

that

act

as

services

must

take

an

OMElement

as

their

argument,

which

represents

the

payload

of

the

incoming

SOAP

message
.

(An

OMElement

is

just

AXIOM's

way

of

representing

an

XML

element,

like

a

DOM

Element

object
.
)

In

this

case,

you're

extracting

the

contents

of

the

first

child

of

the

payload

element,

adding

text

to

it,

and

using

it

as

content

for

the

return

OMElement
.

Unless

this

is

an

"in

only"

service,

these

methods

must

return

an

OMElement,

because

that

becomes

the

payload

of

the

return

SOAP

message
.



To

turn

this

class

into

a

service,

create

the

service

description

file,

services
.
xml,

as

in

Code

Listing

9
.


creative consultants

Code Listing 9
-

Create the Service Description



<service name="UserGuideSampleService">



<description>



This is a sample service created in the Axis2 User's Guide



</description>




<parameter name="ServiceClass"


>org.apache.axis2.axis2userguide.SampleService


</parameter>




<operation name="sayHello">



<messageReceiver


class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/>



</operation>



<operation name="ping">



<messageReceiver


class="org.apache.axis2.receivers.RawXMLINOnlyMessageReceiver"/>



</operation>


</service>

creative consultants




This
document defines the service, called by the

Web Administration Application
, and
the class used to serve requests. For each operation, it defines the appropriate
message receiver class.

Create a new directory, META
-
INF, in the main directory for the class. (In this case,
that's the same directory that contains the org directory) and place the services.xml
file in it.

Create the .aar file by typing: jar cvf SampleService.aar ./*

Deploy the SampleService.aar file by using the

Web Administration application

or by
copying it to the Axis2 services directory.

Now you can create a client class that accesses the service directly (see Code Listing
10).


creative consultants

Code Listing 10
-

Create a Client Class that
Accesses the Service Directly


package org.apache.axis2.axis2userguide;


import javax.xml.stream.XMLStreamException;

import org.apache.axiom.om.OMAbstractFactory;

import org.apache.axiom.om.OMElement;

import org.apache.axiom.om.OMFactory;

import org.apache.axiom.om.OMNamespace;

import org.apache.axis2.addressing.EndpointReference;

import org.apache.axis2.client.Options;

import org.apache.axis2.Constants;

import org.apache.axis2.client.ServiceClient;


public class SampleClient {



private static EndpointReference targetEPR =


new EndpointReference(


"http://localhost:8080/axis2/services/UserGuideSampleService");



public static OMElement greetUserPayload(String personToGreet) {


OMFactory fac = OMAbstractFactory.getOMFactory();


OMNamespace omNs = fac.createOMNamespace(


"http://example1.org/example1", "example1");


OMElement method = fac.createOMElement("sayHello", omNs);


OMElement value = fac.createOMElement("personToGreet",

omNs);


value.addChild(fac.createOMText(value, personToGreet));


method.addChild(value);


return method;


}


creative consultants


public static void main(String[] args) {


try {


OMElement payload =

SampleClient.greetUserPayload("John");


Options options = new Options();


options.setTo(targetEPR);

options.setTransportInProtocol(Constants.TRANSPORT_HTTP);


ServiceClient sender = new ServiceClient();


sender.setOptions(options);


OMElement result = sender.sendReceive(payload);


String response = result.getFirstElement().getText();


System.out.println(response);


} catch (Exception e) { //(XMLStreamException e) {


System.out.println(e.toString());


}


}

}


This class uses the same technique of sending and receiving OMElements, but it's also
important to note the use of the Options class. This class enables you to determine
properties such as the transport used for the return message (the transport used for the
outgoing message can be inferred from the URL of the destination) and the SOAP version to
use. In addition to providing setter and getter methods of specific properties that affect how
the client interacts with the service, the Options class enables you to create inheritance
relationships between Options objects. So if a property is not found in the current Options
object used, the client can check the parent Options object of the current Options object.


Compile and run the above SampleClient.java. Make sure to have all axis2 libraries in your
class path. If all has gone well, 'Hello, John' will be shown as the output in the console.



creative consultants

Deploying Plain Old Java Objects (POJOs)


One very easy way to create a Web service is simply to deploy the Java objects that
represent the service. Start
with
the class, shown in Code Listing 11
.

Code Listing 11
-

Creating the Class SampleService


package org.apache.axis2.axis2userguide;

public class SampleService {


public void doInOnly(){


return;


}


public String noParameters(){


return "Hello";


}


public String twoWayOneParameterEcho(String toEcho){


return toEcho;


}


public boolean multipleParametersAdd(float price, int itemId,


String description, String itemName){


//Code to handle the logic


return true;


}

}

creative consultants

Next, you'll need to tell Axis2 what class corresponds with what Web service calls. Do
this by creating a file called services.xml and adding
the
following shown in Code
Listing 12
.

Code Listing 12
-

Creating services.xml

<service name="SampleService" scope="application">


<description>


Sample Service


</description>


<messageReceivers>


<messageReceiver


mep="http://www.w3.org/2004/08/wsdl/in
-
only"


class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/>


<messageReceiver


mep="http://www.w3.org/2004/08/wsdl/in
-
out"


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


</messageReceivers>


<parameter name="ServiceClass">


org.apache.axis2.axis2userguide.SampleService


</parameter>

</service>


This file makes the InOnly and InOut MEPs available to the service and tells Axis2
which class to call; operations must match method names. In other words, Axis2
automatically sends a call to the multipleParametersAdd operation to the
org.apache.axis2.axis2userguide.SampleService.multipleParametersAdd() method.

creative consultants

Now it's time to create the distribution. Arrange your files in the following directory
structure (see
Code
Listing 13
).

Code Listing 13
-

Create the Directory Structure for the Distribution


-

SampleService


-

META
-
INF


-

services.xml


-

org


-

apache


-

axis2


-

axis2userguide


-

SampleService.class


Finally, deploy the service by copying the SampleService directory to the
webapps/axis2/WEB
-
INF/services directory on the servlet engine. You can check to
make sure that it's been properly deployed by checking
http://<host>:<port>/axis2/services/listServices.

creative consultants

Deploying and Running an Axis2 Service Created from
WSDL


If you have a WSDL file, you can easily create and deploy a service based on that
description. For example, to create a service based on the same WSDL file used in the
clients section of this document, you will follow the steps below.


The short story:

1.


Download the Axis2 standard distribution, if you have not done so already.

2.

Generate the skeleton using the WSDL2Java utility, as in:


java org.apache.axis2.wsdl.WSDL2Java
-
uri
file:///C:/apps/axis2/samples/zSample/Axis2UserGuide.wsdl
-
p org.a

pache.axis2.axis2userguide
-
d adb
-
s
-
wv 1.1
-
ss
-
sd
-
ssi


3.
Open the *Skeleton.java file and add the functionality of your service to the
generated methods.

4.
Build a service using Ant by typing ant jar.server

5.
Deploy the service by copying the build/lib/*.aar file to
<J2EE_HOME>/webapps/axis2/WEB
-
INF/services

6.
Check http://<server>:<port>/axis2/services/listServices to make sure the service
has been properly deployed.



creative consultants


The long story:


As with generating clients, you will need the

Axis2 Standard Distribution
, because
the

Axis2 WAR Distribution
does not include the WSDL2Java utility. Once you've got
it downloaded and unpacked, make sure that you set the AXIS2_HOME variable to
point to the location in which you've unpacked it.


Now you are ready to generate the actual service. To keep things neat, create a
new directory and change to it. The WSDL file is the same one referenced
in

Generating Clients

and includes four operations: NoParameters,
TwoWayOneParameterEcho, MultipleParametersAddItem, and DoInOnly. To
generate the service, use the WSDL2Java utility, as in Code Listing 14.


creative consultants

Code Listing 14
-

Using the WSDL2Java Utility to
Generate the Service



Code Listing 14.1
:


java org.apache.axis2.wsdl.WSDL2Java
-
uri


file:///C:/apps/axis2/samples/zSample/Axis2UserGuide.wsdl
-
p


org.apache.axis2.axis2userguide
-
d adb
-
s
-
wv 1.6.2
-
ss

sd





Note
:

Make

sure

all

the

.
jar

files

in

the

Axis
2

lib

directory

is

set

to

the

CLASSPATH

before

you

run

the

above

code
.

This

statement

tells

the

utility

you

want

to

create

a

service

out

of

the

operations

in

the

file
Axis
2
UserGuide
.
wsdl
,

and

that

the

Java

classes

generated

should

be

in

the

org
.
apache
.
axis
2
.
axis
2
userguide

package

(
-
p)
.

(You

can

view

the

appropriate

directories

created
.
)

It

also

indicates

that

you

want

to

use

the

Axis
2

DataBinding

Framework,

or

ADB

(
-
d),

to

generate

only

synchronous

or

blocking

code

(
-
s),

and

to

generate

server
-
side

code

(
-
ss)

as

opposed

to

a

client,

including

the

services
.
xml

service

descriptor

file

(
-
sd)
.

It

also

specifies

version

1
.
6
.
2

for

the

WSDL

file

(
-
wv)
.


creative consultants

Code Listing 14.2:

You can also use the following script files to achieve the same. In this case you do not have
the set the CLASSPATH manually.

For Linux:

$AXIS2_HOME/bin/wsdl2java.sh
-
uri
file:///C:/apps/axis2/samples/zSample/Axis2UserGuide.wsdl

-
p org.apache.axis2.axis2userguide
-
o target_directory_name
-
d adb
-
s
-
wv 1.6.2
-
ss

sd


For MS Windows
:

%AXIS2_HOME%
\
bin
\
wsdl2java.bat
-
uri
file:
\
\
\
C:
\
apps
\
axis2
\
samples
\
zSample
\
Axis2UserGuide.wsdl

-
p org.apache.axis2.axis2userguide
-
o target_directory_name
-
d adb
-
s
-
wv 1.6.2
-
ss

sd



In both instances, at this point, you should see four new items in your chosen directory:
the build.xml file, which includes instructions for Ant, the src directory, which includes
all the generated classes and stubs, the resources directory, which includes a
regenerated version of the WSDL, and the services.xml file, which ultimately controls
the service's behavior.


You can compile the service at this point, but it doesn't actually do anything yet. You
can solve that problem by opening the
src
\
org
\
apache
\
axis2
\
axis2userguide
\
Axis2UserGuideServiceSkeleton.java file and
either editing the code in bold
--

make sure you manage parameter numbers
--

or
replacing all the code with the following in Code Listing 15.


creative consultants

Code Listing 15
-

Compiling the Service



/**



* Axis2UserGuideServiceSkeleton.java



*



* This file was auto
-
generated from WSDL



* by the Apache Axis2 version: SNAPSHOT Oct 15, 2006 (11:23:18


GMT+00:00)



*/


package org.apache.axis2.axis2userguide;


/**



* Axis2UserGuideServiceSkeleton java skeleton for the axisService



*/


public class Axis2UserGuideServiceSkeleton {









/**



* Auto generated method signature






* @param param7






*/



public org.apache.axis2.axis2userguide.NoParametersResponse


NoParameters



(org.apache.axis2.axis2userguide.NoParametersRequest param7)






{



System.out.println(param7);




NoParametersResponse res =



new NoParametersResponse();




return res;



}










creative consultants


/**



* Auto generated method signature






* @param param9






*/



public


org.apache.axis2.axis2userguide.TwoWayOneParameterEchoResponse


TwoWayOneParameterEcho



(



org.apache.axis2.axis2userguide.TwoWayOneParameterEchoRequest


param9



)






{



System.out.println(param9.getEchoString());




TwoWayOneParameterEchoResponse res =



new TwoWayOneParameterEchoResponse();






res.setEchoString(param9.getEchoString());




return res;



}









/**



* Auto generated method signature






* @param param11






*/



public void DoInOnly



(



org.apache.axis2.axis2userguide.DoInOnlyRequest param11



)






{



System.out.println(param11.getMessageString());



}




creative consultants






/**



* Auto generated method signature






* @param param12






*/



public


org.apache.axis2.axis2userguide.MultipleParametersAddItemResponse


MultipleParametersAddItem



(





org.apache.axis2.axis2userguide.MultipleParametersAddItemRequest


param12



)






{



System.out.println(param12.getPrice());



System.out.println(param12.getItemId());



System.out.println(param12.getDescription());



System.out.println(param12.getItemName());




MultipleParametersAddItemResponse res =



new MultipleParametersAddItemResponse();






res.setSuccessfulAdd(true);



res.setItemId(param12.getItemId());




return res;



}





}


creative consultants

As with generating clients, all these classes, such as
MultipleParametersAddItemRequest and TwoWayOneParameterEchoResponse, are
generated by the utility, and can be found in the same directory as the skeleton file.
They include methods such as setSuccessfulAdd(), which sets the value of the content
of an element in the response, and getItemName(), which retrieves the content of
elements in the request.

Save the file and compile it by typing: ant
jar.server

If all goes well, you should see the BUILD SUCCESSFUL message in your window, and
the Axis2UserGuideService.aar file in the newly created build/lib directory.


creative consultants


Now you need to deploy the service to the server. To do that, copy the
Axis2UserGuideService.aar file to the WEB
-
INF/services directory of the
application server. (You also have the option to use the administration tools. See
the

Web Administrator's Guide

for more information.)


To verify that the service has been properly deployed, check the list of services at
http://<host>:<port>/axis2/services/listServices.


creative consultants

Now you should be able to access the service using any of the clients built in the

Generating
Clients

document.

Ch.6 Samples


Clients


Services


Sample WSDL files


Other Samples

creative consultants

Clients(inAXIS2_HOME/samples/userguide/src/clients)


EchoBlockingClient.java
: A basic example of the send/receive MEP.


EchoBlockingDualClient.java
: Specifies that the return message should be sent
over a different channel than the request message.


EchoBlockingWsaBasedClient.java
: Provides an example of using the capabilities
of WS
-
Addressing action mapping.


EchoNonBlockingClient.java
: Demonstrates an asynchronous request using
Callbacks.


EchoNonBlockingDualClient.java
: Similar to the above, but uses a separate listener
for the response.


ClientForWebServiceWithModule.java
: Simply makes a call to a service with
engaged modules.


ClientSideModuleEngagement.java
: Demonstrates the use of modules on the
client side, in addition to the server side.


MailClient.java
: Demonstrates the use of the Robust In
-
Only MEP.


PingClient.java
: A simple "fire and forget" client.


RESTClient.java
: Demonstrates the ability to request a REST response rather than a
SOAP response. Also demonstrates setting arbitrary properties on the Options
object.


TCPClient.java
: Provides an example of using the TCP transport rather than HTTP.


creative consultants

Services (in AXIS2_HOME/samples/userguide)



groovyService.aar
: Demonstrates how to use Groovy classes in the processing of
SOAP messages.


MyService.aar
: Provides simple "echo" and "ping" operations.


MyServiceWithModule.aar
: Same as above, but demonstrates how to engage a
module.


WsaMappingService.aar
: Demonstrates the mapping of WS
-
Addressing actions.


creative consultants

Sample WSDL files (in AXIS2_HOME/samples):



Axis2SampleDocLit.wsdl
: Demonstrates the use of the Document/Literal WSDL
pattern, rather than RPC.


perf.wsdl
: Demonstrates the use of array values as input values.


creative consultants

Other samples


In AXIS2_HOME/samples Directory:

faulthandling
: Demonstrates the use of SOAP faults and their definitions in
WSDL enabling exception processing in the client.

googleSpellcheck
: Demonstrates both synchronous and non
-
synchronous use
of the Google Web Service in a GUI.

mtom
: Demonstrates the use of MTOM and SOAP with Attachments to send
binary files to a service.

saopwithattachments
: Demonstrates the capabilities and power of SOAP
with Attachment support and the Attachment API of Axis2.

pojo
: Example of a POJO (Plain Old Java Object) Web service. It shows how to
expose the methods of a Java class as a Web service using Apache Aixs2.

servicelifecycle
: Demonstrates the usage of a service life cycle and a bit of
session management. The main idea is to show where and how to use the
service life cycle interface and session related methods.

databinding
: Demonstrates how to use WSDL2Java generated code with
Castor.

version
: A very simple service that simply outputs the Apache Axis2 version.

yahoorestearch
: A complete example of the use of a REST service rather than
a SOAP service.


creative consultants

External:



FlickrClient

: Demonstrates code generation capabilities for WSDL 2.0. The
FlickrService.wsdl describes services offered by flickr in terms of WSDL 2.0. It
also demonstrates how a restful service can be described using the
HTTPBinding of wsdl 2.0.


Extract the

WSO2 WSAS for Java nightly build distribution

and you will find the
sample at WSAS_HOME/samples/FlickrClient or checkout sample from SVN:
http://wso2.org/repos/wso2/trunk/wsas/java/modules/samples/FlickrClient


creative consultants