Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 L05 - Esercitazione Sviluppare SOAP Web Services con Axis2.

Similar presentations

Presentation on theme: "1 L05 - Esercitazione Sviluppare SOAP Web Services con Axis2."— Presentation transcript:

1 1 L05 - Esercitazione Sviluppare SOAP Web Services con Axis2

2 2 Software e librerie Axis2 ANT NetBeansIDE

3 3 Variabili di sistema 1/2 AXIS2_HOME C:\servizi\axis ANT_HOME C:\servizi\apache-ant-1.8.0

4 4 Variabili di sistema JAVA_HOME C:\Programmi\Java\jdk1.6.0_16 PATH %JAVA_HOME%/bin

5 5 Software e librerie Axis2 System Requirements Java Development Kit (JDK) 1.5 o versioni successive ( Introduzione: Axis 2 va installato nella modalità standalone. Scaricare la Standard binary distribution Istruzioni per istallazione: (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)

6 6 Software e librerie Ant 1.8 Download istruzioni per istallazione: 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 (scaricare la versione Web & Java EE

7 7 Axis2

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

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

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

11 11 AXIS2 – Client e Server Side User Application Client API Transport Sender Transport Listener Message Receiver Web Service Business Logic SOAP Handlers (interceptors)

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

13 13 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)

14 14 AXIS2 Architecture (Server Side)

15 15 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 lightweightStAX

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

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

18 18 Avviare AXIS2 Da riga di comando %AXIS2_HOME%\bin\axis2server.bat Aprire il browser e digitare

19 19 Ex. 0 Creare un web service semplice

20 20 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 _ -

21 21 File service.xml Math Operation Service sample.soapservice.MathOperationClass

22 22 Comandi Compilo la classe MathOperationClass e copio il file.class nella directory resources javac src/sample/soapservice/ –d resources Mi posiziono dentro la cartella resources e creo larchivio Axis jar –cvf AddOperationService.aar * Copio larchivio AddOperationService.aar in AXIS_HOME/repository/services

23 23 Verifica e test Controllare sul browser Vedere il WSDL ationService?wsdl Invocare l operazione somma ationService/somma?args0=2&args1=5

24 24 Ex. 1 Realizzare il primo WS

25 25 Ex1:Realizzare un Web Service cd %AXIS2_HOME%\samples\quickstart 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)); }

26 26 Ex1: esempio Struttura della directory in /samples/quickstart - quickstart - README.txt - build.xml - resources - META-INF - services.xml - src - samples - quickstart - service - pojo -

27 27 Ex1:Service Definition Service.xml service name="StockQuoteService" scope="application" targetNamespace="http://quickstart.samples/"> Stock Quote Service samples.quickstart.service.pojo.StockQuoteService

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

29 29 Ex1: testare il servizio – 1/3 Controllare sul browser Invocare le operazioni getPrice e update ce/getPrice?symbol=IBM ce/getPrice?symbol=IBM ce/update?symbol=IBM&price=100 Ripetere getPrice

30 30 Ex1: testare il servizio – 2/3 Invocare le operazioni inviando un Messaggio SOAP di richiesta (es. con TCPMon) - getPrice IBM - update IBM 400

31 31 Ex1: testare il servizio – 3/2

32 32 Ex1: struttura dellarchivio Axis Struttura di StockQuoteService.aar META-INF services.xml lib samples quickstart service pojo - StockQuoteService.class

33 33 Services.xml

34 34 Esempio The description of the service HTTP org.apache.axis2.sample.echo.EchoImpl Mapping to action

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

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

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

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

39 39 Build.xml In blu modifiche da fare …….

40 40 Modificare service.xml Stock Quote Service samples.quickstart.service.pojo.StockQuoteService

41 41 TcpMon

42 42 Esempio configurazione TCPMon

43 43 TCPMon: Ex2.a MathOperationService Usare TCPMon per monitorare richieste e risposte perationService/somma?a=2&b=5

44 44 TCPMon: 2.b Usare TCPMON come sender di messaggi SOAP 17 3

45 45 Ex. 2 Sviluppare un WS partendo da una classe Java

46 46 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; }

47 47 Ex. 2 Passi Aggiornare services.xml Aggiornare build.xml Creare il servizio Testare le operazioni

48 48 perationService/somma?a=2&b=5

49 49 Ex. 3 Creare un servizio Web e programma Client

50 50 Ex.3: Passi Classi di partenza Costruire la directory Services.xml Build.xml Da riga di comando ant generate.service ant rpc.client ant (per ripetere le chiamate del client Usare NetBeans New Project Java Project with existing Ant Scripts

51 51 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; 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 per usare TCPMonhttp://localhost:1234/axis2/services/AddressService options.setTo(targetEPR);

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

53 53 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; }

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

55 55 TcpMon

56 56 Esempio configurazione TCPMon

57 57 TCPMon: Ex2.a MathOperationService Usare TCPMon per monitorare richieste e risposte perationService/somma?a=2&b=5

58 58 TCPMon: 2.b Usare TCPMON come sender di messaggi SOAP 17 3

59 59 Ex 4: WSDL

60 60 Ex.4: Creare lo stub %AXIS2_HOME%\bin\wsdl2java –uri wsdl –p it.px.client –d adb –s wsdl -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

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

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

63 63 Ex.4: eseguire il client Creo un nuovo progetto su Netbeans New Project / Java Project with Existing sources Project folder: C:\servizi\axis \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"

64 64 Ex 5: invocare servizi web esterni Creare lo stub Creare il client Invocare il servizio remoto

65 65 Fine

Download ppt "1 L05 - Esercitazione Sviluppare SOAP Web Services con Axis2."

Similar presentations

Ads by Google