JEE - Web Services JAX-WS &
JAX-RS
Fahad R. Golra
ECE Paris Ecole d'Ingénieurs - FRANCE
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
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
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
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
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
Marshalling & Unmarshalling
7 JEE - Web Services JAX-WS & JAX-RS
Java
Object
Java
Object
Relational
Table
XML
Document
Object Relational Mapping Java/XML Binding
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
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
Basic Web Service Example
@WebService
public class BookCatalog {
@WebMethod
public 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
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
WSDL
WSDL
• SOAP defines the communication mechanism
• UDDI defines the registry of interface definitions
• WSDL defines the actual interfaces
UDDI
Registry
Web Services Model
12 JEE - Web Services JAX-WS & JAX-RS
Stub
Request: SOAP
invoke
Response: SOAP
return
results
Service
Consumer
Service
provider
Server-Side
Code
Client
Code
SOAP runtime
Library
invoke
return
results
Network
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
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
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
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
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
Code First vs. Contract First
18 JEE - Web Services JAX-WS & JAX-RS
WSDL
JAVA
WSDL
JAVA
Code First Contract First
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Jersey Client Side API - Code Sample
Client client = Client.create();

WebResource resource = client.resource(“...”);
//curl http://example.com/base
String 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
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
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
55 JEE - Web Services JAX-WS & JAX-RS

Lecture 7 Web Services JAX-WS & JAX-RS

  • 1.
    JEE - WebServices JAX-WS & JAX-RS Fahad R. Golra ECE Paris Ecole d'Ingénieurs - FRANCE
  • 2.
    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
  • 3.
    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
  • 4.
    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
  • 5.
    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
  • 6.
    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
  • 7.
    Marshalling & Unmarshalling 7JEE - Web Services JAX-WS & JAX-RS Java Object Java Object Relational Table XML Document Object Relational Mapping Java/XML Binding
  • 8.
    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
  • 9.
    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
  • 10.
    Basic Web ServiceExample @WebService public class BookCatalog { @WebMethod public 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
  • 11.
    Web Services Architecture 11JEE - 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 WSDL WSDL • SOAP defines the communication mechanism • UDDI defines the registry of interface definitions • WSDL defines the actual interfaces UDDI Registry
  • 12.
    Web Services Model 12JEE - Web Services JAX-WS & JAX-RS Stub Request: SOAP invoke Response: SOAP return results Service Consumer Service provider Server-Side Code Client Code SOAP runtime Library invoke return results Network
  • 13.
    Simple Object AccessProtocol (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
  • 14.
    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
  • 15.
    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
  • 16.
    Universal Description, Discoveryand 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
  • 17.
    Web Service DescriptionLanguage (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
  • 18.
    Code First vs.Contract First 18 JEE - Web Services JAX-WS & JAX-RS WSDL JAVA WSDL JAVA Code First Contract First
  • 19.
    Code First • Writeyour 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
  • 20.
    Contract First • Writeyour 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
  • 21.
    JAX-WS Usage • Buildingand 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
  • 22.
    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
  • 23.
    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
  • 24.
    Annotations in WebServices • 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
  • 25.
    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
  • 26.
    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
  • 27.
    wsimport tool • wsimporttool 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
  • 28.
    Client Side GeneratedFiles • 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
  • 29.
    Client for ourExample 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
  • 30.
    Java Architecture forXML 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
  • 31.
    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
  • 32.
    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
  • 33.
    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
  • 34.
    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
  • 35.
    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
  • 36.
    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
  • 37.
    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
  • 38.
    Resource based URI @Path("orders/{order_id}") publicclass OrderResource { @GET @Path("customer") CustomerResource getCustomer(@PathParam(“order_id”) int id) {...} } 38 JEE - Web Services JAX-WS & JAX-RS
  • 39.
    Stateless • A RESTFulapplication 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
  • 40.
    Standard Set ofMethods 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
  • 41.
    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
  • 42.
    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
  • 43.
    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
  • 44.
    Hello Example package com.ece.jee; importjavax.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
  • 45.
    Multiple Representations • Offerdata 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
  • 46.
    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
  • 47.
    Content Negotiation: AcceptHeader 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
  • 48.
    Content Negotiation: URLBased @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
  • 49.
    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
  • 50.
    JAX-RS summary • JavaAPI for building RESTful Web Services • POJO based • Annotation-driven • Server-side API • HTTP-centric 50 JEE - Web Services JAX-WS & JAX-RS
  • 51.
    Jersey Client SideAPI • 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
  • 52.
    Jersey Client SideAPI - Code Sample Client client = Client.create();
 WebResource resource = client.resource(“...”); //curl http://example.com/base String 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
  • 53.
    JAX-RS Wildfly Client-sideAPI 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
  • 54.
    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
  • 55.
    55 JEE -Web Services JAX-WS & JAX-RS