Your SlideShare is downloading. ×
0
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Introduction to REST and JAX-RS
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Introduction to REST and JAX-RS

2,379

Published on

An introduction to the architectural style REST and an overview of implementing an application in JAX-RS, the JSR-311 Java REST API.

An introduction to the architectural style REST and an overview of implementing an application in JAX-RS, the JSR-311 Java REST API.

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,379
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
48
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Java REST in Practice Asynchronous JAX-RS Ted Pennings 16 December 2010
  • 2. REST OverviewREST is an architectural style Client - Server Most often over HTTP with JSON or XMLDescribes the location of resources + actions
  • 3. REST PrinciplesResource-basedStatelessCacheableLayered, with optional intermediariesSafety / Idempotency
  • 4. The Basic OperationsCRUD (Create, Read, Update, Delete)Performed atomically on one uniquely identifiedasset or a set of assets
  • 5. REST with HTTPREST verbs apply directly to HTTP methods GET - READ o nus! B POST - CREATE ONS PUT - UPDATE OPTI AD DELETE HEEncoded 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 OKHost: server Date: Wed, 15 Dec 2010 23:59:59 GMTUser-agent: Ted’s Presentation Content-Type: text/plainContent-type: Application/JSON Transfer-Encoding: chunkedContent-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 OKHost: server Date: Wed, 15 Dec 2010 23:59:59 GMTUser-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 createdPUT /widgets/15 HTTP/1.1 200 OKHost: server Date: Wed, 15 Dec 2010 23:59:59 GMTUser-agent: Ted’s Presentation Content-Type: text/plainContent-type: Application/JSON Transfer-Encoding: chunkedContent-length: 134{ widget : { id : 15, (weight was actually 1 gram, typo) type : ‘bolt’, weight : { amount : 10, unit : ‘grams’ } }}
  • 9. What We Just SawREST is resource-orientedAssets are identified with URLsThe HTTP method specifies the operation
  • 10. So What?Putting the important information (what, how)at the HTTP protocol-level allowsintermediaries to act and adviseIncreased scalability and lower costs
  • 11. IntermediariesTwo categories: - Proxies (client-chosen) - Gateways (provider-chosen)
  • 12. Client IntermediariesMostly proxiesMay or may not cacheMay alter Javascript for client safetyFirewalls (eg block NSFW + illegal content)
  • 13. Provider IntermediariesCaching reverse-proxies and CDNsMessage remediation / translationSecurity (eg XSRF nonces)Also, protocol-level load balancing / failoverShould be invisible to client
  • 14. SafetyData retrieval methods are considered safeShould not alter application dataGET / HEAD / OPTIONS / TRACEHighly Cacheable by intermediaries!
  • 15. IdempotencyMethods that may be executed more than oncewith the same result are idempotentPUT / DELETEAll safe methods are idempotentPOST is not always idempotent
  • 16. Enter JAX-RSAbstract specification for tagging resourceendpoints and operations in Java codeAnnotation-drivenExposes results of method calls in the sameway JAX-WS or Spring-WS does
  • 17. Using JAX-RSProviders implement it (like JPA) Provider agnostic ; can easily switch (unlike JPA) Jersey is the reference implementationCan couple with message marshallers/unmarshallers Most rely on JAXB, even for JSON
  • 18. JAX-RS AnnotationsThe 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 Servicehttp:/ /yourserver/context/time@Path("/time")public class TimeJaxRsResource { @GET @Produces("text/plain") public String getCurrentTime() { return new Date().toString(); }}
  • 20. Using Pathshttp:/ /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 Variableshttp:/ /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()); }}
  • 22. What We’ve CreatedStatelessUnfortunately, not useful if cachedNot necessarily asynchronous from a clientperspective (due to accuracy concerns)
  • 23. Message MarshallingJSON to marshall/unmarshall messagesMost commonly used: JacksonCreate a file containing in the followingorg.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 WorkersStateless loop of code trying to identify primesAdd to MongoDB once foundSimple JAR distributed to workersCurrently, only one; possibility for more
  • 27. The AppMethods to find the most recent number andbatches of numbers greater than XExposed over RESTful HTTP with JSONRuns in Jetty, fronted by an intermediary http:/ /primes.tedpennings.com/primes/since/13183229
  • 28. Example Code - Servicehttp:/ /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); }}
  • 29. The IntermediaryNginx reverse-proxying Jetty (same node)Caches all GET operations
  • 30. The Web UIPeriodical Ajax requests for the numbers since themost recent request (asynchronously)Does not require full batches Size varies based on complexity + worker speedAll JavaScript, with jQuery
  • 31. Demo and CodeDemo and Code Walkthroughhttp:/ /primes.tedpennings.comhttp:/ /s3.tedpennings.com/prime-jaxrs.zip
  • 32. Possible Follow-upUse some kind of MapReduce to distributeworkload across multiple workers (Hadoop?)Use Chef or Puppet to dynamically provisionworkers and initialize application
  • 33. Resources (haha)Roy Fielding’s Thesis http:/ /www.ics.uci.edu/~fielding/pubs/dissertation/top.htmJersey site http:/ /jersey.java.netWikipedia (surprisingly good for this)This awesome font : http:/ /www.dafont.com/hand-of-sean.font
  • 34. Contacthttp:/ /ted.pennin.gs / ted@pennin.gstwitter: @thesleepyvegan

×