lecture 7 web services jax-ws & jax-rs

55
JEE - Web Services JAX-WS & JAX-RS Fahad R. Golra ECE Paris Ecole d'Ingénieurs - FRANCE

Upload: fahad-golra

Post on 17-Jul-2015

468 views

Category:

Software


10 download

TRANSCRIPT

Page 1: Lecture 7   Web Services JAX-WS & JAX-RS

JEE - Web Services JAX-WS & JAX-RS

Fahad R. Golra

ECE Paris Ecole d'Ingénieurs - FRANCE

Page 2: Lecture 7   Web Services JAX-WS & JAX-RS

Lecture 7 - Web Services JAX-WS & JAX-RS

• JAX-WS - SOAP Web Services • JAX-RS - RESTful Web Services

2 JEE - Web Services JAX-WS & JAX-RS

Page 3: Lecture 7   Web Services JAX-WS & JAX-RS

Web Services: Definition

• WW3C: “A software system designed to support interoperable machine-to-machine interaction over a network.”

• A Web service is a collection of functions that are packaged as a single entity and published to the network for use by other programs

3 JEE - Web Services JAX-WS & JAX-RS

Page 4: Lecture 7   Web Services JAX-WS & JAX-RS

Why Web Services ?

• Distributed architecture

• Interoperability • Based on open standards • Utilizes existing infrastructure • Can be accessed from any programming language

• Based on internet Standards • XML, XSD, http, etc.

4 JEE - Web Services JAX-WS & JAX-RS

Page 5: Lecture 7   Web Services JAX-WS & JAX-RS

Why Web Services ?

• Ease of use • Easy to understand concepts • Easy to implement • Toolkits allow COM, JEE and CORBA components

to be exposed as Web Services

5 JEE - Web Services JAX-WS & JAX-RS

Page 6: Lecture 7   Web Services JAX-WS & JAX-RS

Java Web Services

• Improved since J2EE 1.4 and JAX-RPC

• JAX-B: standard XML Binding

• JAX-WS: improving on JAX-RPC using annotations

• JAX-RS: developed for Java EE 6, stateless service

6 JEE - Web Services JAX-WS & JAX-RS

Page 7: Lecture 7   Web Services JAX-WS & JAX-RS

Marshalling & Unmarshalling

7 JEE - Web Services JAX-WS & JAX-RS

Java Object

Java Object

Relational Table

XML Document

Object Relational Mapping Java/XML Binding

Page 8: Lecture 7   Web Services JAX-WS & JAX-RS

eXtensible Markup Language (XML)

• Hierarchical tag-based structure like HTML • Language independent • Architecture neutral • Supports arbitrarily complex data formats • Schema can be used to define document formats

• defined in xsd files

8 JEE - Web Services JAX-WS & JAX-RS

Page 9: Lecture 7   Web Services JAX-WS & JAX-RS

Web Service Implementation

• Write a POJO implementing the service

• Add @WebService annotation to the POJO Class

• Optionally, inject a WebServiceContext

• WebServiceContext allows a web service endpoint implementation class to access message context and security information relative to a request

• Deploy the application

• Let your clients access the WSDL

9 JEE - Web Services JAX-WS & JAX-RS

Page 10: Lecture 7   Web Services JAX-WS & JAX-RS

Basic Web Service Example

@WebServicepublic class BookCatalog {

@WebMethodpublic List<String> getBooksCategory() {

List<String> bookCategory = new ArrayList<>();bookCategory.add("Alpha");bookCategory.add("Bravo");bookCategory.add("Charlie");return bookCategory;

}

}

10 JEE - Web Services JAX-WS & JAX-RS

Page 11: Lecture 7   Web Services JAX-WS & JAX-RS

Web Services Architecture

11 JEE - Web Services JAX-WS & JAX-RS

2. Request contract information

3. Retrieve WSDL definition

4. Exchange SOAP messages

1. Register contract information

Service Consumer

Service provider

WSDLWSDL

• SOAP defines the communication mechanism • UDDI defines the registry of interface definitions • WSDL defines the actual interfaces

UDDI Registry

Page 12: Lecture 7   Web Services JAX-WS & JAX-RS

Web Services Model

12 JEE - Web Services JAX-WS & JAX-RS

Stub

Request: SOAP

invokeResponse: SOAP

return results

Service Consumer

Service provider

Server-Side Code

Client Code

SOAP runtime Library

invoke

return results

Network

Page 13: Lecture 7   Web Services JAX-WS & JAX-RS

Simple Object Access Protocol (SOAP)

• XML based protocol for exchange of information • defines encoding rules for

datatype instances • RPC invocations

• Based on HTTP request-response model

• Uses XML Schema • Two different modes

• RPC • Document

13 JEE - Web Services JAX-WS & JAX-RS

SOAP Envelope <soap:Envelope xmlns:soap=“http://…”>

</soap:Envelope>

SOAP Header <soap:Header>

</soap:Header>

SOAP Body <soap:Body>

</soap:Body>

Headers

XML Content Optional SOAPFault

Page 14: Lecture 7   Web Services JAX-WS & JAX-RS

SOAP Example: Request

• Sample SOAP Message for our simple example

<?xml version="1.0" encoding="UTF-8" standalone="no"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header/> <soap:Body> <ns2:getBooksCategory xmlns:ns2="http://jee.ece.com/"/> </soap:Body> </soap:Envelope>

14 JEE - Web Services JAX-WS & JAX-RS

Page 15: Lecture 7   Web Services JAX-WS & JAX-RS

SOAP Example: Response

• Sample SOAP response from our basic example

<?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Header/> <soap:Body> <ns2:getBooksCategoryResponse xmlns:ns2="http://jee.ece.com/"> <return>Alpha</return> <return>Bravo</return> <return>Charlie</return> </ns2:getBooksCategoryResponse> </soap:Body> </soap:Envelope>

15

Page 16: Lecture 7   Web Services JAX-WS & JAX-RS

Universal Description, Discovery and Integration (UDDI)

• An online XML based registry where services can be • listed & registered • discovered & located

• Platform-independent, open framework for integrating business services

• Includes white, green and yellow pages for searching

16 JEE - Web Services JAX-WS & JAX-RS

Page 17: Lecture 7   Web Services JAX-WS & JAX-RS

Web Service Description Language (WSDL)

• An interface definition language for Web Services • Uses XML • Describes the web service operation signatures • Based on XML Schema

• Serves as a contract between the service providers and the service consumers

17 JEE - Web Services JAX-WS & JAX-RS

Page 18: Lecture 7   Web Services JAX-WS & JAX-RS

Code First vs. Contract First

18 JEE - Web Services JAX-WS & JAX-RS

WSDL

JAVA

WSDL

JAVA

Code First Contract First

Page 19: Lecture 7   Web Services JAX-WS & JAX-RS

Code First

• Write your code

• Annotate your code

• Deploy it in a container that supports JAX-WS

• JAX-WS runtime (metro) will • Generate WSDL • Translate SOAP request to a Java method

invocation • Translate method return into a SOAP response

19 JEE - Web Services JAX-WS & JAX-RS

Page 20: Lecture 7   Web Services JAX-WS & JAX-RS

Contract First

• Write your WSDL

• Generate an interface for each portType from the WSDL using wsimport

• Create a class that implements each interface

• Deploy these Service Endpoint Implementation classes to a JAX-WS container

20 JEE - Web Services JAX-WS & JAX-RS

Page 21: Lecture 7   Web Services JAX-WS & JAX-RS

JAX-WS Usage

• Building and using a web service

• write & compile the endpoint implementation class

• package as war archive & deploy it

• Code the client class

• Use “wsimport” tool to generate and compile the web

service artefacts needed to connect to the service

• Compile and run the client class

21 JEE - Web Services JAX-WS & JAX-RS

Page 22: Lecture 7   Web Services JAX-WS & JAX-RS

Service Endpoint Implementation

• Annotations come with attributes • e.g. @WebService has following attributes

• endpointInterface • name • portName • serviceName • targetNamespace • wsdlLocation

22 JEE - Web Services JAX-WS & JAX-RS

Page 23: Lecture 7   Web Services JAX-WS & JAX-RS

Using annotation attributes

• Web Services work on the idea of Interfaces • A change of interface will loose all the clients that

connect to your service. • It is a bad idea to directly annotate the class

without concretising the interface

• Interface can be concretised (locked) by • the use of proper annotation attributes • moving the annotations to an interface that is

implemented by the class

23 JEE - Web Services JAX-WS & JAX-RS

Page 24: Lecture 7   Web Services JAX-WS & JAX-RS

Annotations in Web Services

• Web Services Metadata Annotations • @WebService • @WebMethod • @OneWay • @WebParam • @WebResult

• JAX-WS Annotations • @RequestWrapper • @ResponseWrapper • @WebEndpoint • @WebFault • @WebServiceClient • @WebServiceRef

24 JEE - Web Services JAX-WS & JAX-RS

Page 25: Lecture 7   Web Services JAX-WS & JAX-RS

Example with annotations

@WebService(name = "EceBookCatalog", portName = "EceBookCatalogPort", serviceName = "BookCatalogueService", targetNamespace = "http://www.example.com")

@SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL,

parameterStyle = SOAPBinding.ParameterStyle.WRAPPED)public class BookCatalog2 {

BookServiceBusiness bookService = new BookServiceBusiness();……….

@WebMethod(action = "fetch_books", operationName = "fetchBooks")@WebResult(name = "bookList")public List<String> getBook(@WebParam(name = "categoryName") String Category) {

return bookService.getBooks(Category);}………..

}

25

Page 26: Lecture 7   Web Services JAX-WS & JAX-RS

Coding the client

• Use “wsimport” tool to generate service artefacts • Copy them to your client project • Create an object of the service • Retrieve a proxy to the service, also known as port. • The service operations can be called through this

port.

26 JEE - Web Services JAX-WS & JAX-RS

Page 27: Lecture 7   Web Services JAX-WS & JAX-RS

wsimport tool

• wsimport tool is used for client side generation from the WSDL

• Syntax wsimport [options] <wsdl location>

• Options • -d <directory> : generate out files location • -s <directory> : source files location • -keep : Keep generated files

27 JEE - Web Services JAX-WS & JAX-RS

Page 28: Lecture 7   Web Services JAX-WS & JAX-RS

Client Side Generated Files

• BookCatalogService.java Service factory

• BookCatalog.java Service Endpoint Interface

• GetBookCategory.java Custom data type for request

• GetBookCategoryResponse.java Custom data type for response

• ObjectFactory.java JAXB XML Registry

• package-info.java Holder for JAXB package annotations

28 JEE - Web Services JAX-WS & JAX-RS

Page 29: Lecture 7   Web Services JAX-WS & JAX-RS

Client for our Example

public class BookCustomer {

public static void main(String[] args) {List<String> bookCategories;

BookCatalogService service = new BookCatalogService();BookCatalog port = service.getBookCatalogPort();

bookCategories = port.getBooksCategory();

for (String category : bookCategories) {System.out.println("Book category: " + category);

}}

}

29

Page 30: Lecture 7   Web Services JAX-WS & JAX-RS

Java Architecture for XML Binding (JAXB)

• JAX-WS delegates the mapping of the Java language data types to JAXB API.

• JAXB converts XML schemas (and data types) to Java and vice versa

• XML schema described by WSDL is translated to Java and vice versa, by JAXB

30 JEE - Web Services JAX-WS & JAX-RS

Page 31: Lecture 7   Web Services JAX-WS & JAX-RS

Schema Type vs. Data Type

31 JEE - Web Services JAX-WS & JAX-RS

XML Schema Type Java Data Type

xsd:string java.lang.String

xsd:integer java.math.BigInteger

xsd:int int

xsd:long long

xsd:short short

xsd:decimal java.math.BigDecimal

xsd:float float

Page 32: Lecture 7   Web Services JAX-WS & JAX-RS

RESTful Web Services

• REpresentational State Transfer (REST)

• No specification for RESTful web services

• An approach presented by Roy Fielding in his doctoral thesis

32 JEE - Web Services JAX-WS & JAX-RS

Page 33: Lecture 7   Web Services JAX-WS & JAX-RS

Coming from SOAP

• No Standard Protocol • XML, JSON, Text or any other format

• No Service Definition • No WSDL • WADL, but not used commonly • Better implementations should not use any

33 JEE - Web Services JAX-WS & JAX-RS

Page 34: Lecture 7   Web Services JAX-WS & JAX-RS

Inspiration from HTTP

• Resource based URI

• Methods: GET, POST, PUT, DELETE

• Metadata (header) • Status Codes • Content Type

34 JEE - Web Services JAX-WS & JAX-RS

Page 35: Lecture 7   Web Services JAX-WS & JAX-RS

Principles of REST

• Give everything an ID

• Standard set of methods

• Link things together

• Multiple representations

• Stateless communications

35 JEE - Web Services JAX-WS & JAX-RS

Page 36: Lecture 7   Web Services JAX-WS & JAX-RS

Resource based URI

• Treat each dynamic page as a static resource • www.facebook.com/user1 • www.facebook.com/{userid}

• Resource relations • www.example.com/tutorials/{tutorialid}/sections{sectionid}

• Collection URIs • www.example.com/tutorials/{tutorialid}/sections

• URI Filters • www.example.com/tutorials/{tutorialid}/sections?

offset=5&limit=3

36 JEE - Web Services JAX-WS & JAX-RS

Page 37: Lecture 7   Web Services JAX-WS & JAX-RS

Resource based URI

• Resource == Java class • POJO • No required interfaces

• ID provided by @Path annotation • Value is relative URI, base URI is provided by

deployment context or parent resource • Embedded parameters for non-fixed parts of the URI • Annotate class or “sub-resource locator” method

37 JEE - Web Services JAX-WS & JAX-RS

Page 38: Lecture 7   Web Services JAX-WS & JAX-RS

Resource based URI

@Path("orders/{order_id}") public class OrderResource {

@GET @Path("customer") CustomerResource getCustomer(@PathParam(“order_id”) int id) {...}

}

38 JEE - Web Services JAX-WS & JAX-RS

Page 39: Lecture 7   Web Services JAX-WS & JAX-RS

Stateless

• A RESTFul application does not maintain sessions/conversations on the server

• Doesn’t mean an application can’t have state • REST mandates

• That state be converted to resource state • Conversational state be held on client and transferred

with each request • Sessions are not linkable

• You can’t link a reference to a service that requires a session

39 JEE - Web Services JAX-WS & JAX-RS

Page 40: Lecture 7   Web Services JAX-WS & JAX-RS

Standard Set of Methods

40 JEE - Web Services JAX-WS & JAX-RS

Method Purpose

GET Read, possibly cached

POST Update or create without a known Id

PUT Update or create with a known Id

DELETE Remove

Page 41: Lecture 7   Web Services JAX-WS & JAX-RS

Behavior of Methods

• Predictable behavior • GET - readonly and idempotent. Never changes the

state of the resource • PUT - an idempotent insert or update of a resource.

Idempotent because it is repeatable without side effects.

• DELETE - resource removal and idempotent. • POST - non-idempotent, “anything goes” operation

41 JEE - Web Services JAX-WS & JAX-RS

Page 42: Lecture 7   Web Services JAX-WS & JAX-RS

JAX-RS Annotations

• @Path

• Defines URI mappings and templates

• @ProduceMime, @ConsumeMime

• What MIME types does the resource produce and consume

• @GET, @POST, @DELETE, @PUT, @HEADER

• Identifies which HTTP method the Java method is interested in

42 JEE - Web Services JAX-WS & JAX-RS

Page 43: Lecture 7   Web Services JAX-WS & JAX-RS

JAX-RS Annotations

• @PathParam • Allows you to extract URI parameters/named URI

template segments • @QueryParam

• Access to specific parameter URI query string • @HeaderParam

• Access to a specific HTTP Header • @CookieParam

• Access to a specific cookie value • @MatrixParam

• Access to a specific matrix parameter

43 JEE - Web Services JAX-WS & JAX-RS

Page 44: Lecture 7   Web Services JAX-WS & JAX-RS

Hello Example

package com.ece.jee;

import javax.ws.rs.GET;import javax.ws.rs.Path;import javax.ws.rs.Produces;import javax.ws.rs.core.MediaType;

@Path("/app")public class SayHello {

@GET@Produces(MediaType.TEXT_HTML)@Path("/hello")public String sayHello() {

return "<h1> Hello Dude !!! </h1>";}

}

44 JEE - Web Services JAX-WS & JAX-RS

Page 45: Lecture 7   Web Services JAX-WS & JAX-RS

Multiple Representations

• Offer data in a variety of formats • XML (Type safety advantage) • JSON (easy to parse with JavaScript clients) • (X)HTML (Ideal for clients like browsers for human readable

documents

• Support content negotiation • Accept header

GET /foo Accept: application/json

• URI-based GET /foo.json

45 JEE - Web Services JAX-WS & JAX-RS

Page 46: Lecture 7   Web Services JAX-WS & JAX-RS

Accept: application/xml Accept: application/json;q=1.0, text/plain;q=0.5, application/xml;q=0.5,

@GET

@Produces({"application/xml","application/json"})

Order getOrder(@PathParam("order_id") String id) { ...

}

@GET

@Produces("text/plain")

46 JEE - Web Services JAX-WS & JAX-RS

Page 47: Lecture 7   Web Services JAX-WS & JAX-RS

Content Negotiation: Accept Header

Accept: application/xml Accept: application/json;q=1.0, text/plain;q=0.5, application/xml;q=0.5,

@GET @Produces({"application/xml","application/json"}) Order getOrder(@PathParam("order_id") String id) { ... } @GET @Produces("text/plain") String getOrder2(@PathParam("order_id") String id) { ... }

47

Page 48: Lecture 7   Web Services JAX-WS & JAX-RS

Content Negotiation: URL Based

@Path("/orders") public class OrderResource {

@Path("{orderId}.xml") @Produces(“application/xml”) @GET public Order getOrderInXML(@PathParam("orderId") String orderId) { ... }

@Path("{orderId}.json") @Produces(“application/json”) @GET public Order getOrderInJSON(@PathParam("orderId") String orderId) { ... } }

48

Page 49: Lecture 7   Web Services JAX-WS & JAX-RS

Configuration in Wildfly

• Resteasy is the JBoss Implementation of JAX-RS API

• Bundled with wildfly server

• Specify Servlet mapping as per specification OR

• Create a class

@ApplicationPath("/version")public class MyApplication extends Application {}

49

Page 50: Lecture 7   Web Services JAX-WS & JAX-RS

JAX-RS summary

• Java API for building RESTful Web Services

• POJO based

• Annotation-driven

• Server-side API

• HTTP-centric

50 JEE - Web Services JAX-WS & JAX-RS

Page 51: Lecture 7   Web Services JAX-WS & JAX-RS

Jersey Client Side API

• Consume HTTP-based RESTful Services

• Easy-to-use

• Better than HttpURLConnection

• Reuses JAX-RS API

• Resources and URI are first-class citizens

• Not part of JAX-RS yet

• com.sun.jersey.api.client

51 JEE - Web Services JAX-WS & JAX-RS

Page 52: Lecture 7   Web Services JAX-WS & JAX-RS

Jersey Client Side API - Code Sample

Client client = Client.create(); WebResource resource = client.resource(“...”); //curl http://example.com/baseString s = resource.get(String.class); //curl -HAccept:text/plain http://example.com/base String s = resource.accept(“text/plain”).get(String.class);

52 JEE - Web Services JAX-WS & JAX-RS

Page 53: Lecture 7   Web Services JAX-WS & JAX-RS

JAX-RS Wildfly Client-side API

public class HelloClient {private Client client;private WebTarget target;

public HelloClient() {this.client = ClientBuilder.newClient();this.target = this.client

.target("http://localhost:8080/Rest/version/app/hello");}

public void asyncInvocation() throws InterruptedException {this.target.request("text/html").async()

.get(new InvocationCallback<String>() {

public void completed(String response) {System.out.println("--" + response);

}

public void failed(Throwable throwab) {

}});

Thread.sleep(2000);

53 JEE - Web Services JAX-WS & JAX-RS

Page 54: Lecture 7   Web Services JAX-WS & JAX-RS

Rest Client Wildfly: Hello Example

public class HelloClient {private Client client;private WebTarget target;

public HelloClient() {this.client = ClientBuilder.newClient();this.target = this.client

.target("http://localhost:8080/Rest/version/app/hello");}

public void asyncInvocation() throws InterruptedException {this.target.request("text/html").async()

.get(new InvocationCallback<String>() {

public void completed(String response) {System.out.println("--" + response);

}

public void failed(Throwable throwab) {

}});

Thread.sleep(2000);}

}54

Page 55: Lecture 7   Web Services JAX-WS & JAX-RS

55 JEE - Web Services JAX-WS & JAX-RS