REST and JAX-RS

59
JAX-RS and the REST will follow Guy Nir

description

Review of REST and JAX-RS, as presented by Guy Nir at AlphaCSP's JavaEdge conference, 2009.

Transcript of REST and JAX-RS

Page 1: REST and JAX-RS

JAX-RS… and the REST will follow

Guy Nir

Page 2: REST and JAX-RS

2

» REST – What ? Who ? Why ?

» JAX-RS (JSR-311) - Digg’n in

» Security

» Application-Level Protocol

» Summary

Agenda

Page 3: REST and JAX-RS

What ? Who ? Why ?

… and how

Page 4: REST and JAX-RS

4

Architectural overview

What ? Who ? Why ?

HTTP clientYahoo’s weather

web-server

HTTP request

HTTP response

GET http://weather.yahoo.com/israel/tel-aviv/ramat-gan-1967869/

RESPONSE CODE: 200 (OK) + BODY

Page 5: REST and JAX-RS

5

Architectural overview

What ? Who ? Why ?

GET http://weather.yahoo.com/israel/tel-aviv/ramat-gan-1967869/

Read,

GET http://weather.yahoo.com/israel/tel-aviv/ramat-gan-1967869/

The weather in Israel at Tel-Aviv area (Ramat Gan).

Page 6: REST and JAX-RS

6

HTTP request overview

What ? Who ? Why ?

GET /israel/tel-aviv/ramat-gan-1967869/ HTTP/1.1

Host: weather.yahoo.com

Accept: image/gif, application/xaml+xml, */*

Accept-Language: en-us

User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; ... )

Accept-Encoding: gzip, deflate

Connection: Keep-Alive

Cookie: BA=ba=2139&ip=82.80.99.106&t=1258874241;

HTTP clientYahoo’s weather

web-server

HTTP request

GET http://weather.yahoo.com/israel/tel-aviv/ramat-gan-1967869/

Page 7: REST and JAX-RS

7

HTTP request overview

What ? Who ? Why ?

GET /israel/tel-aviv/ramat-gan-1967869/ HTTP/1.1

Host: weather.yahoo.com

Accept: image/gif, application/xaml+xml, */*

Accept-Language: en-us

User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; ... )

Accept-Encoding: gzip, deflate

Connection: Keep-Alive

Cookie: BA=ba=2139&ip=82.80.99.106&t=1258874241;

HTTP clientYahoo’s weather

web-server

HTTP request

GET http://weather.yahoo.com/israel/tel-aviv/ramat-gan-1967869/

Page 8: REST and JAX-RS

8

HTTP request overview

What ? Who ? Why ?

GET /israel/tel-aviv/ramat-gan-1967869/ HTTP/1.1

Host: weather.yahoo.com

Accept: image/gif, text/plain, application/xml, */*

Accept-Language: en-us

User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; ... )

Accept-Encoding: gzip, deflate

Connection: Keep-Alive

Cookie: BA=ba=2139&ip=82.80.99.106&t=1258874241;

HTTP clientYahoo’s weather

web-server

HTTP request

GET http://weather.yahoo.com/israel/tel-aviv/ramat-gan-1967869/

Page 9: REST and JAX-RS

9

HTTP request overview

What ? Who ? Why ?

GET /israel/tel-aviv/ramat-gan-1967869/ HTTP/1.1

Host: weather.yahoo.com

Accept: image/gif, application/xaml+xml, */*

Accept-Language: en-us

User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; ... )

Accept-Encoding: gzip, deflate

Connection: Keep-Alive

Cookie: BA=2139&ip=82.80.99.106&t=1258874241;

HTTP clientYahoo’s weather

web-server

HTTP request

GET http://weather.yahoo.com/israel/tel-aviv/ramat-gan-1967869/

Page 10: REST and JAX-RS

10

HTTP request overview

What ? Who ? Why ?

HTTP/1.1 200 OK

Connection: close

Content-Type: text/html;charset=utf-8

Cache-Control: private

Content-Length: 69947

Date: Sun, 22 Nov 2009 07:59:11 GMT

Set-Cooie: t=164531234;

HTTP clientYahoo’s weather

web-server

HTTP request

RESPONSE CODE: 200 (OK) + BODY

Page 11: REST and JAX-RS

11

HTTP request overview

What ? Who ? Why ?

HTTP/1.1 200 OK

Connection: close

Content-Type: text/html;charset=utf-8

Cache-Control: private

Content-Length: 69947

Date: Sun, 22 Nov 2009 07:59:11 GMT

Set-Cooie: t=164531234;

HTTP clientYahoo’s weather

web-server

HTTP request

RESPONSE CODE: 200 (OK) + BODY

Page 12: REST and JAX-RS

12

HTTP request overview

What ? Who ? Why ?

HTTP/1.1 200 OK

Connection: close

Content-Type: text/html;charset=utf-8

Cache-Control: private

Content-Length: 69947

Date: Sun, 22 Nov 2009 07:59:11 GMT

Set-Cooie: t=164531234;

HTTP clientYahoo’s weather

web-server

HTTP request

RESPONSE CODE: 200 (OK) + BODY

Page 13: REST and JAX-RS

13

HTTP request overview

What ? Who ? Why ?

HTTP/1.1 200 OK

Connection: close

Content-Type: text/html;charset=utf-8

Cache-Control: private

Content-Length: 69947

Date: Sun, 22 Nov 2009 07:59:11 GMT

Set-Cooie: t=164531234;

HTTP clientYahoo’s weather

web-server

HTTP request

RESPONSE CODE: 200 (OK) + BODY

Page 14: REST and JAX-RS

14

» A resource is …

A network-accessible data object or service identified by an URI (IRI

[1] ):

• Images,

• Documents (HTML, PDF, …),

• Geo-location,

• Weather

Everything is a resource …

What ? Who ? Why ?

[1] Section 3, Atom Publishing Protocol

Page 15: REST and JAX-RS

15

What ? Who ? Why ?

[1] Section 3, Atom Publishing Protocol

Resources:

» Collections

http://portal/bicycles/

» Members/Items:

http://portal/documents/mydog.doc

Page 16: REST and JAX-RS

16

Method REST Operation Description

POST

GET

PUT

DELETE

HEAD

OPTIONS

TRACE

CONNECT

HTTP defines more than just ‘GET’ and ‘POST’:

What ? Who ? Why ?

Method REST Operation Description

POST CREATE (INSERT) Create or update

GET READ (QUERY) Query about the resource

PUT UPDATE (CHANGE) Update

DELETE DELETE (DELETE) I want to delete what-ever-it-is ….

HEAD I’m something like ‘GET’ [1]

OPTIONS JAX-RS mumbles something about me.

TRACE

CONNECT

[1] Unique extension of JAX-RS.

Page 17: REST and JAX-RS

17

» Free of any platform or language,

» Free of any schema or protocol (beyond that of HTTP),

» No ALP (Application- or Presentation- layer Protocol) coercion

» Only a set of recommendations [1]

!

Roy Fielding defines REST as:

What ? Who ? Why ?

[1] Principled Design of the Modern Web Architecture - Roy T. Fielding, Richard N. Taylor - section 4.

Page 18: REST and JAX-RS

18

» REST recommends using URIs instead of query-based URLs:

Don’t use: http://host.com/service?type=weather&when=today

Use:

http://host.com/service/weather/today

» Atom Publishing Protocol (APP).

RFC-5023 (text-only)

Some important points …

What ? Who ? Why ?

Page 19: REST and JAX-RS

19

» Architectural style, not technology !

Client/server + Request/response approach.

» Everything is a RESOURCE.

» CRUD (Create / Read / Update / Delete) …[1]

» Stateless by nature (excellent for distributed systems),

» Cacheable (naturally supported !)

» A great way to web-service !

REST is …

What ? Who ? Why ?

[1] Reference to other acronyms at Wikipedia

Page 20: REST and JAX-RS

JAX-RS

JSR-311

Page 21: REST and JAX-RS

21

» POJO-based,

» HTTP-centric,

» Format independent,

» Container independent,

» Availability as standalone and enterprise platforms.

JAX-RS goals[1]:

JAX-RS (JSR-311)

[1] JSR-311, section 1.2 - Goals

Page 22: REST and JAX-RS

22

JAX-RS (JSR-311)

JAX-RSHTTP

Page 23: REST and JAX-RS

23

JAX-RS (JSR-311)

This page is intentionally left blank

Gesture for times when we used to read books ….

Page 24: REST and JAX-RS

24

JAX-RS (JSR-311)

http://www.disney.com/muppets/...

Page 25: REST and JAX-RS

25

JAX-RS (JSR-311)

/**

* http://www.disney.com/muppets/catalog

*/

@Path("/catalog")

public class MuppetCatalogController {

}

POJO + Annotation = JAX-RS resource

Relative context

Page 26: REST and JAX-RS

26

JAX-RS (JSR-311)

/**

* http://www.disney.com/muppets/catalog

*/

@Path("/catalog")

public class MuppetCatalogController {

@GET

public String findAllCatalogItems() {

String list = ... // Compile a list of all items.

return list;

}

}

Reading the catalog

CLIENT SERVER

GET …/catalog

List all items available for sale.

Page 27: REST and JAX-RS

27

public void doGet(HttpServletRequest req,

HttpServletResponse resp) throws ... {

int muppetId;

String stringId = req.getParameter("muppetId");

if (stringId != null) {

// Hoping for no exception to occur!

muppetId = Integer.parseInt(stringId);

} else {

muppetId = ... // Use some default value …

}

Muppet muppet = findMuppet(muppetId);

generateTextualOutput(muppet, resp.getWriter());

}

JAX-RS (JSR-311)

Reading the catalog

CLIENT SERVER

GET …/catalog?muppetId=650

Properties of Kermit

Page 28: REST and JAX-RS

28

@GET

@Path(“/catalog/{muppetId}”)

public String findItem(@QueryParam(“muppetId”)int muppedId) {

Muppet muppet = findMuppet(muppetId);

return ...

}

JAX-RS (JSR-311)

URI template

CLIENT SERVER

GET …/catalog?muppetId=650

Properties of Kermit

Page 29: REST and JAX-RS

29

@GET

@Path(“/catalog/{muppetId}”)

public String findItem(@DefaultValue(“0”)

@QueryParam(“muppetId”)int muppedId) {

Muppet muppet = findMuppet(muppetId);

return ...

}

JAX-RS (JSR-311)

URI template

CLIENT SERVER

GET …/catalog?muppetId=650

Properties of Kermit

Page 30: REST and JAX-RS

30

@GET

@Path(“/catalog/{muppetId}”)

public String findItem(@PathParam(“muppetId”)int muppedId) {

// ... Do something

}

JAX-RS (JSR-311)

URI template

CLIENT SERVER

GET …/catalog/650

Properties of Kermit

Page 31: REST and JAX-RS

31

@GET

@Path(“/catalog/{muppetId:[0-9]+}”)

public String findItem(@PathParam(“muppetId”)int muppedId) {

// ... Do something

}

JAX-RS (JSR-311)

URI template

CLIENT SERVER

GET …/catalog/650

Properties of Kermit

Regular expression

Page 32: REST and JAX-RS

32

@GET

@Path(“/catalog/{muppetId:[0-9]+}”)

public String findItem(@PathParam(“muppetId”)int muppedId) {

// ... Do something

}

// ACCEPT: http://.../catalog/-477

@GET

@Path(“/catalog/{muppetId:-[0-9]+}”)

public String findItem2(@PathParam(“muppetId”)int muppedId) {

// ... Do something

}

JAX-RS (JSR-311)

URI template

CLIENT SERVER

GET …/catalog/650

Properties of Kermit

Page 33: REST and JAX-RS

33

Cookies, headers and friends …

JAX-RS (JSR-311)

SERVERPublic client

Internal CRM client

http://www.disney.com

http://crm.intranet

Internet

Intranet

GET /muppet/catalog HTTP/1.1

host: crm.intranet

accept: text/plain

User-Agent: Mozilla/4.0 (...)

Cookie: user-type=ADMIN

Cookie

Page 34: REST and JAX-RS

34

Cookies, headers and friends …

JAX-RS (JSR-311)

@PUT

@Path("/catalog/{muppetId}/{propertyName}")

public void updateItem(

@HeaderParam("host") String hostname,

@CookieParam("user-type") UserType type, ...) {

if (!hostname.equals("crm.intranet")) { throw ... }

if (!UserType.CUSTOMER_CARE.equals(type)) { throw ... }

// ... handle the request.

}

enum UserType { ADMIN, CUSTOMER_CARE, TECHNICAL; }

Page 35: REST and JAX-RS

35

» UriInfo

» Request

» HttpHeaders

» SecurityContext

@Context

JAX-RS (JSR-311)

public void handleRequest(

@Context UriInfo uri,

@Context SecurityContext security,

@QueryParam ("username") String username) { ... }

Page 36: REST and JAX-RS

36

Content negotiation (or: cache is always money!)

JAX-RS (JSR-311)

Page 37: REST and JAX-RS

37

JAX-RS (JSR-311)

CLIENT SERVER

GET http://..../muppets/muppetOfTheMonth/image+

Content negotiation precondition

RESPONSE:• 200 (OK) + body• 304 (Not Modified)

Page 38: REST and JAX-RS

38

Content negotiation

JAX-RS (JSR-311)

@GET

@Path("/muppetOfTheMonth/image")

public Response findMuppetOfTheMonth(

@Context UriInfo uri, @Context Request request) {

File file = locateFile(uri.getRequestUri());

EntityTag tag = calculateTag(file);

Date modified = new Date(file.lastModified());

ResponseBuilder r = request.evaluatePreconditions(modified,

tag);

// ...

}

Page 39: REST and JAX-RS

39

JAX-RS (JSR-311)

The @HEAD method

HTTP/1.1 200 OK

Content-type: text/plain

Content-length: 1024256

CLIENT SERVER

HEAD …/catalog/650/image

Page 40: REST and JAX-RS

40

JAX-RS (JSR-311)

The @HEAD method@GET

@Path("/catalog/{muppetId}/image")

public Response fetchThumbnailHeadAndBody() {

return ...;

}

@HEAD

@Path("/catalog/{muppetId}/image")

public Response fetchThumbnailHeadOnly(...) {

int size = getThumbnailSize(muppetId);

ResponseBuilder builder = Response.noContent();

builder.header("Content-length", size);

builder.header(“Is-ReadOnly", true);

return builder.build();

{

Page 41: REST and JAX-RS

41

Bridging between the two worlds ….

JAX-RS (JSR-311)

HTTP Java

MessageBodyReader

MessageBodyWriter

The Millau Viaduct bridge, part E11 highway - connecting Paris and Barcelona. The highest bridge ever

constructed.

Page 42: REST and JAX-RS

42

» Provides adaptation between the “HTTP world” and our own application domain:

MessageBodyReader,

MessageBodyWriter

Providers:

JAX-RS (JSR-311)

MessageBodyWriter

MessageBodyReader

Resource class

HTTP Request

HTTP Response

Java object

Page 43: REST and JAX-RS

43

JAX-RS (JSR-311)

@Path("users/{id}/properties")

public class UserPropertiesResource {

@GET

@Produces(“application/json")

public User findUser(@PathParam("id") int userId) {

return userDao.getUser(userId);

{

@GET

@Produces(“application/atom+xml")

public User findUser(@PathParam("id") int userId) { ... }

@POST

public void findUser(User user) {

userDao.persist(user);

}

{

Page 44: REST and JAX-RS

44

JAX-RS (JSR-311)

@Provider

@Produces("application/json")

public class JSONWriter implements MessageBodyWriter<User> {

@Override

public long getSize(User user, ...) {

return JSON.toString(user).length();

{

@Override

public boolean isWriteable(java.lang.Class<?> type, ...) {

return User.class.equals(type);

{

@Override

public void writeTo(User user, ... OutputStream out) {

JSON.write(user, out);

{

@Path("users/{id}/properties")

public class UserPropertiesResource {

@GET

@Produces(“application/json")

public User findUser(@PathParam("id") int userId) {

// ...

{

@POST

public void findUser(User user) {

// ...

}

{

Page 45: REST and JAX-RS

45

Page 46: REST and JAX-RS

46

» Glassfish Jersey project (Sun Microsystems), https://jersey.dev.java.net/

» RESTEasy (JBoss), http://www.jboss.org/resteasy/

» Apache CXF (Apache Software Foundation), http://cxf.apache.org/

» Wink (ASF incubation project), http://incubator.apache.org/wink/

» Restlet (Noelios Technologies). http://www.restlet.org/

Leading JAX-RS implementations

JAX-RS (JSR-311)

Page 47: REST and JAX-RS

Security

(lack of …)

Page 48: REST and JAX-RS

48

» Authentication

Who’s calling ?

» Authorization

What am I allowed to do ?

» Content delivery:

Integrity,

Confidentiality,

Authentication.

Security

Security

Page 49: REST and JAX-RS

49

» Authentication

Who’s calling ?

» Authorization

What am I allowed to do ?

» Content delivery:

Integrity,

Confidentiality,

Authentication.

Security

Security

Page 50: REST and JAX-RS

50

» Authentication

Who’s calling ?

» Authorization

What am I allowed to do ?

» Content delivery:

Integrity,

Confidentiality,

Authentication.

Security

Security

Page 51: REST and JAX-RS

Application-Level Protocols

Marshalling REST data

Page 52: REST and JAX-RS

52

» Proprietary (custom made) solution,

» Hessian binary web-service protocol (Caucho),

» Burlap XML-based web-service protocol (Caucho),

» Avro / Buffers protocol,

» JSON (JavaScript Object Notion),

» Protocol Buffers (by Google) ,

» Kyro (only for hard-core programmers)

Suggestions:

Content deliver

Page 53: REST and JAX-RS

53

» When we have a really simple format:

Short-message strings,

Single result objects

» Specific binary format,

Multimedia (Images, Movies, etc…),

Proprietary protocol.

» Bound to certain technology:

JAXB, DOM-based (JAXP),

Java native (binary) serialization.

Proprietary (custom made) solution

Content deliver

Page 54: REST and JAX-RS

54

» Binary, compact format.

» Very lightweight,

Extremely suitable to mobile or other limited devices.

Provide J2ME libraries.

» No external IDL or schema,

» Language independent,

» Support for compression, encryption, signatures (with partial external support).

Hessian binary web-service protocol

Content deliver

Page 55: REST and JAX-RS

55

» Minimal XML-based format,

» Very lightweight (considering XML format),

Provide J2ME libraries.

» No external IDL or schema,

» Language independent (as XML is !),

» Suffice to operate EJB –

Cell phone -> Burlap -> RESTEasy -> EJB !

Burlap XML-based web-service protocol

Content deliver

Page 56: REST and JAX-RS

56

» Part of Hadoop stack,

» Lightweight, but not as the other protocols.

» Requires schema:

Pluggable architecture to support multiple formats (JSON, XML, etc …)

» Dynamic typing (very reach with its support),

» Untagged data.

Avro serialization stack

Content deliver

Page 57: REST and JAX-RS

57

» REST is a simple WS.

» JAX-RS is a reflection of the HTTP world.

Using Java-5 annotations only.

» Lack of concrete security model.

Summary

Page 58: REST and JAX-RS

Q & A

Page 59: REST and JAX-RS

Thank you !!!

Applause now !