57
Web Services Technologies Examples from the Mainstream june 2009 Alessandro Ricci [email protected]

Web Services Technologies Examples from the Mainstream

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Web Services Technologies Examples from the Mainstream

Web Services TechnologiesExamples from the Mainstream

june 2009

Alessandro Ricci

[email protected]

Page 2: Web Services Technologies Examples from the Mainstream

Outline

• Brief overview of the architecture of two main Web Service stack implementations

• Java Metro

• Apache Axis2

• JAX-WS specification

• standard Java-based programming model supported by both

Page 3: Web Services Technologies Examples from the Mainstream

Web Service Stack Implementations

• Different kind of technologies technologies

• Java Metro

• Apache Axis2

• Microsoft WCF

• ...

• A comparison: http://wiki.apache.org/ws/StackComparison

• Common Web Services standards

• SOAL, WSDL, WS-*

• Common standards for API

• JAX-WS

• implemented by Java Metro, Axis2

Page 4: Web Services Technologies Examples from the Mainstream

Java Metro

• High-performance, extensible, easy-to-use web service stack.

• Proposed as a “one-stop shop for all your web service needs”

• from the simplest hello world web service...

• ... to reliable, secured, and transacted web service that involves .NET services.

• Part of the GlassFish community

• but it can be also used outside GlassFish.

Page 5: Web Services Technologies Examples from the Mainstream

WSIT

• Metro includes WSIT (Web Services Interoperability Technologies)

• previously known as Project Tango

• It includes implementations of:

• WS-Trust

• WS-SecureConversation

• WS-SecurityPolicy

• WS-ReliableMessaging

• WS-AtomicTransactions/Coordination

• WS-MetadataExchange

• SOAP over TCP

• Interoperability between the Java platform and Windows Communication Foundation (WCF) (aka Indigo) in .NET 3.0 and .NET 3.5.

Page 6: Web Services Technologies Examples from the Mainstream

Metro Functionalities

...

Page 7: Web Services Technologies Examples from the Mainstream

Base Level

• Metro builds on top of libraries that are independently reusable outside the context of web services

• Those includes:

• JAXB RI for the databinding layer

• SAAJ for raw DOM access to SOAP messages

• Woodstox for efficient XML parsing

• XML stream buffer for efficient infoset buffering

Page 8: Web Services Technologies Examples from the Mainstream

Core Layer

• Implementation of the JAX-WS API

• serves as the foundation where all the higher-level features plugs in

• "pay as you go" model

• you'll only pay the performance/complexity price for features that you use

• Basic interoperability features

• WS-I Basic Profile, WS-I Attachments Profile, and WS-Addressing

Page 9: Web Services Technologies Examples from the Mainstream

Transport

• Several transports and related technologies to provide efficient connectivity to different services

• HTTP transport• Metro can act as both a client and a server for HTTP. The HTTP web

service can run inside any servlet container or anywhere on JavaSE6. • MTOM and XOP

• enabling optimized binary encodings of XML content within SOAP 1.2 payloads• XML structure is preserved in a text-based "XML Information Set"

manifest, while enabling the document's contents to be serialized to any binary encoding.

• SOAP over TCP transport • enables highly efficient transmission of SOAP messages by using

FastInfoset • Extensible

• other transports available as well, including the in-VM transport, JMS transport, SMTP transport, etc.

Page 10: Web Services Technologies Examples from the Mainstream

Reliability

• Ensures that the underlying system is able to recover from failures caused by messages that are lost or misordered in transit

• Recovery is handled by the underlying system without involvement of consumer or provider application code.

• Interoperable reliability is achieved by implementing the WS-ReliableMessaging specification

Page 11: Web Services Technologies Examples from the Mainstream

Transaction

• Atomic transactions

• ensuring that all operations within a transaction boundary succeed or fail in a consistent manner

• if even one operation fails then all other operations are aborted.

• transactional support has been available in Java Enterprise Edition for a number of years on IIOP invocations.

• Enabling transactional support for web services.

• interoperable atomic transactions by implementing the WS-Coordination and WS-AtomicTransactions specifications.

Page 12: Web Services Technologies Examples from the Mainstream

Security

• Implementing the WS-Security specification

• interoperable message content integrity and confidentiality, even in the presence of intermediaries

• Not relying on transport-based security

• such as SSL

• Implementation of the WS-Trust specification

• for issuing, renewing, and validating security tokens used by WS-Security, and to establish and broker trust relationships

Page 13: Web Services Technologies Examples from the Mainstream

Apache Axis2

• Apache implementation of the SOAP ("Simple Object Access Protocol") submission to W3C, as defined by the W3C specification:

• "SOAP is a lightweight protocol for exchanging structured information in a decentralized, distributed environment. It is an XML based protocol that consists of three parts: an envelope that defines a framework for describing what is in a message and how to process it, a set of encoding rules for expressing instances of application-defined datatypes, and a convention for representing remote procedure calls and responses."

• First version: Axis

• RPC-perspective on Web Services

• New version: Axis2

• Web Services in the SOA perspective

Page 14: Web Services Technologies Examples from the Mainstream

Axis2 at a glance

• Flexible, efficient and configurable architecture

• supporting SOAP 1.1, SOAP 1.2, REST style of Web services .

• the same business logic implementation can offer both a WS-* style interface as well as a REST/POX style interface simultaneously.M

• Modular and XML-oriented

• it is carefully designed to support the easy addition of plug-in "modules" that extend their functionality for features such as security and reliability

• Modules currently available:

• WS-ReliableMessaging (Apache Sandesha2)

• WS-Coordination and WS-AtomicTransaction (Apache Kandula2)

• WS-Security (Apache Rampart)

• WS-Addressing (part of Axis2 core)

Page 15: Web Services Technologies Examples from the Mainstream

Axis2 Features Overview

• 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

• 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

Page 16: Web Services Technologies Examples from the Mainstream

Axis2 Architecture

• Lifecycle of a Web services message in Axis2

• The sending application creates the original SOAP message, an XML message that consists of headers and a body

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

Page 17: Web Services Technologies Examples from the Mainstream

Handling Messages

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

• the value of Web services is that the sender and receiver (each of which can be either the server or the client) don't even have to be on the same platform, much less running the same application.

Page 18: Web Services Technologies Examples from the Mainstream

Handling Messages

• Assuming that Axis2 is running on both sides, the process is:• 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.

Page 19: Web Services Technologies Examples from the Mainstream

Phases

• Actions are broken down into "phases", with several pre-defined phases, such

• "pre-dispatch", "dispatch," and "message processing"

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

Page 20: Web Services Technologies Examples from the Mainstream

API Standardisations: JAX-WS 2.0

• It is a specification...

• so different implementations (e.g. Axis2, Java Metro,..)

• ... of a programming model ( = set of API)

• Java-based

• ...that aims at simplifying application development through support of a standard, annotation-based model to develop Web Service applications and clients in Java

• Document-centric messaging model, replacing the remote procedure call programming model as defined by JAX-RPC

• SOA perspective

Page 21: Web Services Technologies Examples from the Mainstream

Quick Overview of JAX-WS 2.0

• Simpler way to develop/deploy Web services (w.r.t. JAX-RPC)

• Plain Old Java Object (POJO) can be easily exposed as a Web service

• no deployment descriptor is needed - use Annotation instead

• Layered programming model

• Part of Java SE 6 and Java EE 5 platforms

• Integrated data binding via JAXB 2.0

• Protocol and transport independence

Page 22: Web Services Technologies Examples from the Mainstream

Platform independence

• Using JAX-WS APIs, development of Web services and clients is simplified with better platform independence for Java applications.

• JAX-WS takes advantage of the dynamic proxy mechanism to provide a formal delegation model with a pluggable provider.

• This is an enhancement over JAX-RPC, which relies on the generation of vendor-specific stubs for invocation.

Page 23: Web Services Technologies Examples from the Mainstream

Exploiting annotations

• JAX-WS introduces support for annotating Java classes with metadata to indicate that the Java class is a Web service.

• JAX-WS supports the use of annotations based on the Metadata Facility for the Java Programming Language (JSR 175) specification, the Web Services Metadata for the Java Platform (JSR 181) specification and annotations defined by the JAX-WS 2.0 specification

• Using annotations within the Java source and within the Java class simplifies development of Web services by defining some of the additional information that is typically obtained from deployment descriptor files, WSDL files, or mapping metadata from XML and WSDL files into the source artifacts.

Page 24: Web Services Technologies Examples from the Mainstream

JAX-WS Programming Model

• Layered programming model

• Server side

• Client side

Page 25: Web Services Technologies Examples from the Mainstream

Layered-programming model

Page 26: Web Services Technologies Examples from the Mainstream

Layered programming: features

• Upper layer uses annotations extensively

• easy to use

• toolability

• fewer generated classes

• Lower layer is more traditional

• API-based

• for advanced scenarios

• Most application will use the upper layer only

• Either way, portability is guaranteed

Page 27: Web Services Technologies Examples from the Mainstream

Server-side: two basic ways for building Web Services

• Starting from a WSDL file (top-down approach)

• Generate classes using ws import

• WS interface

• WS implementation skeleton class

• Add business logic to the WS implementation class

• Build, deploy, and test

• Starting from a POJO (bottom-up approach)

• Annotate POJO

• Build and deploy

• WSDL file generated automatically

Page 28: Web Services Technologies Examples from the Mainstream

Starting from POJO

• Write a POJO implementing the service

• Add @WebService annotation to it

• Optionally, inject a WebServiceContext

• Deploy the application

• Point your clients at the WSDL

• e.g. http://myserver/myapp/MyService?WSDL

Page 29: Web Services Technologies Examples from the Mainstream

Server-side: example

• @WebService annotation

• all public methods become web service operations

• WSDL/Schema generated automatically

• default values are used

import javax.jws.WebService;

@WebServicepublic class Calculator { public int add(int a, int b) { return a+b; }}

Page 30: Web Services Technologies Examples from the Mainstream

Publishing the Web Service

import javax.xml.ws.Endpoint;

public static void main(String[] args) {

Endpoint.publish( "http://localhost:8080/WebServiceExample/Calculator", new Calculator());

}

Page 31: Web Services Technologies Examples from the Mainstream

Customising through Annotations

@WebService(name=”CreditRatingService”,targetNamespace=”http://example.org”)public class CreditRating { @WebMethod(operationName=”getCreditScore”) public Score getCredit(@WebParam(name=”customer”) Customer c) { // ... implementation code ... }}

Page 32: Web Services Technologies Examples from the Mainstream

Starting from the WSDL

• Typically, you would start from WSDL to build your web service if you want to implement a web service that is already defined either by a standard or an existing instance of the service

• in either case, the WSDL already exists.

• the JAX-WS wsimport tool will process the existing WSDL document, either from a local copy on disk or by retrieving it from a network address

• wsimport will take the WSDL description and generate a corresponding Java interface and other supporting classes.

Page 33: Web Services Technologies Examples from the Mainstream

Client-side programming

• The process for creating a web service client application will always start with an existing WSDL document

• Point a tool (e.g. wsimport) at the WSDL for the service

• wsimport http://example.org/calculator.wsdl

• wsimport then generates the corresponding Java source code for the described interface

• Call new on the service class

• Get a proxy using a get<ServiceName>Port method

• Invoke any remote operations

Page 34: Web Services Technologies Examples from the Mainstream

Client-side: example

• No need to use factories

• The code is fully portable

• XML is completely hidden from programmer

CalculatorService svc = new CalculatorService();Calculator proxy = svc.getCalculatorPort();int answer = proxy.add(35, 7);

Page 35: Web Services Technologies Examples from the Mainstream

Annotations: @WebService

• Marks a Java class as implementing a Web Service, or a Java interface as defining a Web Service interface

• Attributes

• endpointInterface

• name

• portName

• serviceName

• targetNamespace

• wsdlLocation

Page 36: Web Services Technologies Examples from the Mainstream

Annotations: @WebMethod

• Customises a method that is exposed as a Web Service operation

• the method is not required to throw java.rmi.RemoteException.

• Attributes

• action

• exclude

• operationName

Page 37: Web Services Technologies Examples from the Mainstream

Annotations: @WebParam

• Customises the mapping of an individual parameter to a Web Service message part and XML element.

• Attributes

• header

• mode

• name

• partName

• targetNamespace

Page 38: Web Services Technologies Examples from the Mainstream

Annotations: @WebResult

• Customises the mapping of the return value to a WSDL part and XML element

• Attributes

• header

• name

• partName

• targetNamespace

Page 39: Web Services Technologies Examples from the Mainstream

Annotations: example

@WebService(targetNamespace = "http://duke.example.org", name="AddNumbers")@SOAPBinding(style=SOAPBinding.Style.RPC, use=SOAPBinding.Use.LITERAL)public interface AddNumbersIF { @WebMethod(operationName="add", action="urn:addNumbers") @WebResult(name="return") public int addNumbers( @WebParam(name="num1")int number1, @WebParam(name="num2")int number2) throws AddNumbersException;}

Page 40: Web Services Technologies Examples from the Mainstream

Data binding with JAXB 2.0

• Java Architecture for XML Binding (JAXB) is a Java technology that supports transformation between schema and Java objects and between XML instance documents and Java object instances.

• providing an easy way to map Java classes and XML schema for simplified development of Web services

• JAXB leverages the flexibility of platform-neutral XML data in Java applications to bind XML schema to Java applications without requiring extensive knowledge of XML programming

• JAXB consists of a runtime application programming interface (API) and accompanying tools that simplify access to XML documents.

• JAXB also helps to build XML documents that both conform and validate to the XML schema.

Page 41: Web Services Technologies Examples from the Mainstream

JAXB Architecture

• JAXB provides the xjc schema compiler tool, the schemagen schema generator tool, and a runtime framework.

• you can use the xjc schema compiler tool to start with an XML schema definition (XSD) to create a set of JavaBeans that map to the elements and types defined in the XSD schema.

• you can also start with a set of JavaBeans and use the schemagen schema generator tool to create the XML schema.

• once the mapping between XML schema and Java classes exists, XML instance documents can be converted to and from Java objects through the use of the JAXB binding runtime API.

• data stored in XML documents can be accessed without the need to understand the data structure. You can then use the resulting Java classes to assemble a Web services application

Page 42: Web Services Technologies Examples from the Mainstream

JAXB applicability

• JAXB annotated classes and artifacts contain all the information needed by the JAXB runtime API to process XML instance documents.

• The JAXB runtime API supports marshaling of JAXB objects to XML and unmarshaling the XML document back to JAXB class instances.

• optionally, you can use JAXB to provide XML validation to enforce both incoming and outgoing XML documents to conform to the XML constraints defined within the XML schema.

• JAXB is the default data binding technology used by the Java API for XML Web Services (JAX-WS) 2.0 tooling and implementation within this product.

• you can develop JAXB objects for use within JAX-WS applications.

• you can also use JAXB independently of JAX-WS when you want to leverage the XML data binding technology to manipulate XML within your Java applications.

Page 43: Web Services Technologies Examples from the Mainstream

Annotation benefits

• Using annotations makes it easier to expose Java artifacts as Web services

• In addition, as artifacts are created from using some of the top-down mapping tools starting from a WSDL file, annotations are included within the source and Java classes as a way of capturing the metadata along with the source files.

• Using annotations also improves the development of Web services within a team structure because you do not need to define every Web service in a single or common deployment descriptor as required with JAX-RPC Web services

• taking advantage of annotations with JAX-WS Web services allows parallel development of the service and the required metadata

Page 44: Web Services Technologies Examples from the Mainstream

Advanced concepts (...and problems...)

• State, sessions, concurrency

• resource injection

• Asynchronous invocations

Page 45: Web Services Technologies Examples from the Mainstream

Sessions and states

• Consider a simple Counter Web Service which tracks the user requests

• each time client calls getCounter(), the service returns the counter after incrementing by 1.

• Wrong

• the JAX-WS RI only creates one instance of a service class, and have it serve all incoming requests concurrently

@WebServicepublic class Hello { int counter = 0; public int getCounter() { // incorrect – not unique for each client session. return counter++; }}

Page 46: Web Services Technologies Examples from the Mainstream

Being state-less & session-less

• Web Services are stateless by default because of the underlying HTTP protocol. • the server processes each web service request as a new interaction even

though it is from the same client• to have a knowledge about previous requests, Server would need to

maintain state about the client through some sort• maintaining state/session would have extra load on the client/server in

terms of time and memory• even then, sometimes stateful web services can be useful for

conversational message exchange patterns, where multiple message exchanges are required between client and server.

Page 47: Web Services Technologies Examples from the Mainstream

Dealing with session (1/2)

• A solution exploiting resource injection

@WebServicepublic class Hello {

@Resource private WebServiceContext wsContext;

public int getCounter(){ MessageContext mc = wsContext.getMessageContext(); HttpSession session = ((javax.servlet.http.HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST)).getSession(); // Get a session property "counter" from context if (session == null) throw new WebServiceException("No session in WebServiceContext"); Integer counter = (Integer)session.getAttribute("counter"); if (counter == null) { counter = new Integer(0); System.out.println("Starting the Session"); } counter = new Integer(counter.intValue() + 1); session.setAttribute("counter", counter); return counter;

}}

is it a cleansolution?!?

Page 48: Web Services Technologies Examples from the Mainstream

Resource injection

• JAX-WS uses some annotations defined by Common Annotations for the Java Platform (JSR 250), to inject the Web Service context and declaring lifecycle methods

• Web ServiceContext holds the context information pertaining to a request being served.

• By placing the @Resource annotation on a service endpoint implementation, you can request a resource injection and collect the javax.xml.ws.WebServiceContext interface related to that particular endpoint invocation

• When the endpoint sees the @Resource annotation, the endpoint adds the annotated variable with an appropriate value before the servlet is placed into service.

• From the WebServiceContext interface, you can collect the MessageContext for the request associated with the particular method call using the getMessageContext() method

Page 49: Web Services Technologies Examples from the Mainstream

Dealing with the state (2/2)

• The JAX-WS RI has a vendor extension that allows developers to bring back object state to the web service world

• normally, the JAX-WS RI only creates one instance of a service class, and have it serve all incoming requests concurrently

• this makes it essentially impossible to use instance fields of the service class for any meaningful purpose.

• because of this, people end up coding like C, in anti-OO fashion. Either that or you end up with writing boiler-plate code to dispatch a request to the right instance of your real domain object.

• The stateful web service support in the JAX-WS RI resolves this problem by having the JAX-WS RI maintain multiple instances of a service

• by using WS-Addressing behind the scene, it provides a standard-based on-the-wire protocol and easy-to-use programming model

Page 50: Web Services Technologies Examples from the Mainstream

An example (1/2)

• declare @Stateful annotation on a class + public static method/field that takes StatefulWebServiceManager

@Stateful @WebService @Addressingclass BankAccount { protected final int id; private int balance; Account(int id) { this.id = id; } @WebMethod public synchronized void deposit(int amount) { balance+=amount; }

// either via a public static field public static StatefulWebServiceManager<BankAccount> manager; // ... or via a public static method (the method name could be anything) public static void setManager(StatefulWebServiceManager<BankAccount> manager) { ... }}

is it a cleansolution?!?

Page 51: Web Services Technologies Examples from the Mainstream

An example (2/2)

• After the service is deployed but before you receive a first request, the resource injection occurs on the field or the method.

• each instance of a stateful web service class is identified by an unique EndpointReference.

• Your application creates an instance of a class, then you'll have the JAX-WS RI assign this unique EPR for the instance as follows:

• Typically you then pass this EPR to remote systems.

• when they send messages to this EPR, the JAX-WS RI makes sure that the particular exported instance associated with that EPR will receive a service invocation.

@WebServiceclass Bank { // this is ordinary stateless service @WebMethod public synchronized W3CEndpointReference login(int accountId, int pin) { if(!checkPin(pin)) throw new AuthenticationFailedException("invalid pin"); BankAccount acc = new BankAccount(accountId); return BankAccount.manager.export(acc); }}

Page 52: Web Services Technologies Examples from the Mainstream

Asynchronous invocations

• Web services are called both synchronously and asynchronously

• JAX-WS adds support for both a polling and callback mechanism when calling Web services asynchronously

• using a polling model, a client can issue a request, get a response object back, which is polled to determine if the server has responded.

• When the server responds, the actual response is retrieved

• using the callback model, the client provides a callback handler to accept and process the inbound response object.

• Both the polling and callback models enable the client to focus on continuing to process work without waiting for a response to return, while providing for a more dynamic and efficient model to invoke Web services

Page 53: Web Services Technologies Examples from the Mainstream

Asynchronous invocations: example

• The asynchronous invocation that uses the callback mechanism requires an additional input by the client programmer.

• the callback is an object that contains the application code that will be executed when an asynchronous response is received

@WebServicepublic interface CreditRatingService { // sync operation Score getCreditScore(Customer customer); // async operation with polling Response<Score> getCreditScoreAsync(Customer customer); // async operation with callback Future<?> getCreditScoreAsync(Customer customer, AsyncHandler<Score> handler);}

Page 54: Web Services Technologies Examples from the Mainstream

Asynchronous call-back handler

... CreditRatingService svc = ...;

Future<?> invocation = svc.getCreditScoreAsync(customerFred, new AsyncHandler<Score>() { public void handleResponse (Response<Score> response){ Score score = response.get(); // do work here... } }); ...

concurrency problems?thread-safety?

Page 55: Web Services Technologies Examples from the Mainstream

Asynchronous polling client

CreditRatingService svc = ...; Response<Score> response = svc.getCreditScoreAsync(customerFred);

while (!response.isDone()) { // do something while we wait }

// no cast needed, thanks to generics Score score = response.get();

Page 56: Web Services Technologies Examples from the Mainstream

Concluding remarks

• Java Metro & Apache Axis2 technology

• modular / extensible / customisable architectures

• supporting the JAX-WS standard programming model

• not only JAX-WS, but also JAX-WS

• JAX-WS programming model

• very effective for simple services

• not so effective for complex services

• not really “one-stop shop for all your web service needs”