L05 esercitazione
1 / 65

L05 - Esercitazione - PowerPoint PPT Presentation

  • Uploaded on

L05 - Esercitazione. Sviluppare SOAP Web Services con Axis2. Software e librerie. Axis2 ANT NetBeansIDE. Variabili di sistema 1/2. AXIS2_HOME C:\servizi\axis2-1.5.1 ANT_HOME C:\servizi\apache-ant-1.8.0. Variabili di sistema. JAVA_HOME C:\Programmi\Java\jdk1.6.0_16 PATH

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 ' L05 - Esercitazione' - holli

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
L05 esercitazione

L05 - Esercitazione

Sviluppare SOAP Web Services con Axis2

Software e librerie
Software e librerie

  • Axis2

  • ANT

  • NetBeansIDE

Variabili di sistema 1 2
Variabili di sistema 1/2





Variabili di sistema
Variabili di sistema





Software e librerie1
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)

Software e librerie2
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


  • 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.

Axis2 caratteristiche
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

Axis2 introduzione
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 WS-Atomic Transaction recommendations

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

Axis2 client e server side
AXIS2 – Client e Server Side



Web Service Business Logic










Handlers (interceptors)

Handlers (interceptors)

Axis2 client e server side1
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 "pre-dispatch" phase, it is handed off to the dispatchers, which pass it on to the appropriate application.

Axis2 client e server side2
AXIS2 – Client e Server Side

  • In Axis2, these actions are broken down into "phases", with several pre-defined phases, such as the "pre-dispatch", "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)

Axis2 architecture
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:

    • 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.

    • 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

Axis2 architecture1
AXIS2 Architecture

  • 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.

Axis2 architecture2
AXIS2 Architecture

  • 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.

  • 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.

  • 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.

  • 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 server (provided by Axis2) on the client side work as the TransportReceiver

Avviare axis2
Avviare AXIS2

  • Da riga di comando


  • Aprire il browser e digitare


Creazione di un web service passo dopo passo
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


    _ src



    _ MathOperationClass.java

File service xml
File service.xml

<service name="AddOperationService" targetNamespace="http://addOperation.samples/">


Math Operation Service



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



<schema schemaNamespace="http://addOperation.samples/xsd"/>

<parameter name="ServiceClass">sample.soapservice.MathOperationClass




  • Compilo la classe MathOperationClass e copio il file .class nella directory resources

    • javac src/sample/soapservice/MathOperationClass.java –d resources

  • Mi posiziono dentro la cartella resources e creo l’archivio Axis

    • jar –cvf AddOperationService.aar *

  • Copio l’archivio AddOperationService.aar in AXIS_HOME/repository/services

Verifica e test
Verifica e test

  • Controllare sul browser


  • Vedere il WSDL

    • http://localhost:8080/axis2/services/AddOperationService?wsdl

  • Invocare l’ operazione somma

    • http://localhost:8080/axis2/services/MathOperationService/somma?args0=2&args1=5

Ex1 realizzare un web service
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) {

    map.put(symbol, new Double(price));



Ex1 esempio
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

Ex1 service definition
Ex1:Service Definition

  • Service.xml

service name="StockQuoteService" scope="application" targetNamespace="http://quickstart.samples/">


Stock Quote Service



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


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



<schema schemaNamespace="http://quickstart.samples/xsd"/>

<parameter name="ServiceClass">




Ex1 creare il servizio
Ex1: creare il servizio

  • Da riga di comando posizionati nella nella directory quickstart

    %ANT_HOME%\bin\ant generate.service

  • Copiare StockQuoteService.aar in AXIS2_HOME/repository/services

Ex1 testare il servizio 1 3
Ex1: testare il servizio – 1/3

  • Controllare sul browser


  • Invocare le operazioni getPrice e update

    • http://localhost:8080/axis2/services/StockQuoteService/getPrice?symbol=IBM

    • http://localhost:8080/axis2/services/StockQuoteService/update?symbol=IBM&price=100

    • Ripetere getPrice

Ex1 testare il servizio 2 3
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/">


<ns:getPrice xmlns:ns="http://quickstart.samples/xsd">





- update

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">


<ns:update xmlns:ns="http://quickstart.samples/xsd">






Ex1 struttura dell archivio axis
Ex1: struttura dell’archivio Axis

Struttura di StockQuoteService.aar


    • services.xml

  • lib

  • samples

    • quickstart

      • service

        • pojo

          - StockQuoteService.class


<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"/>


<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"/>



Services xml 1 2
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

Services xml 2 2
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

Services xml messagereceiver
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.

Ex 1 b
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

Build xml

In blu modifiche da fare

<project name="quickstartGet" basedir="." default="generate.service">


<jar destfile="${build.dir}/StockQuoteServiceGet.aar">

Modificare service xml
Modificare service.xml

<service name="StockQuoteServiceGet" scope="application" targetNamespace="http://quickstart.samples/">


Stock Quote Service


<operation name="getPrice">


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


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



<schema schemaNamespace="http://quickstart.samples/xsd"/>

<parameter name="ServiceClass">samples.quickstart.service.pojo.StockQuoteService</parameter>



Tcpmon ex2 a
TCPMon: Ex2.a

  • MathOperationService

  • Usare TCPMon per monitorare richieste e risposte

  • http://localhost:1234/axis2/services/MathOperationService/somma?a=2&b=5

Tcpmon 2 b
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>

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;



Ex 2 passi
Ex. 2 Passi

  • Aggiornare services.xml

  • Aggiornare build.xml

  • Creare il servizio

  • Testare le operazioni

Ex 3 creare un servizio web e programma client

Ex. 3 Creare un servizio Web e programma Client http://localhost:8080/axis2/services/MathOperationService/somma?a=2&b=5

Ex 3 passi
Ex.3: Passihttp://localhost:8080/axis2/services/MathOperationService/somma?a=2&b=5

  • Classi di partenza

    • AddressService.java

    • Address.java

  • Costruire la directory

    • Services.xml

    • Build.xml

  • Da riga di comando

    • 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

Ex 3 client code
Ex.3: Client Codehttp://localhost:8080/axis2/services/MathOperationService/somma?a=2&b=5

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


Ex 3 client code1
Ex.3: Client codehttp://localhost:8080/axis2/services/MathOperationService/somma?a=2&b=5

// Setting the address

QName opSetAddress = new QName("http://service.pojo.sample", "setAddress");

Address a = new Address();




a.setStreet("via Santa Marta");


Object[] opSetAddressArgs = new Object[] { a};

serviceClient.invokeRobust(opSetAddress, opSetAddressArgs);

Ex 3 client code2
Ex.3: Client codehttp://localhost:8080/axis2/services/MathOperationService/somma?a=2&b=5

// 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!");



Ex 3 client code3
Ex.3: Client codehttp://localhost:8080/axis2/services/MathOperationService/somma?a=2&b=5

// 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());



Esempio configurazione tcpmon1
Esempio configurazione TCPMonhttp://localhost:8080/axis2/services/MathOperationService/somma?a=2&b=5

Tcpmon ex2 a1
TCPMon: Ex2.ahttp://localhost:8080/axis2/services/MathOperationService/somma?a=2&b=5

  • MathOperationService

  • Usare TCPMon per monitorare richieste e risposte

  • http://localhost:1234/axis2/services/MathOperationService/somma?a=2&b=5

Tcpmon 2 b1
TCPMon: 2.bhttp://localhost:8080/axis2/services/MathOperationService/somma?a=2&b=5

  • 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>

Ex 4 wsdl

Ex 4: WSDLhttp://localhost:8080/axis2/services/MathOperationService/somma?a=2&b=5

Ex 4 creare lo stub
Ex.4: Creare lo stubhttp://localhost:8080/axis2/services/MathOperationService/somma?a=2&b=5

  • %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


  • 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

Ex 4 invocare lo stub
Ex.4: Invocare lo stubhttp://localhost:8080/axis2/services/MathOperationService/somma?a=2&b=5

MathOperationServiceStub stub = new MathOperationServiceStub();

MathOperationServiceStub.Somma params= new MathOperationServiceStub.Somma();




MathOperationServiceStub.SommaResponse response = stub.somma(params);

Ex 4 codice completo
Ex.4: codice completohttp://localhost:8080/axis2/services/MathOperationService/somma?a=2&b=5

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());



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());




Ex 4 eseguire il client
Ex.4: eseguire il clienthttp://localhost:8080/axis2/services/MathOperationService/somma?a=2&b=5

  • Creo un nuovo progetto su Netbeans

  • New Project / Java Project with Existing sources

    • Project folder: C:\servizi\axis2-1.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"

Ex 5 invocare servizi web esterni
Ex 5: invocare servizi web esternihttp://localhost:8080/axis2/services/MathOperationService/somma?a=2&b=5

  • http://www.xmethods.com

    • Creare lo stub

    • Creare il client

    • Invocare il servizio remoto