Date post: | 10-May-2015 |
Category: |
Technology |
Upload: | guy-nir |
View: | 8,288 times |
Download: | 0 times |
JAX-RS… and the REST will follow
Guy Nir
2
» REST – What ? Who ? Why ?
» JAX-RS (JSR-311) - Digg’n in
» Security
» Application-Level Protocol
» Summary
Agenda
What ? Who ? Why ?
… and how
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
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).
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/
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/
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/
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/
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
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
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
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
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
15
What ? Who ? Why ?
[1] Section 3, Atom Publishing Protocol
Resources:
» Collections
http://portal/bicycles/
» Members/Items:
http://portal/documents/mydog.doc
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.
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.
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 ?
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
JAX-RS
JSR-311
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
22
JAX-RS (JSR-311)
JAX-RSHTTP
23
JAX-RS (JSR-311)
This page is intentionally left blank
Gesture for times when we used to read books ….
24
JAX-RS (JSR-311)
http://www.disney.com/muppets/...
25
JAX-RS (JSR-311)
/**
* http://www.disney.com/muppets/catalog
*/
@Path("/catalog")
public class MuppetCatalogController {
}
POJO + Annotation = JAX-RS resource
Relative context
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.
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
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
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
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
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
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
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
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; }
35
» UriInfo
» Request
» HttpHeaders
» SecurityContext
@Context
JAX-RS (JSR-311)
public void handleRequest(
@Context UriInfo uri,
@Context SecurityContext security,
@QueryParam ("username") String username) { ... }
36
Content negotiation (or: cache is always money!)
JAX-RS (JSR-311)
37
JAX-RS (JSR-311)
CLIENT SERVER
GET http://..../muppets/muppetOfTheMonth/image+
Content negotiation precondition
RESPONSE:• 200 (OK) + body• 304 (Not Modified)
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);
// ...
}
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
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();
{
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.
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
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);
}
{
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) {
// ...
}
{
45
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)
Security
(lack of …)
48
» Authentication
Who’s calling ?
» Authorization
What am I allowed to do ?
» Content delivery:
Integrity,
Confidentiality,
Authentication.
Security
Security
49
» Authentication
Who’s calling ?
» Authorization
What am I allowed to do ?
» Content delivery:
Integrity,
Confidentiality,
Authentication.
Security
Security
50
» Authentication
Who’s calling ?
» Authorization
What am I allowed to do ?
» Content delivery:
Integrity,
Confidentiality,
Authentication.
Security
Security
Application-Level Protocols
Marshalling REST data
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
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
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
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
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
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
Q & A
Thank you !!!
Applause now !