Soap and restful webservice

Preview:

Citation preview

SOAP And Restful Web Service

• Overview of web service• SOAP web service specification• SOAP Web Service Implementation• Restful web service specification• Restful Web Service Implementation• When to use

Agenda

• Definition: “A Web service is a software system designed to support interoperable machine-to-machine interaction over a network”.

• Characteristic– Machine-to-machine interactions– Loosely-coupling– Interoperability– Platform-independence– Language-independence– Operating system-independence– Leverage of the existing WWW

Web service definition

• Addressing the key points– How to encode/decode data need to be transferred: base64, binary..– The format of encoded application data(wire-protocol): STOMP, RMI, SOAP…– The protocol used to transfer data : HTTP, TCP, SMTP…– The way used to transfer data: publish/subscribe, point-to-point, request-response…

• Advantages of web service– Interoperability – Standard industry

• Disadvantages of web service– Performance: XML serializable, SOAP encoding..– Availability– Transaction– Authentication

Web service definition

• Roles in a SOAP web service– Service Provider: The service provider implements the service and

makes it available on the Internet.– Service Registry: Provides a central place where developers can

publish new services or find existing ones.– Service Consumer: consume the web service

• Protocol used– SOAP: provides a simple and lightweight mechanism for exchanging

structured and typed information between peers in a decentralized, distributed environment using XML.

– WSDL: defines services as collections of network endpoints.– UDDI: provides a platform-independent way of describing and

discovering Web services and Web service providers.– Transferring protocol: HTTP, FTP, SMTP…

SOAP Web Service

• Additional specification WS-*– WS-Security: encrypting XML message, digital signature before sending over network.– WS-Reliability: insure message is delivered correctly.– WS-Transaction: describe an extensible coordination framework and specific

coordination types for: Short duration, ACID transactions and longer running business transactions.

– WS-Addressing: defines a standard for incorporating message addressing information into web services messages and provides a uniform addressing method for SOAP messages traveling over synchronous and asynchronous transports

– WS-Policies– WS-Notification and Eventing: describes a publish/subscribe messaging

model implemented over Web services and leverages the WS-Addressing specification.– WS-I Basic Profile: provides interoperability guidance for core Web Services

specifications such as SOAP, WSDL, and UDDI.

SOAP Web Service

Technology stack

CXFAxis2

JbossWSOracle Fusion

jBPM, Oracle Fusion

SOAP Web Service Flow

Web Service Description Language(WSDL)• Describe the interface of a web service: location, method, message transferring…• Some major parts of a WSDL document:

– Message: Messages are the data element for all input/output for a WSDL and its operations– portType: is a set of abstract operations

• One-way: input only, the endpoint receives a message• Request-Response: the endpoint receives a message, process and return a response• Solicit-Response: output followed by input: The endpoint sends a message, and receives a

correlated message. This type of operation may also output an optional fault message. • Notification: output only, send message but not wait for response.

– Binding: how a portType operation will actually be transmitted over the wire, HTTP GET, HTTP POST, or SOAP

– Port: which specifies an address(like URI) for a binding– Service: is used to aggregate a set of related ports

WSDL: some examples

WSDL: Message Exchanging Pattern

Request-Response pattern

Solicit Request pattern

One-Way pattern

Notification patternasynchrony

synchrony

• SOAP: XML-based mechanism for exchanging structured data between network applications.• SOAP consist of some major parts:

– Envelope: defines an overall framework for expressing general info.– Header: is a generic container for control information.– Body: represents the message payload.– Fault: carry error and/or status information within a SOAP message.

• SOAP encode model:– SOAP Encoding: uses a set of rules based on the XML Schema data types to encode, but

the message does not conform to a particular schema– Literal XML: body contents conform to a specific XML Schema

• SOAP communication model: – Document-style – RPC-style

• The combination of encode and communication model affects considerably on performance, interoperability….

SOAP Web Service: SOAP

SOAP

SOAP Web Service StyleSoap bindingEncoded style

Document Style(Java default) RPC Style

Encoded Document-style message that does not include a schema (nobody uses this in practice).

RPC-style message that formats its body according to the rules defined in the SOAP standard (which are not always exact and can lead to incompatibilities).

Literal(java Default)

Document-style message that formats its body according to a schema. This schema is included in the WSDL. There’s also a 5th type. It isn’t an official standard but it is used a lot in practice. It came into being to compensate for document/literal’s main shortcoming of not having a standard way of specifying the web method name:

RPC-style message that formats its body according to a schema that reflects the rules defined in the SOAP standard. This schema is included in the WSDL.

Literal Wrapped(Java Default)

The same as document/literal, but wraps the contents of the body in an element with the same name as the web service method (just like RPC-style messages). This is what web services implemented in Java use by default.

Literal Bare

Communication model

• JAX-WS: – Java specification for next generation of XML Web Service model.– Support SOAP 1.1, SOAP 1.2 over HTTP– Support WSDL 1.1 HTTP Binding– Support WS-I Basic Profile 1.1 and 1.0– Go with Java 5 or later version which support many new feature.– Using JAXB for schema mapping.– Implemented by some most popular framework:

• CXF• Axis 2

• JAX-RPC:– Support SOAP 1.1– Support WS-I Basic Profile 1.0– Go with java 1.4– JAX-RPC has its own data mapping model

SOAP Web Service Implementation

• Annotation: simplifying the development effort and extensively used. – @ServiceMode: Message or Payload.– @WebService: mark a endpoint implementation as implementing a web service or to mark

that a service endpoint interface as defining a web service interface.– @WebMethod: define a web service operation– @WebEndpoint– @WebParam– @SOAPBinding: Document or RPC– @Oneway: a one-way operation returns the thread of control to the calling application prior

to executing the actual business method.– @HandlerChain: intercept the SOAP message before entering main process for

validating…by implementing SOAPHandler– @MTOM: support attachment like binary… format– @BindingType: binding to a specific protocol like SOAP, JMS…

JAX-WS

• Invoking Asynchronously web service– Asynchronous polling use: Service service = ...;

StockQuote quoteService = (StockQuote)service.getPort(portName); Response<Float> response = quoteService.getPriceAsync(ticker); while(response.isDone()) {

// do something while we wai } Float quote = response.get();

– Asynchronous callback use: class MyPriceHandler implements AsyncHandler<Float> { …………. public void handleResponse(Response<Float> response) {} }

JAX-WS

• Resource injection: @Resource private WebServiceContext ctx;• Data binding with JAXB 2.1

– Marshaling Java Object to XML.– Un-marshaling XML to Java Object.– Validate schema

• Support MTOM– Allowing to send binary attachment such as image– Optimizing transferring.

• Support SOAP 1.2• Support WS-Addressing

JAX-WS

• REST is described by a set of architectural constraints that attempt to minimize latency and network communications while, at the same time, maximizing the independence and scalability of component implementations.

• REST characteristic/constraints– Client-Server: Separation of concerns is the principle behind the client-

server.– Layer– Caching: improve network efficiency– Stateless: communication must be stateless in nature.– Uniform unique resource: emphasis on a uniform interface between

components, and is the central feature that distinguishes the REST architectural style from other network-based styles .

Restful Web Service

• Restful web service built base on the REST architecture style with some important feature:

– The web services are completely stateless. A good test is to consider whether the interaction can survive a restart of the server.

– A caching infrastructure can be leveraged for performance If the data that the web service returns is not dynamically generated.

– Bandwidth is particularly important and needs to be limited. REST is particularly useful for limited-profile devices, such as PDAs and mobile phones.

– The service producer and service consumer have a mutual understanding of the context and content being passed along. There is no formal way to describe the web services interface, both parties must agree with a pre-defined interface.

Restful Web Service

Restful Web Service Architecture

JSP/AjaxAngularJSIOS appAndroid app

HTTP/HTTPs/Other

Rest Controller

Service Facade

JSON, XML, PNG.

Core Services

• The API suggests its own usage– Using common and concrete terms– Using noun, not verb: /getAllCars -> /cars– Do not mix up singular and plural nouns

• Self-description the request-response.• JSON when possible, XML if have to• SSL everywhere - all the time• Pagination, sorting the query result• Average granularity, not just one resource = one URL• Use sub-resources for relations• Versioning with timestamp, a release number and in the path, not header• Leverage the HTTP status codes and error In a payload• Use HTTP headers for specifying serialization formats

– Content-Type defines the request format– Accept defines a list of acceptable response formats.

• Stateless design.

Restful Web Service design guidelines

• JAX-RS– A Java Specification for building Restful Web service– A part of JEE architecture– Current version: 2.0– Some most popular framework implementation:

• Jersey: a JAX-RS reference implementation from Oracle. • RESTEasy: fully certified and portable implementation of the JAX-RS by Jboss.• Restlet• CXF: enterprise solution with fully Spring integration.

• Non JAX-RS compliant:– Not fully support JAX-RS, provide some non-standard APIs

• Dropwizard: Java framework for developing ops-friendly, high-performance, RESTful web services.

• Spring MVC

How to build a Restful Web Service

• Annotation – @Path: is used to define a URI matching pattern for incoming HTTP

requests to a specific resource. URI value can be a regular expression, variables are denoted by braces { and }:

@Path("/users/{username}") -> http://example.com/users/Galileo@Path("{database}-db") public Object getDatabase(@PathParam("database") String db) -> http://example.com/oracle-db

– @GET: HTTP GET method is used to retrieve a representation of a resource, and It is both an idempotent and safe operation

• GET http://www.example.com/customers/12345• GET http://www.example.com/customers/12345/orders

– @POST: HTTP POST to *create* new resources• POST http://www.example.com/customers• POST http://www.example.com/customers/12345/orders

JAX-RS

• Annotation – @PUT: HTTP PUT to create/update a resource, this is an idempotent – @DELETE: HTTP DELETE use to delete a resource– @PathParam: retrieval based on id like GET /employee/{id}– @QueryParam: for filtering, allows to inject individual URI query parameter GET /customers?start=0&size=10 -> @GET(“/customers”) @Produces("application/xml") public String getCustomers(@QueryParam("start") int start, @QueryParam("size") int size) – @FormParam: used to access application/x-www-formurlencoded

request bodies.– @DefaultValue– @Cookie: use to retrieve the cookie value sending by client.

JAX-RS

• Asynchronous – Client asynchronous call by polling using Future or callback using

AsyncInvoker interface.– Server side asynchronous implementation

• Bean validation– Supports the Bean Validation to verify JAX-RS resource classes.– Using annotation: @NotNull, @Email..

• Filter and handler– Server filter: Request Filter and Response Filter by implementing

ContainerRequestFilter, ContainerRequestFilter.– Client filter: Request Filter and Response Filter by implementing

ClientRequestFilter, ClientResponseFilter.

JAX-RS

• Content negotiation– Client/Server can specify the expected content:

• Media: GET /library Accept: application/json• Language: GET /stuff Accept-Language: en-us, es• Encode:

– Using annotation:• @Consumes: specify which MIME media types of representations a resource

can accept, or consume, sending from the client.• @Produces: specify the MIME media types of representations a resource can

produce and send back to the client: application/json, application/xml, text/html, image/jpeg, image/png

• Client API• HATEOAS

JAX-RS

SOAP or RestfulSOAP Restful

Protocol->Standard Yes No, an architectural style

Behavior Services-> processing Resource-> represent the state of application, data

Transport HTTP, FTP, JMS, SMTP HTTP,…

Message Format XML XML, Json, Text

State management State-full Stateless

Cache No Yes

Client/Server model need

No Yes

THANK YOU

Recommended