4. What ? Who ? Why ?
Architectural overview
GET http://weather.yahoo.com/israel/tel-aviv/ramat-gan-1967869/
HTTP request
Yahoo’s weather
HTTP client web-server
HTTP response
RESPONSE CODE: 200 (OK) + BODY
4
5. What ? Who ? Why ?
Architectural overview
GET http://weather.yahoo.com/israel/tel-aviv/ramat-gan-1967869/
Read, The weather in Israel at Tel-Aviv area
(Ramat Gan).
5
10. What ? Who ? Why ?
HTTP request overview
HTTP request Yahoo’s weather
HTTP client web-server
RESPONSE CODE: 200 (OK) + BODY
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;
10
11. What ? Who ? Why ?
HTTP request overview
HTTP request Yahoo’s weather
HTTP client web-server
RESPONSE CODE: 200 (OK) + BODY
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;
11
12. What ? Who ? Why ?
HTTP request overview
HTTP request Yahoo’s weather
HTTP client web-server
RESPONSE CODE: 200 (OK) + BODY
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;
12
13. What ? Who ? Why ?
HTTP request overview
HTTP request Yahoo’s weather
HTTP client web-server
RESPONSE CODE: 200 (OK) + BODY
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;
13
14. What ? Who ? Why ?
Everything is a resource …
» A resource is …
A network-accessible data
object or service identified by
[1]
an URI (IRI ):
• Images,
• Documents (HTML, PDF, …),
• Geo-location,
• Weather
[1] Section 3, Atom Publishing Protocol
14
15. What ? Who ? Why ?
Resources:
» Collections
http://portal/bicycles/
» Members/Items:
http://portal/documents/mydog.doc
[1] Section 3, Atom Publishing Protocol
15
16. What ? Who ? Why ?
HTTP defines more than just ‘GET’ and ‘POST’:
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.
16
17. What ? Who ? Why ?
Roy Fielding defines REST as:
» Free of any platform or language,
» Free of any schema or protocol (beyond that of HTTP),
» No ALP (Application- or Presentation- layer Protocol)
coercion
[1]
» Only a set of recommendations !
[1] Principled Design of the Modern Web Architecture - Roy T. Fielding, Richard N. Taylor - section 4.
17
18. What ? Who ? Why ?
Some important points …
» 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)
18
19. What ? Who ? Why ?
REST is …
» 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 !
[1] Reference to other acronyms at Wikipedia
19
26. JAX-RS (JSR-311)
Reading the catalog
GET …/catalog
CLIENT SERVER
List all items available for sale.
/**
* 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;
}
}
26
27. JAX-RS (JSR-311)
Reading the catalog
GET …/catalog?muppetId=650
CLIENT SERVER
Properties of Kermit
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());
}
27
28. JAX-RS (JSR-311)
URI template
GET …/catalog?muppetId=650
CLIENT SERVER
Properties of Kermit
@GET
@Path(“/catalog/{muppetId}”)
public String findItem(@QueryParam(“muppetId”)int muppedId) {
Muppet muppet = findMuppet(muppetId);
return ...
}
28
29. JAX-RS (JSR-311)
URI template
GET …/catalog?muppetId=650
CLIENT SERVER
Properties of Kermit
@GET
@Path(“/catalog/{muppetId}”)
public String findItem(@DefaultValue(“0”)
@QueryParam(“muppetId”)int muppedId) {
Muppet muppet = findMuppet(muppetId);
return ...
}
29
30. JAX-RS (JSR-311)
URI template
GET …/catalog/650
CLIENT SERVER
Properties of Kermit
@GET
@Path(“/catalog/{muppetId}”)
public String findItem(@PathParam(“muppetId”)int muppedId) {
// ... Do something
}
30
31. JAX-RS (JSR-311)
URI template
GET …/catalog/650
CLIENT SERVER
Properties of Kermit
@GET Regular expression
@Path(“/catalog/{muppetId:[0-9]+}”)
public String findItem(@PathParam(“muppetId”)int muppedId) {
// ... Do something
}
31
32. JAX-RS (JSR-311)
URI template
GET …/catalog/650
CLIENT SERVER
Properties of Kermit
@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
}
32
33. JAX-RS (JSR-311)
Cookies, headers and friends …
Internet
http://www.disney.com
Public
SERVER
client
Intranet
GET /muppet/catalog HTTP/1.1
host: crm.intranet http://crm.intranet
accept: text/plain
User-Agent: Mozilla/4.0 (...) Internal
CRM
Cookie: user-type=ADMIN client
Cookie
33
34. JAX-RS (JSR-311)
Cookies, headers and friends …
@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; }
34
37. JAX-RS (JSR-311)
CLIENT SERVER
GET http://..../muppets/muppetOfTheMonth/image
+
Content negotiation precondition
RESPONSE:
• 200 (OK) + body
• 304 (Not Modified)
37
38. JAX-RS (JSR-311)
Content negotiation
@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);
// ...
}
38
39. JAX-RS (JSR-311)
The @HEAD method
HEAD …/catalog/650/image
CLIENT SERVER
HTTP/1.1 200 OK
Content-type: text/plain
Content-length: 1024256
39
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();
{
40
41. JAX-RS (JSR-311)
Bridging between the two worlds ….
HTTP Java
MessageBodyReader
MessageBodyWriter
The Millau Viaduct bridge, part E11 highway - connecting Paris and Barcelona. The highest bridge ever
constructed.
41
42. JAX-RS (JSR-311)
Providers:
» Provides adaptation between the “HTTP world” and
our own application domain:
MessageBodyReader,
MessageBodyWriter
Java object
HTTP Request
MessageBodyReader
Resource class
MessageBodyWriter
HTTP Response
42
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);
}
{
43
44. JAX-RS (JSR-311)
@Provider
@Path("users/{id}/properties")
@Produces("application/json")
public classclass UserPropertiesResource {
public JSONWriter implements MessageBodyWriter<User> {
@Override@GET
@Produces(“application/json")
public long getSize(User user, ...) {
public User findUser(@PathParam("id") int userId) {
return JSON.toString(user).length();
{ // ...
{
@Override
@POST
public boolean isWriteable(java.lang.Class<?> type, ...) {
return User.class.equals(type);user) {
public void findUser(User
{ // ...
}
{
@Override
public void writeTo(User user, ... OutputStream out) {
JSON.write(user, out);
{
44
53. Content deliver
Proprietary (custom made) solution
» 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.
53
54. Content deliver
Hessian binary web-service protocol
» 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).
54
55. Content deliver
Burlap XML-based web-service protocol
» 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 !
55
56. Content deliver
Avro serialization stack
» 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.
56
57. Summary
» REST is a simple WS.
» JAX-RS is a reflection of the HTTP world.
Using Java-5 annotations only.
» Lack of concrete security model.
57