4. The Basic Operations
CRUD (Create, Read, Update, Delete)
Performed atomically on one uniquely identified
asset or a set of assets
5. REST with HTTP
REST verbs apply directly to HTTP methods
GET - READ
o nus!
B
POST - CREATE
ONS
PUT - UPDATE
OPTI
AD
DELETE
HE
Encoded in JSON or XML
RA CE
T
6. REST HTTP Example
Widget Registry at http:/
/server/widgets
Create a Widget (Bolt, weighs 10g)
POST /widgets HTTP/1.1 200 OK
Host: server Date: Wed, 15 Dec 2010 23:59:59 GMT
User-agent: Ted’s Presentation Content-Type: text/plain
Content-type: Application/JSON Transfer-Encoding: chunked
Content-length: 115
{
{ newAssetId: 15
widget : { }
type : ‘bolt’,
weight : {
amount : 10,
unit : ‘grams’
} Alternatively, could redirect to new
}
} asset with Location header
7. Another HTTP Example
Widget Registry at http:/
/server/widgets
Get Widget from last slide (ID 15 )
GET /widgets/15 HTTP/1.1 200 OK
Host: server Date: Wed, 15 Dec 2010 23:59:59 GMT
User-agent: Ted’s Presentation Content-Type: text/plain
Transfer-Encoding: chunked
Content-length: 135
{
widget : {
id : 15,
type : ‘bolt’,
weight : {
Also available in browser at amount : 10,
unit : ‘grams’
http:/
/server/widgets/15
}
}
}
8. Final HTTP Example
Widget Registry at http:/
/server/widgets
Update Widget previously created
PUT /widgets/15 HTTP/1.1 200 OK
Host: server Date: Wed, 15 Dec 2010 23:59:59 GMT
User-agent: Ted’s Presentation Content-Type: text/plain
Content-type: Application/JSON Transfer-Encoding: chunked
Content-length: 134
{
widget : {
id : 15,
(weight was actually 1 gram, typo)
type : ‘bolt’,
weight : {
amount : 10,
unit : ‘grams’
}
}
}
9. What We Just Saw
REST is resource-oriented
Assets are identified with URLs
The HTTP method specifies the operation
10. So What?
Putting the important information (what, how)
at the HTTP protocol-level allows
intermediaries to act and advise
Increased scalability and lower costs
13. Provider Intermediaries
Caching reverse-proxies and CDNs
Message remediation / translation
Security (eg XSRF nonces)
Also, protocol-level load balancing / failover
Should be invisible to client
14. Safety
Data retrieval methods are considered safe
Should not alter application data
GET / HEAD / OPTIONS / TRACE
Highly Cacheable by intermediaries!
15. Idempotency
Methods that may be executed more than once
with the same result are idempotent
PUT / DELETE
All safe methods are idempotent
POST is not always idempotent
16. Enter JAX-RS
Abstract specification for tagging resource
endpoints and operations in Java code
Annotation-driven
Exposes results of method calls in the same
way JAX-WS or Spring-WS does
17. Using JAX-RS
Providers implement it (like JPA)
Provider agnostic ; can easily switch (unlike JPA)
Jersey is the reference implementation
Can couple with message marshallers/unmarshallers
Most rely on JAXB, even for JSON
18. JAX-RS Annotations
The litany found in the javax.ws.rs package...
@Path(“/path”)
@GET / @POST / @PUT / @DELETE /etc
@Produces + @Consumes(“text/plain”)
@PathParam + @HeaderParam + @QueryParam
19. Creating a Time Service
http:/
/yourserver/context/time
@Path("/time")
public class TimeJaxRsResource {
@GET
@Produces("text/plain")
public String getCurrentTime() {
return new Date().toString();
}
}
20. Using Paths
http:/
/yourserver/context/time/eastern
@Path("/time")
public class TimeJaxRsResource {
@GET
@Path("/eastern")
@Produces("text/plain")
public String getCurrentEasternTime() {
DateFormat format = new SimpleDateFormat();
TimeZone eastern = TimeZone.getTimeZone(
"America/New_York");
format.setTimeZone(eastern);
return format.format(new Date());
}
}
21. Using Path Variables
http:/
/yourserver/context/time/tz/America_Chicago
@Path("/time")
public class TimeJaxRsResource {
@GET
@Path("/tz/{timezone}")
@Produces("text/plain")
public String getTime(@PathParam ("timezone") String tz) {
DateFormat format = new SimpleDateFormat();
TimeZone timezone = TimeZone.getTimeZone(tz);
format.setTimeZone(timezone);
return format.format(new Date());
}
}
23. Message Marshalling
JSON to marshall/unmarshall messages
Most commonly used: Jackson
Create a file containing in the following
org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider
META-INF/services/javax.ws.rs.ext.MessageBodyReader
META-INF/services/javax.ws.rs.ext.MessageBodyWriter
24. Example : Prime Numbers
Prime number generation is computationally
expensive but fairly simple
Worker thread(s) generate prime numbers
A web UI shows the latest additions
http:/
/primes.tedpennings.com/
25. The Prime Algorithm
long x, y;
for (x = start; x < Long.MAX_VALUE; x++) {
if (x % 2 != 0 || x == 2) {
for (y = 2; y <= x / 2; y++) {
if (x % y == 0) {
break;
}
}
if (y > x / 2) {
System.out.println("Discovered prime: " + x);
repo.add(x);
}
}
}
26. The Workers
Stateless loop of code trying to identify primes
Add to MongoDB once found
Simple JAR distributed to workers
Currently, only one; possibility for more
27. The App
Methods to find the most recent number and
batches of numbers greater than X
Exposed over RESTful HTTP with JSON
Runs in Jetty, fronted by an intermediary
http:/
/primes.tedpennings.com/primes/since/13183229
28. Example Code - Service
http:/
/prime.tedpennings.com/primes/since/1500
@Path("/")
public class PrimeJaxRsResource {
private final MongoPrimeRepository repo = new MongoPrimeRepository();
@GET
@Path("/since/{since}")
@Produces("application/json")
public Set<Long> getPrimesSince(@PathParam("since") long since) {
LOG.info("Showing the default number of primes since " + since);
return repo.getPrimes(since);
}
}
30. The Web UI
Periodical Ajax requests for the numbers since the
most recent request (asynchronously)
Does not require full batches
Size varies based on complexity + worker speed
All JavaScript, with jQuery
31. Demo and Code
Demo and Code Walkthrough
http:/
/primes.tedpennings.com
http:/
/s3.tedpennings.com/prime-jaxrs.zip
32. Possible Follow-up
Use some kind of MapReduce to distribute
workload across multiple workers (Hadoop?)
Use Chef or Puppet to dynamically provision
workers and initialize application
33. Resources (haha)
Roy Fielding’s Thesis http:/
/www.ics.uci.edu/~fielding/pubs/dissertation/top.htm
Jersey site http:/
/jersey.java.net
Wikipedia (surprisingly good for this)
This awesome font : http:/
/www.dafont.com/hand-of-sean.font