L05 - Esercitazione
Sviluppare SOAP Web
Services con Axis2
1
Software e librerie



Axis2
ANT
NetBeansIDE
2
Variabili di sistema 1/2
AXIS2_HOME
C:\servizi\axis2-1.5.1
ANT_HOME
C:\servizi\apache-ant-1.8.0
3
Variabili di sistema
JAVA_HOME
C:\Programmi\Java\jdk1.6.0_16
PATH
%JAVA_HOME%/bin
4
Software e librerie

Axis2

System Requirements





Java Development Kit (JDK) 1.5 o versioni successive
(http://java.sun.com)
Introduzione: http://ws.apache.org/axis2/1_5/contents.html
Axis 2 va installato nella modalità standalone.
Scaricare la Standard binary distribution
http://ws.apache.org/axis2/download/1_5_1/download.cgi
Istruzioni per istallazione:
http://ws.apache.org/axis2/1_5_1/contents.html


(ovvero i paragrafi) 1. Download and Install the Apache Axis2
Binary Distribution 2. Starting up Axis2 Standalone Server
IMPORTANTE: settare la variabile AXIS2_HOME con il valore della
directory AXIS2 (Eg: /opt/axis2-1.4)
5
Software e librerie

Ant 1.8




Download http://ant.apache.org/bindownload.cgi
istruzioni per istallazione:
http://ant.apache.org/manual/install.html#installing
Sintesi istruzioni per istallazione: estrarre lo zip e
settare la variabile ANT_HOME alla directory di
istallazione di Ant e settare
PATH=%ANT_HOME%\bin
NetBeans 6.1 o successive

Download
http://download.netbeans.org/netbeans/6.1/final/
(scaricare la versione Web & Java EE
6
Axis2
7
AXIS2



Axis (Apache eXtensible Interaction System) è
un'implementazione del protocollo SOAP definito
da W3C.
AXIS è essenzialmente un motore SOAP in grado
di processare messaggi SOAP e permette di
sviluppare client, server e gateway SOAP.
In realtà AXIS non è propriamente un semplice
engine SOAP,ma piuttosto un framework per
realizzare sistemi di integrazione basati su SOAP.
8
AXIS2 - caratteristiche
Le caratteristiche più importanti del framework sono:

Supporto parziale delle specifiche SOAP 1.2

Supporto per la pubblicazione automatica dei servizi(Java
Web Service)

Supporto serializzazione/de-serializzazione

Generazione automatica del documento WSDL per un
servizio pubblicato

Tool WSDL2Java e Java2WSDL

Soap Monitor e TCP Monitor

Diversi metodi per l'invocazione dei WS: Dynamic
Invocation Interface, Stub generato
dal WSDL e Dynamic Proxy
9
AXIS2 - Introduzione


The Apache Axis2 project is a Java-based implementation of both
the client and server sides of Web services. 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 recommedations
Axis2 enables you to 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,
WSReliableMessaging, WS-Addressing, WS-Coordination, and WSAtomic Transaction recommendations
Use Axis2's modular structure to easily add support for new
recommendations as they emerge
10
AXIS2 – Client e Server Side
User
Application
Client
API
Transport
Sender
Handlers
(interceptors)
Message
Receiver
Transport
Listener
SOAP
Web
Service
Business
Logic
Handlers
(interceptors)
11
AXIS2 – Client e Server Side

Axis2 can handle processing for both the sender
and the receiver in a transaction.






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 "predispatch" phase, it is handed off to the dispatchers,
which pass it on to the appropriate application.
12
AXIS2 – Client e Server Side

In Axis2, these actions are broken down into "phases",
with several pre-defined phases, such as the "predispatch", "dispatch," and "message processing", being
built into Axis2. Each phase is a collection of "handlers".
Axis2 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 Axis2 system. These modules are the main
extensibility mechanisms in Axis2 (e.g. WS-Security,
WS-ReliableMessaging)
13
AXIS2 Architecture (Server Side)
14
AXIS2 Architecture

The Axis2 architecture separates logic and state; this allows the
logic to execute in parallel threads. The Axis2 architecture is
implemented using seven independent modules:
1. Information model: This module manages the state of the SOAP
engine. The Information model has two types of classes for holding the
state. The Description classes hold data that is static in nature and
exists throughout the life of the Axis engine instance, such as
configuration of transports, services, and operations. Context classes
hold dynamic information of the service and operation that are valid on
the context of an invocation, such as the current request and response
SOAP message, From address, To address, and other elements.
2. XML processing model: Axis2 introduces a new model called AXIOM
for processing SOAP messages. AXIOM uses StAX (Streaming API for
XML) to parse the XML. StAX is a standard streaming pull parser
Java™ API. AXIOM is very lightweight
15
AXIS2 Architecture
3.
SOAP processing model: Axis2 architecture defines two pipes (or Flows)
called InPipe (InFlow) and OutPipe (OutFlow) for handling request
messages and response messages on the server side. On the client side,
the pipes are inverted -- in other words, the SOAP request message flows
through the OutPipe and the response message flows through the InPipe. A
pipe or flow contains a series of handlers grouped into phases. The phases
are executed in a predefined order. In addition to the set of predefined
phases and handlers, users can configure user phases and associated
handlers at the operation, service, or global level. Handlers act as
interceptors of the SOAP message and can process the header or body of
the SOAP message.
Passing through all the phases configured in the Inpipe, the request
message reaches the MessageReceiver, which then invokes the actual
service implementation.
When a fault occurs during the execution of these pipes, the faults goes
through InFaultPipe or OutFaultPipe pipes. InFaultPipe is invoked on the
client side when the Fault message is received; the OutFaultPipe is invoked
on the server side when an invocation causes a fault to be sent to the client.
16
AXIS2 Architecture
4.
Deployment module: This module configures the Axis engine and deploys the
services and modules. axis2.xml (found in webapps/axis2/WEB-INF) contains
the global configuration of the Axis2 engine, including: Global modules, Global
receivers, Transports, User phase definitions. Configuration of each service is
contained in a services.xml file in the service archive.
5.
WSDL and code generation: This module takes care of generating client stub
and server skeleton code from the WSDL file. The Axis2 code generator emits
XML files that are applied with the correct XML style sheets to generate code in
the needed language.
6.
Client API: The Axis2 client API invokes operations following In-Only and In-Out
message patterns defined by WSDL 2.0. The client API supports both blocking
and non-blocking invocation of In-Out operations.
7.
Transports: This module contains handlers that interact with the transport layer.
There are two types of transport handlers, TransportListener and
TransportSender. The TransportListener receives the SOAP message from the
transport layer and passes it to the InPipe for processing. A TransportSender
sends the SOAP message received from the OutPipe over the specified
transport. Axis2 provides handlers for HTTP, SMTP, and TCP. For HTTP
transport, the AxisServlet on the server side and a simple standalone HTTP 17
server (provided by Axis2) on the client side work as the TransportReceiver
Avviare AXIS2

Da riga di comando
%AXIS2_HOME%\bin\axis2server.bat

Aprire il browser e digitare
http://localhost:8080/axis2/services/
18
Ex. 0 Creare un web service
semplice
19
Creazione di un web service
passo dopo passo

Classe Java
package sample.soapservice;
public class MathOperationClass {
public int somma (int a, int b) {
return a+b;
}
}

Struttura in cartelle
_ addOperation
_ resources
_ META-INF
_service.xml
_ src
_sample
_soapservice
_ MathOperationClass.java
-
20
File service.xml
<service name="AddOperationService"
targetNamespace="http://addOperation.samples/">
<description>
Math Operation Service
</description>
<messageReceivers>
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out"
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</messageReceivers>
<schema schemaNamespace="http://addOperation.samples/xsd"/>
<parameter name="ServiceClass">sample.soapservice.MathOperationClass
</parameter>
</service>
21
Comandi

Compilo la classe MathOperationClass e copio il
file .class nella directory resources


Mi posiziono dentro la cartella resources e creo
l’archivio Axis


javac
src/sample/soapservice/MathOperationClass.java
–d resources
jar –cvf AddOperationService.aar *
Copio l’archivio AddOperationService.aar in
AXIS_HOME/repository/services
22
Verifica e test

Controllare sul browser
http://localhost:8080/axis2/services/listService

Vedere il WSDL


http://localhost:8080/axis2/services/AddOper
ationService?wsdl
Invocare l’ operazione somma

http://localhost:8080/axis2/services/MathOper
ationService/somma?args0=2&args1=5
23
Ex. 1 Realizzare il primo WS
24
Ex1:Realizzare un Web Service

cd %AXIS2_HOME%\samples\quickstart

StockQuoteService.java
package samples.quickstart.service.pojo;
import java.util.HashMap;
public class StockQuoteService {
private HashMap map = new HashMap();
public double getPrice(String symbol) {
Double price = (Double) map.get(symbol);
if(price != null){
return price.doubleValue();
}
return 42.00;
}
public void update(String symbol, double price) {
25
Ex1: esempio

Struttura della directory in
<AXIS2_HOME>/samples/quickstart
- quickstart
- README.txt
- build.xml
- resources
- META-INF
- services.xml
- src
- samples
- quickstart
- service
- pojo
- StockQuoteService.java
26
Ex1:Service Definition

Service.xml
service name="StockQuoteService" scope="application"
targetNamespace="http://quickstart.samples/">
<description>
Stock Quote 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>
<schema schemaNamespace="http://quickstart.samples/xsd"/>
<parameter name="ServiceClass">
samples.quickstart.service.pojo.StockQuoteService
</parameter>
27
</service>


Ex1: creare il servizio
Da riga di comando posizionati nella nella director
quickstart
%ANT_HOME%\bin\ant generate.service
Copiare StockQuoteService.aar in
AXIS2_HOME/repository/services
28
Ex1: testare il servizio – 1/3

Controllare sul browser
http://localhost:8080/axis2/services/listService

Invocare le operazioni getPrice e update

http://localhost:8080/axis2/services/StockQuoteServi
ce/getPrice?symbol=IBM

http://localhost:8080/axis2/services/StockQuoteServi
ce/update?symbol=IBM&price=100

Ripetere getPrice
29
Ex1: testare il servizio – 2/3
Invocare le operazioni inviando un Messaggio SOAP di richiesta (es. con TCPMon)
- getPrice
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<ns:getPrice xmlns:ns="http://quickstart.samples/xsd">
<ns:symbol>IBM</ns:symbol>
</ns:getPrice>
</soapenv:Body>
</soapenv:Envelope>
- update
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<ns:update xmlns:ns="http://quickstart.samples/xsd">
<ns:symbol>IBM</ns:symbol>
<ns:price>400</ns:price>
</ns:update>
</soapenv:Body>
</soapenv:Envelope>
30
Ex1: testare il servizio – 3/2
31
Ex1: struttura dell’archivio Axis
Struttura di StockQuoteService.aar

META-INF



services.xml
lib
samples
 quickstart
 service
 pojo
- StockQuoteService.class
32
Services.xml
33
Esempio
<service name="name of the service" scope="name of the scope" class="full qualifide
name the service lifecycle class" targetNamespace="target namespase for the
service">
<description> The description of the service </description>
<transports> <transport>HTTP</transport> </transports>
<schema schemaNamespace="schema namespace"/>
<messageReceivers> <messageReceiver
mep="http://www.w3.org/2004/08/wsdl/in-out"
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</messageReceivers>
<parameter name="ServiceClass"
locked="xsd:false">org.apache.axis2.sample.echo.EchoImpl</parameter>
<operation name="echoString" mep="operation MEP"> <actionMapping>Mapping
to action</actionMapping> <module ref=" a module name "/>
<messageReceiver
class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/>
</operation>
</service>
34
Services.xml 1/2

name: The service name will be the name of the archive file if the .aar
file contains only one service, or else the name of the service will be the
name given by the name attribute

scope: (Optional Attribute) The time period during which runtime
information of the deployed services will be available. Scope is of several
types- "Application", "SOAPSession", "TransportSession", "Request". The
default value (if you don't enter any value) will be "Request“

class: (Optional attribute) The full qualified name of the service lifecycle
implementation class. ServiceLifeCycle class is useful when you want to do
some tasks when the system starts and when it shuts down

targetNamespace: (Optional Attribute) Target name space of the service.
This value will be used when generating the WSDL. If you do not specify
this value, the value will be calculated from the package name of the
service impl class
35
Services.xml 2/2

description: (Optional) If you want to display any description about the
service via Axis2 web-admin module, then the description can be specified
here

transports : (Optional) The transports to which the service is going to
be exposed. If the transport element is not present, then the service will be
exposed in all the transports available in the system

parameters: A services.xml can have any number of top level parameters
and all the specified parameters will be transformed into service properties
in the corresponding AxisService. There is a compulsory parameter in
services.xml called ServiceClass that specifies the Java class, which
performs the above transformation. This class is loaded by the
MessageReceiver

operations : If the service impl class is Java, then all the public
methods in that service will be exposed. If the user wants to override
it, he has to add the "operation" tag and override it. In a non-Java
scenario or if you do not have a service class, then all the operations the
user wants to expose by the service has to be indicated in the services.xml
36
Services.xml: messageReceiver

MessageReceiver

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.
37
Ex. 1.b



Copiare la directory Quickstart e
rinominarla (es. quickstartGet)
Modificare services.xml per esporre solo il
metodo Get (vedi slide successive)
Testare il servizio
38
Build.xml
In blu modifiche da fare
<project name="quickstartGet" basedir="."
default="generate.service">
…….
<jar
destfile="${build.dir}/StockQuoteServiceG
et.aar">
39
Modificare service.xml
<service name="StockQuoteServiceGet" scope="application"
targetNamespace="http://quickstart.samples/">
<description>
Stock Quote Service
</description>
<operation name="getPrice">
<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>
<schema schemaNamespace="http://quickstart.samples/xsd"/>
<parameter
name="ServiceClass">samples.quickstart.service.pojo.StockQuoteService<
/parameter>
40
</operation>
</service>
TcpMon
41
Esempio configurazione TCPMon
42
TCPMon: Ex2.a



MathOperationService
Usare TCPMon per monitorare richieste e
risposte
http://localhost:1234/axis2/services/MathO
perationService/somma?a=2&b=5
43
TCPMon: 2.b

Usare TCPMON come sender di
messaggi SOAP
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<ns:somma xmlns:ns="http://addOperation.samples/xsd">
<ns:a>17</ns:a>
<ns:b>3</ns:b>
</ns:somma>
</soapenv:Body>
</soapenv:Envelope>
44
Ex. 2 Sviluppare un WS partendo
da una classe Java
45
MathOperationClass.java
package sample.soapservice;
public class MathOperationClass {
public int somma (int a, int b) {
return a+b;
}
public int moltiplicazione (int a, int b) {
return a*b;
}
public int sottrazione (int a, int b) {
return a-b;
}
public int divisione (int a, int b) {
return a/b;
}
}
46
Ex. 2 Passi




Aggiornare services.xml
Aggiornare build.xml
Creare il servizio
Testare le operazioni
47

http://localhost:8080/axis2/services/MathO
perationService/somma?a=2&b=5
48
Ex. 3 Creare un servizio Web e
programma Client
49
Ex.3: Passi

Classi di partenza



Costruire la directory



Services.xml
Build.xml
Da riga di comando




AddressService.java
Address.java
ant generate.service
ant rpc.client
ant rpc.client.run (per ripetere le chiamate del client
Usare NetBeans

New Project

Java Project with existing Ant Scripts
50
Ex.3: Client Code
package sample.pojo.rpcclient;
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;
import sample.pojo.data.Address;
public class AddressRPCClient {
public static void main(String[] args1)throws AxisFault {
//creo istanza del client
RPCServiceClient serviceClient = new RPCServiceClient();
// assegno l'indirizzo del service
Options options = serviceClient.getOptions();
EndpointReference targetEPR = new
EndpointReference("http://localhost:8080/axis2/services/AddressService");
// oppure http://localhost:1234/axis2/services/AddressService per usare TCPMon
options.setTo(targetEPR);
51
Ex.3: Client code
// Setting the address
QName opSetAddress = new QName("http://service.pojo.sample", "setAddress");
Address a = new Address();
a.setCity("Firenze");
a.setIsHome(false);
a.setNumber(3);
a.setStreet("via Santa Marta");
a.setPostalcode(50100);
Object[] opSetAddressArgs = new Object[] { a};
serviceClient.invokeRobust(opSetAddress, opSetAddressArgs);
52
Ex.3: Client code
// Getting the weather
QName opGetAddress = new QName("http://service.pojo.sample", "getAddress");
Object[] opGetAddressArgs = new Object[] { };
Class[] returnTypes = new Class[] { Address.class };
Object[] response = serviceClient.invokeBlocking(opGetAddress,
opGetAddressArgs,returnTypes );
Address result = (Address) response[0];
if (result == null) {
System.out.println("Address didn't initialize!");
return;
}
53
Ex.3: Client code
// Displaying the result
System.out.println("via
: " + result.getStreet());
System.out.println("numero
: " + result.getNumber());
System.out.println("Città
: " + result.getCity());
System.out.println("codice postale : " + result.getPostalcode());
System.out.println("abitazione : " + result.getIsHome());
54
TcpMon
55
Esempio configurazione TCPMon
56
TCPMon: Ex2.a



MathOperationService
Usare TCPMon per monitorare richieste e
risposte
http://localhost:1234/axis2/services/MathO
perationService/somma?a=2&b=5
57
TCPMon: 2.b

Usare TCPMON come sender di
messaggi SOAP
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<ns:somma xmlns:ns="http://addOperation.samples/xsd">
<ns:a>17</ns:a>
<ns:b>3</ns:b>
</ns:somma>
</soapenv:Body>
</soapenv:Envelope>
58
Ex 4: WSDL
59
Ex.4: Creare lo stub

%AXIS2_HOME%\bin\wsdl2java –uri
http://localhost:8080/axis2/services/MathOperationService?
wsdl –p it.px.client –d adb –s
-p imposta il package

-s solo codice per chiamate sincrone

-o directory di output
http://localhost:8080/axis2/services/MathOperationService?wsdl


Il comando precedente genera una classe “stub” che
rappresenta il proxy verso il Web Service


A proxy is a local object with the same interface of the actual web
service; it allows you to call the web service as if it were a local
object
Per invocare il servizio
60
Ex.4: Invocare lo stub
MathOperationServiceStub stub = new
MathOperationServiceStub();
MathOperationServiceStub.Somma params= new
MathOperationServiceStub.Somma();
params.setA(5);
params.setB(6);
try{
MathOperationServiceStub.SommaResponse response =
stub.somma(params);
61
Ex.4: codice completo
package it.px.client;
import org.apache.axis2.AxisFault;
public class MathOperationClient {
public static void main(String[] args1) throws AxisFault{
MathOperationServiceStub stub = new MathOperationServiceStub();
MathOperationServiceStub.Somma params= new
MathOperationServiceStub.Somma();
params.setA(new Integer(args1[0]).intValue());
params.setB(new Integer(args1[1]).intValue());
try{
MathOperationServiceStub.SommaResponse response = stub.somma(params);
System.out.println("Result is: " + response.get_return());
}
catch (java.rmi.RemoteException ne)
{
System.out.println("eccezione " + ne.toString());
}
}
}
62
Ex.4: eseguire il client


Creo un nuovo progetto su Netbeans
New Project / Java Project with Existing sources


Project folder: C:\servizi\axis21.5.1\samples\mathOperationClient
Da Properties, Libraries



Add library AXIS2
Oppure Add Jar e selezionare tutti i jar dentro
AXIS2_HOME\lib
Sul nodo Project selezionare Run


In Properties, Run, inserire gli argomenti
Es. Arguments: "5" "10"
63
Ex 5: invocare servizi web esterni

http://www.xmethods.com



Creare lo stub
Creare il client
Invocare il servizio remoto
64
Fine
65
Scarica

service