37
© 2010 VMware Inc. All rights reserved Building RESTful Web Services with Java Vassil Popovski ([email protected] ) Staff Engineer, R&D VMware, Inc. 10/07/2010

Building Restful Web Services with Java

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Building Restful Web Services with Java

© 2010 VMware Inc. All rights reserved

Building RESTful Web Services with JavaVassil Popovski ([email protected]) Staff Engineer, R&D

VMware, Inc.

10/07/2010

Page 2: Building Restful Web Services with Java

2

Agenda REST Principles and examples Java (JAX-RS) and REST Live Demo JAX-RS Advanced concepts

Page 3: Building Restful Web Services with Java

3

What is REST?

Page 4: Building Restful Web Services with Java

4

Page 5: Building Restful Web Services with Java

5

What is REST ? (now seriously)

Representational State Transfer Introduced in 2000 by Roy Fielding:

• in his PhD thesis (chapter 5) http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm

• Captured his interpretation of the WWW architecture

Architectural style for distributed system such as World Wide Web• Note: REST is *not* a standard, just a set of principles

Positioned as an alternative to WS-* implementations

Page 6: Building Restful Web Services with Java

6

What is REST ? (now seriously)

Page 7: Building Restful Web Services with Java

7

REST Principles (RESTful systems)

Everything is a resource• Examples: Customer, Locations, Item, List of users

Resources have identifiers• Examples: URIs for web

Uniform interfaces to access the resources• Examples: HTTP methods (GET, POST, PUT, DELETE, HEAD)

Resources have representations• Examples: XML, JSON, Binary

Link resources together• Hypermedia as the Engine of Application State (HATEOAS)

• Examples: Hyperlinks

1

2

3

4

5

Page 8: Building Restful Web Services with Java

9

Real life example

Bug tracking system (over simplified)• Bugs (summary, priority, user who reported it)

• Notes (description, user who created the note)

• Users (user name)

UML Notation:“whole-part” relationship (composition)“part” is exclusively owned by “whole”

UML Notation:One-way association

UML Notation:Generalization / inheritance

Page 9: Building Restful Web Services with Java

10

Real life example – resources and identifies

Resources:• User, Bug, Note,

• All users, All bugs, All notes for a particular bug

IdentifiersIdentifiers Notehttp://<host>/users All users

http://<host>/users/{userId} A particular user

http://<host>/bugs All bugs

http://<host>/bugs/{bugId} A particular bug

http://<host>/bugs/{bugId}/notes All notes for a particular bug

http://<host>/bugs/{bugId}/notes/{noteId} A particular note for a particular bug

1 Everything is a resource

2 Resources have identifiers

Page 10: Building Restful Web Services with Java

11

Uniform interfaces (in the context of REST)

HTTP verbs (CRUD interfaces)HTTP verb Meaning Safe? Idempotent? Cacheable?

POST Create*

GET Retrieve

PUT Update*

DELETE Delete

f(f(x)) = f(x)Does not cause side effects

(*) POST and PUT may also have other meaningsPOST – can be used for partial updates and also to add something to a resource (PASTE AFTER)PUT – can be used to create if sending the full content of the specified resource and you know the URI of the resource (PASTE OVER)

Page 11: Building Restful Web Services with Java

12

Real life example – uniform interfaces

Operation DescriptionGET http://<host>/users List all users

POST http://<host>/users Creates a new user

GET http://<host>/users/345 Retrieves a particular user

PUT http://<host>/users/345 Modifies a particular user

DELETE http://<host>/users/345 Deletes a particular user

Operation DescriptionGET http://<host>/bugs/234/notes List all notes for bug 234

POST http://<host>/bugs/234/notes Creates a new note for bug 234

[GET | PUT | DELETE] .../bugs/234/notes/34 [retrieves | modifies | deletes] note 34 in bug 234

3 Uniform interfaces to access the resources

Page 12: Building Restful Web Services with Java

13

Real life example – representations and linking resources XML representation for note:

JSON representation for bug:

GET http://localhost:9000/bugs/1/notes/1 Content-type: application/xml<Note href=“http://localhost:9000/bugs/1/notes/1"> <description>It is really broken</description> <owner>http://localhost:9000/users/1</owner></Note>

POST http://localhost:9000/bugs Content-type: application/json{ "Bug" : { "priority" : "P1", "reporter" : "http://localhost:9000/users/1", "summary" : "Something is wrong" }}

4 Resources have representations

5 Link resources together

Note: the client can request different representations using “Accept” http header

Note: the client declares what representation it sends to server with “Content-type” http header

Page 13: Building Restful Web Services with Java

14

Java and REST

Page 14: Building Restful Web Services with Java

15

JAX-RS: Java API for RESTful Web Services

JSR 311 (https://jsr311.dev.java.net/)• Current version of JAX-RS spec is 1.1

• The spec is “readable”!

• Roy Fielding is an expert group member for this JSR

• javax.ws.rs.*

JAX-RS in 1 sentence:• JAX-RS = POJOs + Annotations

JAX-RS capabilities:• Dispatch URIs to specific classes and methods that can handle requests

• Methods deal with POJOs (nicely integrates with JAXB)

• Allows to map HTTP requests to method invocations

• URI manipulation functionality

Page 15: Building Restful Web Services with Java

16

JAX-RS implementations

Jersey (reference implementation) Apache CXF (the one used in the demo) Apache Wink eXo RESTEasy Restlet Triaxrs

Page 16: Building Restful Web Services with Java

17

JAX-RS key concepts

Resource classes• Java classes that have at least one method annotated with @Path or a request method designator

(@GET, @PUT, @POST, @DELETE)

• Lifecycle: • By default a new resource class instance is created for each request

• The JSR does not restrict other implementation specific lifecycles

Resource methods• A public method of a resource class annotated with a request method designator (@GET, @PUT,

@POST, @DELETE, @OPTIONS, @HEAD)

Provider classes• Classes annotated with @Provider and implementing one or more JAX-RS interfaces:

• MessageBodyReader/MessageBodyWriter

• ExceptionMapper

• ContextResolver

• Lifecycle: • By default single instance of each provider class is instantiated for each JAX-RS application

• The JSR does not restrict other implementation specific lifecycles

Page 17: Building Restful Web Services with Java

18

JAX-RS annotations (most commonly used)

Annotation Target Description@Path Class or Method Relative path for a resource

@Consumes@Produces

Class or Method List of media types that can be consumed / produced

@GET@POST@PUT@DELETE@OPTIONS@HEAD

Method HTTP verb handled by the annotated method

@PathParam Parameter (also field, POJO method)

Value that can be extracted from URI

@Context Parameter (also field, POJO method)

Inject contextual information – UriInfo, HttpHeaders, Request, ContextResolver, etc.

Page 18: Building Restful Web Services with Java

19

JAX-RS complete example

@Path("/users")

public class UserHandler {

@GET

@Path("{id}")

@Produces("application/xml”)

public JaxbUser getUser(@PathParam("id") long id) {

...

}

Page 19: Building Restful Web Services with Java

20

JAX-RS complete example

@Path("/users")

public class UserHandler {

@GET

@Path("{id}")

@Produces("application/xml”)

public JaxbUser getUser(@PathParam("id") long id) {

...

}

Base URI path to resource

Page 20: Building Restful Web Services with Java

21

JAX-RS complete example

@Path("/users")

public class UserHandler {

@GET

@Path("{id}")

@Produces("application/xml”)

public JaxbUser getUser(@PathParam("id") long id) {

...

}

The HTTP method for getUser() method

Page 21: Building Restful Web Services with Java

22

JAX-RS complete example

@Path("/users")

public class UserHandler {

@GET

@Path("{id}")

@Produces("application/xml”)

public JaxbUser getUser(@PathParam("id") long id) {

...

}

URI path segment/parameter

Page 22: Building Restful Web Services with Java

23

JAX-RS complete example

@Path("/users")

public class UserHandler {

@GET

@Path("{id}")

@Produces("application/xml”)

public JaxbUser getUser(@PathParam("id") long id) {

...

}

GET …/users/{id}

Page 23: Building Restful Web Services with Java

24

JAX-RS complete example

@Path("/users")

public class UserHandler {

@GET

@Path("{id}")

@Produces("application/xml”)

public JaxbUser getUser(@PathParam("id") long id) {

...

}

Returned Content-Type

Page 24: Building Restful Web Services with Java

25

JAX-RS complete example

@Path("/users")

public class UserHandler {

@GET

@Path("{id}")

@Produces("application/xml”)

public JaxbUser getUser(@PathParam("id") long id) {

...

}

Injects the value of URI segment into the id

parameter

Page 25: Building Restful Web Services with Java

26

JAX-RS complete example

@Path("/users")

public class UserHandler {

@GET

@Path("{id}")

@Produces("application/xml”)

public JaxbUser getUser(@PathParam("id") long id) {

...

}

GET http://localhost:9000/users/2Content-Type: application/xml

<?xml version="1.0" encoding="UTF-8"?><User> … </User>

Page 26: Building Restful Web Services with Java

27

Page 27: Building Restful Web Services with Java

28

Demoto wake you up…

Page 28: Building Restful Web Services with Java

29

Advanced topics

Regular expressions in @Path @*Params ExceptionMapper MessageBodyReader/MessageBodyWriter

Page 29: Building Restful Web Services with Java

30

@Path and regular expression mappings

@Path(path-expression)

"{" variable-name [ ":" regular-expression ] "}“

Examples• @Path("example2/{var:.+}") matches following:

• …/example2/a

• …/example2/a/b/c

• @Path("example3/{var:\\d+}") matches following:• …/example3/345

• …/example3/23

• @Path(“example4/{name}-{id}”) matches following:• …/example4/a-1• …/example4/a----1

Page 30: Building Restful Web Services with Java

31

@[Query|Header|Matrix|Cookie|Form]Param @QueryParam

• For example …/query?sorted=true@GET@Path("query")public String queryParamExample(@QueryParam(“sorted") String var) {return var;

}

@MartixParam• For example …/users;sorted=true

@HeaderParam• For example “Date” header

@CookieParam / @FormParam

@DefaultValue – can be used with any @*Param to specify the default value

Page 31: Building Restful Web Services with Java

32

Exception Mappers

package javax.ws.rs.ext

public interface ExceptionMapper<E extends Throwable> {

Response toResponse(E exception);

}

Page 32: Building Restful Web Services with Java

33

MessageBodyReader

MessageBodyReader MessageBodyWriter

package javax.ws.rs.ext

public interface MessageBodyReader<T> {

boolean isReadable(Class<?> type, Type genericType,

Annotation annotations[], MediaType mediaType);

T readFrom(Class<T> type, Type genericType,

Annotation annotations[], MediaType mediaType,

MultivaluedMap<String, String> httpHeaders,

InputStream entityStream) throws IOException, WebApplicationException;

}

Page 33: Building Restful Web Services with Java

34

MessageBodyWriter

package javax.ws.rs.ext

public interface MessageBodyWriter<T> {

boolean isWriteable(Class<?> type, Type genericType,

Annotation annotations[], MediaType mediaType);

long getSize(T t, Class<?> type, Type genericType, Annotation annotations[],

MediaType mediaType);

void writeTo(T t, Class<?> type, Type genericType, Annotation annotations[],

MediaType mediaType,

MultivaluedMap<String, Object> httpHeaders,

OutputStream entityStream) throws IOException, WebApplicationException;

}

Page 34: Building Restful Web Services with Java

35

JAX-RS features that were not covered PathSegment @Encoded @ApplicationPath Cookies Complex negotiation / Variant processing (javax.ws.rs.core.Variant): @OPTIONS, @HEAD, @HttpMethod SecurityContext CacheControl (+ Etags, conditional GET/PUT) Application (+ how to deploy in servlet container, EE6, EJB) Integration with Spring Security

Page 35: Building Restful Web Services with Java

36

Several other topics not covered

Restful java clients WADL REST support in Spring 3.0

Page 36: Building Restful Web Services with Java

37

Additional materials

Apache CXF (JAX-RS part): http://cxf.apache.org/docs/jax-rs.html RESTEasy users guide:

http://docs.jboss.org/resteasy/docs/1.1.GA/userguide/pdf/RESTEasy_Reference_Guide.pdf

WizTools REST Client: http://code.google.com/p/rest-client/

Page 37: Building Restful Web Services with Java

38