Title: Designing and Implementing RESTful Web Services with JAXRS
1Designing and Implementing RESTful Web Services
with JAX-RS
Eben HewittBangaloreNovember 3-4, 2009
2goals
- Understand principles of REST
- Survey RESTful tools and protocols
- Learn how to implement RESTful services with
JAX-RS
3who i am
- Architect at a multi-billion dollar, 50 year-old
US retailer - Speaker on SOA at JavaOne, others
- Interviewed on SOA by InfoQ
- Author of 5 books including Java SOA Cookbook
(OReilly, 2009) - Contributor to 97 Things Every Software Architect
Should Know (OReilly, 2009) - Other contributors include Gregor Hohpe, Bill de
hÓra, Neal Ford, editor Richard Monson-Haefel. - Many certifications in Java, Web Services, TOGAF
- I kitties
4REST Overview
- REpresentational State Transfer
- http//www.ics.uci.edu/fielding/pubs/dissertation
/top.htm (Fielding, 2000) - Web Architecture
- Components user agent, intermediary, server,
browser, spider, gateway - Connectors HTTP, HTTPS, FTP
- Data URI referring to HTML, XML, RSS
5REST is an architectural style
- WWW is based on these principles
- Starting from the null style, a set of
constraints - Separation of Concerns
- Statelessness
- Scalability
- Cacheable
- Reduce latency, reduce payload
- Uniform Interface
- Decouples, improves visibility, independently
evolve - Information Hiding
- Simplified clients, legacy encapsulation, load
balancing - Allow Code-on-Demand
- Applets, JavaScript
6REST in a Nutshell
- REST services are built around Resources
- REST services are Stateless
- REST uses a Uniform Interface
- Resources are manipulated through Representations
- Messages are Self-Describing
- Hypermedia As The Engine Of Application State
7Uniform Resources
- Resources are domain interests
- Universal Semantics
- Operations mean the same thing for every resource
(GET, DELETE) - All Resources are identified by a single
mechanism (URI) - Manipulate resources by exchanging Representations
8Uniform Methods
- URI is sufficient for working with resources
- Dont need a separate Resource Description
Language - Intermediaries can take advantage of caching, can
better anticipate behavior
9Hypermedia as the Engine of Application State
- Responses are Representations
- They carry or point to current state of
application - They may contain links to transition to a new
state - No application state is kept on the server
- Hypertext doesnt need to be HTML in a browser
10REST Noun (Resource) Oriented
- About resources
- The operations are standard via HTTP
- Resources can be cached, bookmarked, saved via
standard mechanisms - Customer
- http//example.com/customer/123
- http//example.com/order/555/customer
- POST, GET, DELETE
11The Tipping Point
- March 1, 2005 Yahoo! Launches REST API
- On December 5, 2006, Google stopped accepting new
signups for SOAPSearch - Public REST APIs
12Atom vs RSS
- Atom intended as a replacement for RSS, published
under IETF - Clarify ambiguities
- Unify
- Extend capabilities
13- https//rome.dev.java.net
- Make it easy to work with RSS and Atom in Java
- Includes parsers and generators for a variety of
feeds - Get Java objects representing specific feed types
- Or, work normalized objects (SyndFeed)
14Root Representations
- Publish a well-known root representation
- Dont require extensive documentation
- Let clients discover all others from this root
(like index.html) - Adds clarity for client-side library author
- Ensures only valid state transitions
- Cant Check Order until you have placed it
15JAX-RS
- Java API for RESTful Web Services
- Helps developers quickly write RESTful
applications - API Expressed in Annotations
- To become part of Java EE 6
16REST and SOAP
- With REST, the semantics are specified entirely
by the URI - The SOAP envelope is the beginning
- Its the extension point for a variety of specs
(addressing, security, transactions, MTOM, WS-RM)
- With REST, the URI is the end
17Orientation
- SOAP oriented around verbs
- (RPC, actions)
- REST oriented around nouns
- Resources
18SOAP Verb (Operation) Oriented
- A SOAP interface defines verb/noun combinations,
after RPC - Its about a variety of operations
- addCustomer
- updateCustomerAddress
- getCustomer
19JAX-RS
20Resources
- In JAX-RS, a Resource is a POJO
- No interface to implement
- Just express the matching URI
- _at_Path
- The value is a relative path
- The base URI is provided by the either
- Deployment Context
- Parent Resource
21JAX-RS Methods
- If your method returns void, JAX-RS returns a 204
(successfully processed, no message body) - Automatic encoding
- _at_Path("product list") is identical to
_at_Path("product20list).
22HTTP Methods
23Hello Jersey!
- import javax.ws.rs.Path
- import javax.ws.rs.GET
- import javax.ws.rs.ProduceMime
- _at_Path("/helloRest")
- public class HelloRest
- _at_GET
- _at_ProduceMime("text/html")
- public String sayHello()
- return "lthtmlgtltbodygtlth1gtHello from
Jersey!lt/bodygtlt/h1gtlt/htmlgt" -
24Modify web.xml to Use Adapter Servlet
- ltweb-app version"2.5" xmlns"http//java.sun.com/
xml/ns/javaee" - xmlnsxsi"http//www.w3.org/2001/XMLSchema-instan
ce" - xsischemaLocation"http//java.sun.com/xml/ns/jav
aee - http//java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
gt - ltservletgt
- ltservlet-namegtServletAdaptorlt/servlet-namegt
- ltservlet-classgt
- com.sun.jersey.spi.container.servlet.ServletContai
ner - lt/servlet-classgt
- ltload-on-startupgt1lt/load-on-startupgt
- lt/servletgt
- ltservlet-mappinggt
- ltservlet-namegtServletAdaptorlt/servlet-namegt
- lturl-patterngt/resources/lt/url-patterngt
- lt/servlet-mappinggt
25Uniform Interface
- Annotate methods
- _at_GET, _at_PUT, _at_POST, _at_DELETE, _at_HEAD
- JAX-RS forwards to correct method based on
request method
26URI Templates
- At class level, assign a Root Resource with _at_Path
- Dynamic resources assigned using
_at_PathParam(paramName) - Can use Regular Expressions to match
- _at_Path("products/ida-zA-Za-zA-Z_0-9"
- Non-matches return 404
27URI Template Example
- _at_Path("/products/id")
- public class ProductResource
- _at_Context
- private UriInfo context
- / Creates a new instance of ProductResource /
- public ProductResource()
- _at_GET
- _at_ProduceMime("text/plain")
- public String getProduct(_at_PathParam("id") int
productId) - switch (productId)
- case 1 return "A Shiny New Bike"
- case 2 return "Big Wheel"
- case 3 return "Taser Toddler Edition"
- default return "No such product"
-
-
28Variable Resources of the Same Type
- Map path elements using _at_PathParam
-
- _at_Path(customer/name")
- public class Customer
- _at_GET
- String get(_at_PathParam("name") String name)
- _at_PUT
- Void put(_at_PathParam(name) String name, String
value)
29Regular Expressions in URI Template
- _at_Path("/products/id \\d3")
- public class ProductResource
- public ProductResource()
- _at_GET
- _at_Produces("text/plain")
- public String getProductPlainText(_at_PathParam("id")
int productId) - return "Your Product is " productId
-
-
- //constrained to 3 digits
- http//localhost8080/jrs/resources/products/555
- works
- http//localhost8080/jrs/resources/products/7
- returns 404
30Accessing Query Parameters
- Use _at_QueryParam on your method parameter
- Optionally include _at_DefaultValue
- _at_GET
- _at_Produces("text/xml")
- public String getProducts(
- _at_PathParam("id") int productId,
- _at_QueryParam("results")
- _at_DefaultValue("5") int numResults)
- ///resources/products?results3
31Accessing Request Headers
- _at_GET public String doGet(_at_Context HttpHeaders
headers) - //list all incoming headers
- MultivaluedMapltString,Stringgt h
headers.getRequestHeaders() - for (String header h.keySet())
- System.out.println(header "" h.get(header))
-
32Accessing Other Parameter Types
- _at_FormParam
- Extracts from a request representation of MIME
media type "application/x-www-form-urlencoded"
and conforms to the encoding specified by HTML
forms - _at_MatrixParam
- Extracts from URL path segments
- _at_HeaderParam
- _at_CookieParam
33Representation Formats
- Identified by media type
- text/xml, application/json
- Content negotiation is automatically handled by
JAX-RS - Annotate with _at_Produces or _at_Consumes to indicate
static content capabilities - _at_Path("/emps")
- public class EmployeeService
- _at_GET
- _at_Path("id")
- _at_Produces("application/xml")
- public Employee getEmployee(_at_PathParam("id") int
empId) - return emps.get(empId)
-
- //this example uses JAXB on the Employee POJO for
XML - _at_XmlRootElement(name"employee")
- public class Employee id, name
34Produces/Consumes
- _at_Produces
- Specify the MIME media types of representations a
resource can produce and send back to the client. - Applied at Class or Method level
- _at_Consumes
- Specify MIME media types of representations a
resource can consume that were sent by the client - Applied at Class or Method level
- One method can consume more than one media type
35Building a Response
- ResponseBuilder allows you to create a response
that contains metadata instead of, or in addition
to, an entity - String type new MimetypesFileTypeMap().getConten
tType(image) - return Response.ok(image, type).build()
36Using JAXB to Provide XML View of Java
- byte
- java.lang.String
- java.io.InputStream
- java.io.Reader
- java.io.File
- javax.activation.DataSource
- javax.xml.transform.Source
- javax.xml.bind.JAXBElement and application-supplie
d JAXB classes (used for XML media types only) - MultivaluedMapltString, Stringgt for form content
only (application/x-www-formurlencoded) - StreamingOutput
37Different Representations of a Resource
- Typical HTTP Accept Request Header
- Accept text/html,application/xhtmlxml,applicatio
n/xmlq0.9,/q0.8 - Use HTTP Commons Client library
- private static void getXml()
- HttpClient client new HttpClient()
- GetMethod get new GetMethod(RESOURCE_URL)
- get.setRequestHeader("Accept", "text/xml")
- try
- int httpStatus client.executeMethod(get)
- if (HttpStatus.SC_OK httpStatus)
- String xmlResponse get.getResponseBodyAsSt
ring() - System.out.println("Xml Response "
xmlResponse) - //
38Responses
- UriInfo get information about deployment
context, request URI and the route to the
resource - UriBuilder helps you construct resource URIs
39Getting a Parameter Map with UriInfo
- _at_GET public String get(
- _at_Context UriInfo ui)
- MultivaluedMapltString, Stringgt q
ui.getQueryParameters() - MultivaluedMapltString, Stringgt p
ui.getPathParameters()
40UriBuilder
- Makes it easy to build new URIs or from scratch.
- Methods to work with all parts of URI Path,
Fragment, Matrix Param, query param, scheme - To create sitefaq
- UriBuilder.fromPath("arg1").fragment(
- "arg2").build(site", faq")
41Adding Metadata to Responses
- Response response Response.noContent()
- .header("MY_KEY", "MY_VALUE")
- .cacheControl(cacheCtl)
- .expires(expy)
- .language(Locale.ENGLISH)
- .type(MediaType.TEXT_HTML)
- .build()
- HTTP/1.1 204 No Content
- Server Apache-Coyote/1.1
- Cache-Control no-store, no-transform,
must-revalidate, max-age500 - Expires Sat, 10 Oct 2009 164149 GMT
- MY_KEY MY_VALUE
- Content-Language en
- Date Sat, 08 Nov 2008 164149 GMT
42Security
- Available via the SecurityContext from _at_Context
- Same as security in HttpServletRequest
- _at_Path(cart")
- public ShoppingBasketResource get(_at_Context
SecurityContext sc) - if(sc.isUserInRole(GoldMember")
- //
43Implementations
- Jersey
- Restlet
- JBoss RESTEasy
- Apache CXF
- Triaxrs
- Apache Wink
44thank you