You are on page 1of 35

Java Web Services

JavaLounge

Made Easy
Mario Goller (ZH-AD)
10.05.2012

BASEL

BERN

LAUSANNE

ZRICH

2011 Trivadis
Java Web Services
27.04.2012

DSSELDORF

FRANKFURT A.M.

FREIBURG I.BR.

HAMBURG

MNCHEN

STUTTGART

WIEN

AGENDA
1. Web Service Basics
2. JAX-WS
Overview
Endpoint implementation
Service consumer

3. JAX-RS
Overview
Resources and Parameters
Representations

2011 Trivadis
Java Web Services
27.04.2012

Web Service Basics


It enables application-to-application
interaction over the Web, regardless of
platform, language, or data formats
Applications can make themselves available
over the Inter/Intranet using a standardized
XML messaging system : SOAP, WSDL and
UDDI
Communication protocol to transport the
XML messages over the network can be HTTP,
SMTP or FTP
HTTP is the most popular transport protocol

2011 Trivadis
Java Web Services
27.04.2012

Web Service Basics


WSDL (Web Services Description Language)
WSDL is an XML-based format designed to
describe the interfaces exposed by a service
What a service does?
How clients can use it?

SOAP
specifies exactly how to encode an XML file,
i.e. how an application can call another
application and pass information to it
It also specifies how the called application
can return a response
It is fundamentally a stateless one-way
transmission protocol
4

2011 Trivadis
Java Web Services
27.04.2012

AGENDA
1. Web Service Basics
2. JAX-WS
Overview
Endpoint implementation
Service consumer

3. JAX-RS
Overview
Resources and Parameters
Representations

2011 Trivadis
Java Web Services
27.04.2012

Overview JAX-WS
Java API for XML Web Services
Since Java EE 5, JAX-WS (JSR 224) , now also included in Java 6 SE)
replaces the older JAX-RPC API (= old Java web services, basically RMI)
JAX-WS is platform independent (Java frameworks like Metro/Glassfish,
Axis2 or CXF support JAX-WS). Services developed on one platform can
be easily ported to another platform.
Annotation based
Tools available for WSDL consumption
Development Approaches
Contract First (Top Down)
Code First (Bottom Up)
6

2011 Trivadis
Java Web Services
27.04.2012

Metro Web Service Stack


Extensible web-service stack (http://jax-ws.java.net)
Tools

WSIT

JAX-WS
XML
Transport
7

JAX-WS Tooling (NetBeans)

Security

ReliableMessaging

Transactions

Metadata
WSDL
Policy

Core Web Services


JAXB, JAXP, StAX

HTTP

2011 Trivadis
Java Web Services
27.04.2012

TCP

SMTP

JAX-WS Communication Model


JAX-WS 2.2 allows both regular Java classes and stateless EJBs to be
exposed as web services

2011 Trivadis
Java Web Services
27.04.2012

JAX-WS Annotation
The @javax.jws.WebService annotation marks a Java class or
interface as being a web service
By default, all the public methods of a web service are exposed in the
WSDL and use all the default mapping rules. To customize some
elements of this mapping, you can apply the @javax.jws.WebMethod
annotation on methods.
The @javax.jws.WebResult annotation operates in conjunction
with @WebMethod to control the generated name of the message
returned value in the WSDL
The @javax.jws.WebParam annotation is similar to @WebResult as it
customizes the parameters for the web service methods.

2011 Trivadis
Java Web Services
27.04.2012

JAX-WS Annotation - Example


Service Endpoint implementation
@WebService
@
public class OrderService {

@Stateless
@WebService
public class OrderEJB {
...
}

@WebMethod
public String getOrder(@WebParam(name = "id") int i) {...}
@WebMethod
public @WebResult(name="orderStatus") int getStatus(int i)
{...}
@PostConstruct
public void init() {...}
@PreDestroy
public void teardown() {...}
}

10

2011 Trivadis
Java Web Services
27.04.2012

lifecycle callback
methods

JAX-WS Development in Detail

11

2011 Trivadis
Java Web Services
27.04.2012

JAX-WS JavaSE Endpoint


Use embedded HttpServer to deploy the webservice
public class HelloPublisher {
public static final String URI =
"http://localhost:9999/hello";
public static void main(String[] args) {
//Create instance of service implementation
HelloWS impl = new HelloWS();
//Make available
Endpoint endpoint = Endpoint.publish(URI, impl);
...
// stop the service endpoint
endpoint.stop();
}
}

12

2011 Trivadis
Java Web Services
27.04.2012

JAX-WS Application Client


Generate artifact using wsimport pointing to WSDL
wsimport generates JAXB binding classes and service endpoint
C:\>wsimport p client keep http://localhost:8080/orderService?wsdl

This populates the client subdirectory with .class and .java files.
Call the web service using the generated client-side stubs:

OrderWSService service = new OrderWSService();


OrderWS port = service.getOrderWSPort();
Order result = port.getOrder(2);
System.out.println("Found Order: " + result);

13

2011 Trivadis
Java Web Services
27.04.2012

Creating a Web Service Consumer


The process of creating and using a SEI and its associated proxy instance

14

2011 Trivadis
Java Web Services
27.04.2012

Consuming a Web Service from a Servlet or EJB


An EJB, Servlet, or other container-managed resource can act as web
service client
Use the @WebServiceRef annotation to inject a reference to the
service you want to invoke
public class MyServlet extends HttpServlet {
@WebServiceRef(type = OrderWSService.class)
private OrderWSService service;
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) {
...
OrderWS port = service.getOrderWSServicePort();
...
}
}
15

2011 Trivadis
Java Web Services
27.04.2012

Asynchronous Calls with a JAX-WS Client


Using the binding customizations
add the <enableAsyncMapping> custom binding on the server side
in the WSDL, then use one of the (generated) invokeAsync methods
available on your SEI
Each asynchronous method has a different manner of handling the
asynchronous behavior: polling and callbacks
Example using a polling mechanism:
Response<DoLongJobResponse> response = port.doLongJobAsync(jobName);
while(!response.isDone()){
LOGGER.debug("Waiting...");
Thread.sleep(1000); //do something
}
DoLongJobResponse res = response.get();

16

2011 Trivadis
Java Web Services
27.04.2012

Asynchronous Service Calls


Example using Asynchronous Callbacks by writing a callback handler:
class MyHandler implements AsyncHandler<DoLongJobResponse> {
private DoLongJobResponse response;
public void handleResponse(Response<DoLongJobResponse>
> in)
{
response = in.get();
LOGGER.debug("Got response! " +
response.getJobDone());
}
}

17

2011 Trivadis
Java Web Services
27.04.2012

Short comparison of important Java WS stacks


JAX-WS (Glassfish RI):
JAX-WS compliant (the RI defines the standard).
Supported by many WS frameworks.

Apache CXF framework:


Easy to use, slim
Apache Axis2:
Features-rich, but also high complexity
Not (fully) JAX-WS compliant (not JAX-WS technology compatibility kit
compliant).
Support for different XML-Java binding frameworks (XMLBeans etc.)

JBoss:
uses CXF or Metro as WS-stack (http://www.jboss.org/jbossws)

18

2011 Trivadis
Java Web Services
27.04.2012

JAX-WS Handler
JAX-WS provides a handler framework that allows application code to
inspect and manipulate outgoing and incoming SOAP messages:
LogicalHandler access only to the message payload
SOAPHandler access to the entire SOAP message, including any optional
headers and attachments

1.

Create a handler class, which implements the Handler interface

2.

Place a handler within a handler chain (e.g. configuration file)

19

2011 Trivadis
Java Web Services
27.04.2012

AGENDA
1. Web Service Basics
2. JAX-WS
Overview
Endpoint implementation
Service consumer

3. JAX-RS
Overview
Resources and Parameters
Representations

20

2011 Trivadis
Java Web Services
27.04.2012

What is REST?
REpresentational State Transfer (REST)
REST is an architectural style
Client/server + Request/response approach

Based on key principles of WWW


Priciples of REST:
Everything is a resource
CRUD (Create / Read / Update / Delete)
Stateless by nature (excellent for distributed systems)
Cachable (naturally supported !)
Layered, with optional intermediaries
Safety / Idempotency

21

2011 Trivadis
Java Web Services
27.04.2012

JAX-RS Introduction
Java API for RESTful Web Services (JAX-RS) JSR 311
Standard annotaions-driven API, standard part of Java EE 6
uses annotations on POJOs (Plain Old Java Objects) to map to the
RESTful style of presenting web applications
Jersey reference implementation
Download it from http://jersey.dev.java.net
Comes with Glassfish, Java EE 6
Tools support in NetBeans

22

2011 Trivadis
Java Web Services
27.04.2012

RESTful Web Services with JAX-RS


Resource == Java class
POJO, EJB Stateless, Singleton Session Beans

Resources are identified by an unique identifier in form of URIs (Uniform


Resource Identifier)
URI provided by @Path annotation
Relative to deployment context
Annotate class or sub-resource locator method
@Path("/books")
public class BookResource {
@Path("/all")
public String getAll() {...}
}

23

2011 Trivadis
Java Web Services
27.04.2012

REST Standard Methods


Annotate resource class methods with standard method
@GET, @PUT, @POST, @DELETE, @HEAD
JAX-RS routes request to appropriate resource class and method
Flexible method signatures, annotations on parameters specify mapping
from request
Return value mapped to response
@Path("/books")
public class BookResource{
@GET
Book getBook(@QueryParam("title") String title) {...}
@DELETE
boolean delete(@QueryParam("title") String title) {...}
}
24

2011 Trivadis
Java Web Services
27.04.2012

How it works

Application
GET /books/all HTTP/1.1
Accept: text/xml

URL
Matching

Resource
Method
Matching

Content
type
Matching

@GET
@Produces("application/xml")
public List<Book> getAll(){

HTTP/1.1 200 OK
Content-Type: text/xml

25

2011 Trivadis
Java Web Services
27.04.2012

Sub-Resources and Parameters


a class that can respond for many instances of the same type
Access a specific instance by using a URL that includes the identifier
annotations on parameters specify mapping from request data
return value is mapped to http response
Restriction of values in a path template with regular expressions
@Path("/books")
public class BookResource {
@GET
Path("/{id: \\d{5}}")
Book getBook(@PathParam("id") String id) {...}
}

26

2011 Trivadis
Java Web Services
27.04.2012

Variable Resources and Parameters


GET /books

Server

Client
List all available books
@Path("/books")
public class OrderResource {
@GET
String getAll() {...}
}

GET /books/?id=234

Server

Client
Returns the book with ID 234
@Path("/books")
public class BookResource {
@GET
Book getBook(@QueryParam("id") String id) {...}
}
27

2011 Trivadis
Java Web Services
27.04.2012

HTTP Example
Request
GET /books/all HTTP/1.1
Host: rest.example.com
Accept: application/xml

Method
Resource

Response
HTTP/1.1 200 OK
Date: Tue, 08 May 2012 16:41:58 GMT
Server: Apache/1.3.6
Content-Type: application/xml; charset=UTF-8
<?xml version="1.0"?>
<books xmlns="">
<book></book>

</book>
28

2011 Trivadis
Java Web Services
27.04.2012

Representation

JAX-RS Representations
Static and dynamic content negotiation
Multiple representations
Annotate methods or classes:
@Produces matches Accepts header
@Consumes matches Content-Type header
@GET
@Consumes("application/xml")
@Produces({"application/xml","application/json"})
String getOrder(@PathParam("order_id") String id) {
...
}

29

2011 Trivadis
Java Web Services
27.04.2012

Multiple Representations
Representation oriented
Representations
{order: {id:123, items:[{item: {...}]}}
JSON

GET http://host/orders/123

Order 123

PDF

Accept: application/json
Accept-Language: en

XML

30

2011 Trivadis
Java Web Services
27.04.2012

JAX-RS Providers
Provides adaptation between the HTTP world and your own
application domain:
MessageBodyReader
MessageBodyWriter

@Produces("text/xml")
@Provider
public class OrderXMLWriter implements
MessageBodyWriter<List<Order>> {
...
}
31

2011 Trivadis
Java Web Services
27.04.2012

Summary
JAX-WS
easier to use and more powerful than JAX-RPC
annotation-based
part of the Java EE (5/6) and Java SE 6 platforms
Layered design hides the complexity
- Extensible at the protocol and transport level
JAX-RS
High-level declarative programming model for REST
annotation-based

32

2011 Trivadis
Java Web Services
27.04.2012

Summary
Use REST (JAX-RS):
only synchronous
short-running calls
When the web
services are
completely stateless
When bandwidth is
particularly important
and needs to be
limited

33

2011 Trivadis
Java Web Services
27.04.2012

Use SOAP (JAX-WS):


When the architecture
must address complex
nonfunctional
requirements such as:
Transactions
Security
Addressing
Trust
Coordination

when synchr. and


asynchr. long-running
calls

Questions ?

34

2011 Trivadis
Java Web Services
27.04.2012

Trivadis AG

THANK YOU.

Mario Goller
Europastrasse 5
CH-8152 Glattbrugg (ZH)
Tel. +41-44-808 70 20
Fax +41-44-808 70 21
info@trivadis.com
www.trivadis.com

BASEL

35

BERN

LAUSANNE

ZRICH

2011 Trivadis
Java Web Services
27.04.2012

DSSELDORF

FRANKFURT A.M.

FREIBURG I.BR.

HAMBURG

MNCHEN

STUTTGART

WIEN

You might also like