SlideShare une entreprise Scribd logo
1  sur  90
Télécharger pour lire hors ligne
REST and Jersey Introduction



             Chris Winters
      Pittsburgh Java User Group
              21 April 2009




                   
Did you update the URLs?




    (slide 13: update with IP so people can access)




                            
Anyone want to vent?




              
Who am I?
       http://www.cwinters.com/ (not the male model)
       Dad of awesome two year­old
       Software Architect at Vocollect Healthcare Systems
       Most experience on very small teams
       AccuNurse: voice­assisted care for nursing homes
       We use many, many opensource libraries
       Not a REST expert, just very interested

                                 
REST
       Representational State Transfer
       Defined in Roy Fielding dissertation
       One primary implementation to­date: web + HTTP
       Why the interest?
       Web: ubiquitous, scalable, enabling platform




                                 
HTTP Success
       Text­based!
       Simple!
       Universal!
       Clients and servers aren't tightly bound




                                  
HTTP Success, Deeper
       Supports very simple + very complex apps
       Lots of options to scale, not just single path
       Stateless by default
       ...which means it's easy to test
       Those aren't documents, they're resources!
       ...and a resource ~~ distributed object


                                   
So? I'm not building Amazon
       Simplicity
       Flexibility
       Evolvability
       Testability
       Discoverability
       ...all good things, not related to scaling


                                    
A few initial warnings
       Resource­oriented very useful approach
       ...tough to purely implement with browsers
       ...and it requires some mind bending
       Still worthwhile!
       REST != HTTP (but we'll use it anyway)
       Show a good deal of code


                                 
Map
       What is REST?
       REST in Java
       What is REST?
       REST in Java
       ...




                          
In the beginning...
       quot;RESTquot; was created looking back at HTTP
       But the guy who created REST 
        also helped create HTTP
       His dissertation is very readable!




                                  
REST boiled down
       Give every quot;thingquot; an ID
       Link things together
       Use standard methods
       Resources with multiple representations
       Communicate statelessly




        (from Stefan Tilkov, awesome REST guy)
                                  
Our dorky little application
       Notem: record notes, become group memory
       Potential: Dynamic notes (~~IRC bots)




                                
Access Notem now!
       Crude interface, but easy to navigate
       Web:
        http://10.4.13.146:8765
       Data:
        http://10.4.13.146:8765/r/
       Distribution:
        http://10.4.13.146:8765/notem-0.25.zip
       Slides:
        http://10.4.13.146:8765/cwinters_rest.pdf

                                  
Notem resources
       Resource = 'state with URI' (lots else too)
       Every note
       Every collection of notes 
       Initial workspace




                                  
Jersey intro
                RI of JSR­311, Sun 
                 folks primary on team
                Heavily reliant on 
                 annotations
                Skeptical before, but 
                 I'm a believer!




          
Jersey Extensibility
       Highly extensible
       @Provider means: quot;Hey Jersey, plug this in!quot;
       Examples: TemplateProvider, JAXB items
       Contextual items can be injected with @Context
       Contextual: UriInfo, HttpHeaders, Security
       Interesting bit: getting contextual data down to 
        objects manipulated by other frameworks (JAXB) 

                                 
RBD #1: An ID for
                    everything
       ID == URI
       I == Identifier, L == Location
       Globally unique, routeable identifier
       They don't have to be pretty!
       'Thing' can have broad meaning:
           Collection of other things
           Process that can report state

                                          
'Routeable' identifier?
       Most think of ID as primary key: 42
       Maybe: table:ID
       Maybe: server:database:table:ID
       ...where 'server' lookup into local registry
       Even if that worked, what would it return?




                                   
URI works everywhere
       Built on top of basic plumbing (DNS, hostnames)
       Protocol specification built­in (http://, ftp://)
       Abstraction built­in too:
           what I want (URL)
           how to shuffle it around (HTTP)
           not how to fetch/generate




                                     
Common misconception: URI
        design
       quot;Hackablequot; URIs nice, not necessary
       Only constraint is that they're unique
       BDUF: Lay out entire URI scheme
       Agile: Define as you go, refactor mercilessly




                                  
RBD #1: Jersey help
       Every resource has an enforced unique URI
       ...not much beyond that




                                   
RBD #2: Link things
                  together
       Use server­provided URIs as references
       Clients building URIs is a common mistake! 
       Limit URI templates to query­building hints
       HATEOAS




                                 
URI templates?
       On server­side, hugely useful
       Declare variables from URI, map to method params
       Also available: regex matching




                                 
HATEOAS?
       Hypertext As The Engine 
        of Application State
       RTF uses quot;the hypermedia 
        constraintquot; instead




                               
HATEOAS!
       Server­controlled links define what clients can do
       You can move hosts!
       Shard data!
       Change URIs!
       And potentially all this without taking systems down




                                  
HATEOAS + refactoring
       Refactoring another benefit of HATEOAS
       Client dependent on server for state transitions
       ...immediately change 
        client behavior
       Seems simple, but 
        we're just used to it
       Start simple, grow 
        organically
                                  
Clients cannot assume
             resource structure!
       Everything the client can do is created by server
       Client and server can know beforehand about media 
        types and types of transitions
       Different 'rel' types in 'link' element...
       OPTIONS informs about allowed methods
           Jersey: application.wadl
       Ways to know you're not doing HATEOAS...

                                    
'REST endpoint'
       “Here's the endpoint for our REST API”
       REST exposes resources many URIs
       Not actions via a few




                                 
URI scheme up front
       “Here are all the URIs in our REST API”
       ...implies out­of­band info important to app flow 
       Client discover resources moving through system
       Publishing your URI structure is coupling




                                  
Clients parse URIs
       “Here's the data you'll need from the URI”
       URI is opaque identifier
       Content of resource should be standalone
       Example: /blog/2009/04/20/my_hair_isnt_that_bad
           Does content have date in it too?
       API forces client to parse URIs: more coupling


                                    
URIs name actions
       Flickr API URIs name actions vs resources
        /services/rest/?method=flickr.test.echo...

       REST has uniform interface! (more later)
       Specifying methods/actions == RPC




                                 
RPC + Coupling


quot;Today's example is the SocialSite 
REST API. That is RPC. It screams RPC. 
There is so much coupling on display that it 
should be given an X rating.quot;

­ Roy Fielding, 
REST APIs must be hypertext driven

                          
So bad about coupling?
       Evolvability
       Dependencies on structure inhibits evolution
       Do you expose your database tables?
       Or your libraries?
       If you choose to, it's a trade­off
       ...just one that REST explicitly chooses differently


                                    
URIs and the real world
       Easier to publish API that says quot;Send datablob A to 
        URI B and X will occurquot;
       IMO REST client development, generic or 
        otherwise, still early days...
       ...you do what you can




                                  
More HATEOAS
       Lots of recent discussion on this:
           rest­discuss posts (including Solomon Duskis)
           Subbu: quot;On Linkingquot;
           Craig McC on Sun Cloud API




                                     
Generating links
       Underdeveloped area
       Componentize link generation?
       Should a resource generate its own URI?
       How to inject context (host/port) down?
       Manipulate rules at runtime?
           Example: Reference all Employee objects at host frodo
           Example: ...all Buildings with area > 25000 to gondor

                                      
RBD #2: Jersey Help

“...this is probably the hardest area. JAX­RS 
provides a bunch of ways to construct URIs but 
there is no such URI binding facility with a 
modeling API, such as JAXB.”

­ Paul Sandoz
InfoQ announcement: JSR 311 Final


                         
RBD #3: Use standard
                methods
       AKA, 'uniform interface'
       Methods never vary based on resources
       Key constraint that allows intermediaries to function
       Google knows GET is safe, can spider your site
       ...except when it's not safe




                                    
Dangers of unsafe GET

    quot;[The Alexa toolbar] logged into the 
    administrative area and followed the 
    'delete' link for every entry,quot; the admin 
    says. quot;My dumb­ass boss still didn't 
    want to uninstall Alexa ­­ could have 
    strangled the man.quot;
    ­ Stupid user tricks 3: IT admin follies


                           
Methods have semantics
       Key difference from RPC systems
       HTTP defines what GET/PUT/DELETE mean
       ...on any resource
       Idempotent: invoke multiple times with same effect
       What will service.updateOrder() do if called twice?
       What about service.takeOrder()?
       POST is the catch­all, the 'process' method

                                  
Standard methods +
           idempotency

Method   Purpose                 Idempotent? Safe?
===================================================
GET      Retrieve representation     Y          Y
PUT      Provide representation      Y          N
POST     Create/extend resource      N          N
DELETE   Delete resource             Y          N
HEAD     GET minus body              Y          Y
OPTIONS Find methods for resource    Y          Y




                           
Which does RPC-over-HTTP
               use?


Method   Purpose                 Idempotent? Safe?
===================================================
POST     Create/extend resource    **N**      **N**




                           
Benefits of standard
                  methods
       Original name of REST: HTTP Object Model 
       All objects on the web can be manipulated similarly
       Implementation hiding: what language? what 
        model? who cares?
       Generic invocation: no need to generate code for 
        actions, only data



                                 
Where are my methods?
              Constraint!
       Yes, GET/PUT/DELETE/POST are constraints
       Ask anyone who writes: can sharpen focus
       Thinking in uniform 
        methods key to ROA




                                
Nouning verbs
       One pattern for adapting action­centric designs is 
                      [1]
        nouning verbs
       Canonical example: transactions
       Treat the transaction as a resource with status
       Reference the resource in your actions – client 
        maintains application state! (more later) 



[1] Because “resourcing verbs” sounds too Office Space-y
                                  
Nouning Transactions




              
TMTOWTDI
       Instead of referencing the resource, maybe I could  
        POST different resources to the transaction?
       ...transaction resource could passthru resources
       There are multiple ways to do it: that's the point
       Actions­as­resources takes a while, but useful




                                   
RBD #3: Jersey support
       Awesome
       Annotations for all major HTTP methods
       @HEAD coming in JAX­RS 1.1




                                
Sidetrack: Jersey resources
       “How does Jersey discover my resources?”
       Define Application which explicitly names
       Tell Jersey to scan your package
       Wire into your DI framework (Spring/Guice)
       Also true of @Provider implementations




                                 
Enabling evil

“Granted the abstraction of this messaging 
infrastructure led to bindings and dependencies 
that we are trying to get out of today, but that 
doesn't make RPC evil, it's the technologies and 
'programming style' that resulted from RPC that 
have become evil.”

­ Ebenezer Ikonne

                          
Avoiding evil
       Great presentation by Steve Vinoski on RPC history 
        discusses RPC issues
       Summary: Avoid
       ...if remote looks local, you will eventually lose




                                   
Current distributed systems
       Highly dependent on code generation, stubs
       Winds up treating 
        data­over­wire as opaque 
       ...will be difficult to reuse 
        on the same platform
       cross­platform? ha!



                                     
Defining service contracts


“Using a regular programming language to define 
supposedly abstract interfaces greatly increases 
the chances that language­specific constructs will 
leak into the contract.”

­ Steve Vinoski


                          
Problems with remote calls
       RPC should have high barrier to entry: it's hard!
       Very tight coupling
       Synchronization required (pre­3.0 entity beans?)
       Restricted failure modes
       Closed protocol (typically)
       And...


                                    
Fallacies of distributed
               computing
    1) The network is reliable.
    2) Latency is zero.
    3) Bandwidth is infinite.
    4) The network is secure.




                                   
Fallacies of distributed
                computing
    5) Topology doesn't change.
    6) There is one administrator.
    7) Transport cost is zero.
    8) The network is homogeneous.


    More: Fallacies of Distributed Computing Explained


                                  
RPC hopes
       System that solves problems inherent in distributed 
        computing.
       Examples Vinoski uses: REST and Erlang  
       Make explicit tradeoffs to work around limitations
       Echoing Fielding dissertation: it's all about tradeoffs




                                   
Focus on data!
       All this means: you're pushing the problem to data.
       This is good! You wind up there anyway. 




                                  
Sending data
       Historically representation tied to RPC system
       IIOP, DCE, RMI, SOAP + XML
       Instead, your data identified by media type
       Allows you to separate concerns:
           Library for processing media type
           Library for moving data through logic



                                     
RBD #4: Multiple
                 representations
       'Resource' is an abstract entity, a concept
       You only interact with representations
       With HTTP, content negotiation informs




                                   
HTTP: Accept
       Every request has an 'Accept' HTTP header
       Useful tools for seeing this in browser
       Useful tools for specifying from CLI
       RESTful service provides appropriate representation




                                  
Representations in Notem
       Three main ones, not applicable in all cases
       text/html, application/xml, application/json
       When using programmatic HTTP access it's easier 
        to control 




                                  
Representation
          communicates resource
       Others we could use?




                                
Representation
          communicates resource
       audio/mpeg: output of TTS engine
       application/ssml+xml: Speech synthesis markup (so 
        your TTS can speak the note)
       application/morse­code (madeup)
       Representations can be derived: not every one needs 
        to be PUTable



                                 
Designing representations
       Behooves you to use widely known media types
       quot;Get over the idea that your domain is a unique and 
        special snowflakequot;
       See Bill de Hora 
        quot;Snowflake APIsquot;




                                 
Media types

“A REST API should spend almost all of its 
descriptive effort in defining the media type(s) 
used for representing resources and driving 
application state...”

­ Roy Fielding, 
REST APIs must be hypertext driven


                           
RBD #4: Jersey support
       Awesome
       Declare @Produces and @Accepts for class or 
        methods
       Jersey parses Accept header and dispatches to the 
        right one




                                 
What's a valid return value?
       No interface required
       One known: javax.ws.rs.core.Response: status 
        + cookies, etag, entity...
       Others: try to match with MessageBodyWriter
       ...including list/array, though may be useful to have 
        explicit 'collection representation' to model 
        additional state


                                  
MessageBodyWriter
                 examples
       byte[] ­> ByteArrayProvider
       Viewable ­> ViewableMessageBodyWriter ­> 
        TemplateProvider
       JAXB­registered object ­> 
        JSONJAXBElementProvider || 
        XMLJAXBElementProvider




                                
Brief digression on JAXB
       Nifty technology!
       Tutorials focus on XML schemas and code 
        generation
       Skip all that, basic use is pretty easy




                                   
Marshalling sucks
       How many libraries? JiBX, XmlBeans, XStream...
       No silver bullet
       Marshalling always sucks, anyone who says 
        differently is selling you something




                                
RBD #5: Communicate
          statelessly
“...communication must be stateless in 
nature...such that each request from client to 
server must contain all of the information 
necessary to understand the request, and cannot 
take advantage of any stored context on the 
server. Session state is therefore kept entirely on 
the client.”

­ Roy Fielding, p.78­9.
                           
Benefits of statelessness
       Caching
       Scale out, not up
       Simple in some senses, not others




                                 
Different types of state
       Client: Application state is 'where' you are
       Server: Resource state is what you're manipulating
       Possible to represent application state as resource?




                                  
Examples of state
       Phone conversation: all 'application' state
       Client/server app: server holds open transactions, 
        current 'screen', relies on open connection
       Web app: current page of results, shopping cart, 
        current 'item' being worked on, GUI 
        customizations...




                                   
Shopping cart example
       Assuming a fully featured client
       ...how might we design a RESTful shopping cart?




                                 
RBD #5: Jersey support
       Really an implementation detail
       Jersey helps you DTRT, but you're free to break it




                                 
Why caching?
       The fastest DB query is the one never executed
       Nearly all applications are read­mostly: optimize!
       Transparently­added caching even better
       (view 'Many intermediaries image')
       The network is not transparent




                                  
Faking statefulness (test)
       Form data just key/value pairs
       Cookies just text
       HTTP Authentication just a header




                                 
'Architectural Style'


“An architectural style is a coordinated set of 
architectural constraints that restricts the 
roles/features of architectural elements and the 
allowed relationships among those elements 
within any architecture that conforms to that style.”

­ Roy Fielding, p. 13

                           
'Architectural Style'
       Abstraction for component interaction
       An architecture reflects its environment
       ...but hard to compare those from different 
        environments 
       It is not a set of defined messages




                                   
'Architecture Style'
       Alan Dean:
           A style can be applied to many different architectures.
           An architecture can consist of many different styles.




                                       
Pieces of the Style
       Client/Server (separation of concerns)
       Stateless communication
       Caching
       Uniform interface
       Layered system
       Code on demand


                                   
Style implications
     You will not be buying a 'REST Toolkit'
     One level up from tools allows evaluation of fit for 
      purpose
     Fielding dissertation opens with reference to Monty 
      Python sketch :
quot;It might very well be the best slaughterhouse design ever 
   conceived, but that would be of little comfort to the 
   prospective tenants as they are whisked along hallways 
   containing rotating knives.quot;
­ Fielding
                                 
Other styles
       POX: Plain old XML: not bad <em>a priori</em>, 
        but,
           ... typically everything goes through POST (XML­RPC)
       MEST ('processThis()', see Jim Webber for more)
       quot;Low RESTquot; vs quot;High RESTquot; (RTF says it's 
        hogwash)



                                    
Now what?
       Evolvability is underrated
       Distributed systems are hard
       Try it! Building even a small system will introduce 
        new 'resources' that you probably haven't thought of
       Jersey is proof that JSRs can work




                                  
Thank you!




         
Resources on REST



    Collected on my site, slides are terrible for this:
            http://www.cwinters.com/rest/




                              
Attributions
       Testudo Shrug
       Tinkertoy Sticks 
       I hate zombies
       Mike Tomlin (Gregory Shamus/Getty Images)
       I Hate Mondays




                               

Contenu connexe

Similaire à Cwinters Intro To Rest And JerREST and Jersey Introductionsey

Introduction to Bazaar
Introduction to BazaarIntroduction to Bazaar
Introduction to BazaarTim Penhey
 
Using Wordpress 2009 04 29
Using Wordpress 2009 04 29Using Wordpress 2009 04 29
Using Wordpress 2009 04 29Matthew Baya
 
API's, Freebase, and the Collaborative Semantic web
API's, Freebase, and the Collaborative Semantic webAPI's, Freebase, and the Collaborative Semantic web
API's, Freebase, and the Collaborative Semantic webDan Delany
 
Search As A Service
Search As A ServiceSearch As A Service
Search As A ServiceMarkus Wolff
 
Applications of the REST Principle
Applications of the REST PrincipleApplications of the REST Principle
Applications of the REST Principleelliando dias
 
Douglas Knudsen - Great Mash Up
Douglas Knudsen - Great Mash UpDouglas Knudsen - Great Mash Up
Douglas Knudsen - Great Mash Up360|Conferences
 
Text indexing and search libraries for PHP - Zoë Slattery - Barcelona PHP Con...
Text indexing and search libraries for PHP - Zoë Slattery - Barcelona PHP Con...Text indexing and search libraries for PHP - Zoë Slattery - Barcelona PHP Con...
Text indexing and search libraries for PHP - Zoë Slattery - Barcelona PHP Con...phpbarcelona
 
Creating Semantic Mashups Bridging Web 2 0 And The Semantic Web Presentation 1
Creating Semantic Mashups  Bridging Web 2 0 And The Semantic Web Presentation 1Creating Semantic Mashups  Bridging Web 2 0 And The Semantic Web Presentation 1
Creating Semantic Mashups Bridging Web 2 0 And The Semantic Web Presentation 1jward5519
 
Creating Semantic Mashups Bridging Web 2 0 And The Semantic Web Presentation 1
Creating Semantic Mashups  Bridging Web 2 0 And The Semantic Web Presentation 1Creating Semantic Mashups  Bridging Web 2 0 And The Semantic Web Presentation 1
Creating Semantic Mashups Bridging Web 2 0 And The Semantic Web Presentation 1jward5519
 
Facebook Hadoop Data & Applications
Facebook Hadoop Data & ApplicationsFacebook Hadoop Data & Applications
Facebook Hadoop Data & Applicationsdzhou
 
When To Use Ruby On Rails
When To Use Ruby On RailsWhen To Use Ruby On Rails
When To Use Ruby On Railsdosire
 
ReST Vs SOA(P) ... Yawn
ReST Vs SOA(P) ... YawnReST Vs SOA(P) ... Yawn
ReST Vs SOA(P) ... Yawnozten
 
Streamlining Your Applications with Web Frameworks
Streamlining Your Applications with Web FrameworksStreamlining Your Applications with Web Frameworks
Streamlining Your Applications with Web Frameworksguestf7bc30
 
Blueprint talk at Open Hackday London 2009
Blueprint talk at Open Hackday London 2009Blueprint talk at Open Hackday London 2009
Blueprint talk at Open Hackday London 2009Ricardo Varela
 
REST Introduction (PHP London)
REST Introduction (PHP London)REST Introduction (PHP London)
REST Introduction (PHP London)Paul James
 
yet another rails
yet another railsyet another rails
yet another railsashok kumar
 

Similaire à Cwinters Intro To Rest And JerREST and Jersey Introductionsey (20)

Introduction to Bazaar
Introduction to BazaarIntroduction to Bazaar
Introduction to Bazaar
 
Using Wordpress 2009 04 29
Using Wordpress 2009 04 29Using Wordpress 2009 04 29
Using Wordpress 2009 04 29
 
API's, Freebase, and the Collaborative Semantic web
API's, Freebase, and the Collaborative Semantic webAPI's, Freebase, and the Collaborative Semantic web
API's, Freebase, and the Collaborative Semantic web
 
Search As A Service
Search As A ServiceSearch As A Service
Search As A Service
 
Applications of the REST Principle
Applications of the REST PrincipleApplications of the REST Principle
Applications of the REST Principle
 
Douglas Knudsen - Great Mash Up
Douglas Knudsen - Great Mash UpDouglas Knudsen - Great Mash Up
Douglas Knudsen - Great Mash Up
 
Rest Vs Soap Yawn2289
Rest Vs Soap Yawn2289Rest Vs Soap Yawn2289
Rest Vs Soap Yawn2289
 
Text indexing and search libraries for PHP - Zoë Slattery - Barcelona PHP Con...
Text indexing and search libraries for PHP - Zoë Slattery - Barcelona PHP Con...Text indexing and search libraries for PHP - Zoë Slattery - Barcelona PHP Con...
Text indexing and search libraries for PHP - Zoë Slattery - Barcelona PHP Con...
 
Creating Semantic Mashups Bridging Web 2 0 And The Semantic Web Presentation 1
Creating Semantic Mashups  Bridging Web 2 0 And The Semantic Web Presentation 1Creating Semantic Mashups  Bridging Web 2 0 And The Semantic Web Presentation 1
Creating Semantic Mashups Bridging Web 2 0 And The Semantic Web Presentation 1
 
Creating Semantic Mashups Bridging Web 2 0 And The Semantic Web Presentation 1
Creating Semantic Mashups  Bridging Web 2 0 And The Semantic Web Presentation 1Creating Semantic Mashups  Bridging Web 2 0 And The Semantic Web Presentation 1
Creating Semantic Mashups Bridging Web 2 0 And The Semantic Web Presentation 1
 
Facebook Hadoop Data & Applications
Facebook Hadoop Data & ApplicationsFacebook Hadoop Data & Applications
Facebook Hadoop Data & Applications
 
When To Use Ruby On Rails
When To Use Ruby On RailsWhen To Use Ruby On Rails
When To Use Ruby On Rails
 
ReST Vs SOA(P) ... Yawn
ReST Vs SOA(P) ... YawnReST Vs SOA(P) ... Yawn
ReST Vs SOA(P) ... Yawn
 
Streamlining Your Applications with Web Frameworks
Streamlining Your Applications with Web FrameworksStreamlining Your Applications with Web Frameworks
Streamlining Your Applications with Web Frameworks
 
Os Furlong
Os FurlongOs Furlong
Os Furlong
 
Blueprint talk at Open Hackday London 2009
Blueprint talk at Open Hackday London 2009Blueprint talk at Open Hackday London 2009
Blueprint talk at Open Hackday London 2009
 
REST Introduction (PHP London)
REST Introduction (PHP London)REST Introduction (PHP London)
REST Introduction (PHP London)
 
SEASR Installation
SEASR InstallationSEASR Installation
SEASR Installation
 
yet another rails
yet another railsyet another rails
yet another rails
 
Scaling Scribd
Scaling ScribdScaling Scribd
Scaling Scribd
 

Plus de elliando dias

Clojurescript slides
Clojurescript slidesClojurescript slides
Clojurescript slideselliando dias
 
Why you should be excited about ClojureScript
Why you should be excited about ClojureScriptWhy you should be excited about ClojureScript
Why you should be excited about ClojureScriptelliando dias
 
Functional Programming with Immutable Data Structures
Functional Programming with Immutable Data StructuresFunctional Programming with Immutable Data Structures
Functional Programming with Immutable Data Structureselliando dias
 
Nomenclatura e peças de container
Nomenclatura  e peças de containerNomenclatura  e peças de container
Nomenclatura e peças de containerelliando dias
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agilityelliando dias
 
Javascript Libraries
Javascript LibrariesJavascript Libraries
Javascript Librarieselliando dias
 
How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!elliando dias
 
A Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the WebA Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the Webelliando dias
 
Introdução ao Arduino
Introdução ao ArduinoIntrodução ao Arduino
Introdução ao Arduinoelliando dias
 
Incanter Data Sorcery
Incanter Data SorceryIncanter Data Sorcery
Incanter Data Sorceryelliando dias
 
Fab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine DesignFab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine Designelliando dias
 
The Digital Revolution: Machines that makes
The Digital Revolution: Machines that makesThe Digital Revolution: Machines that makes
The Digital Revolution: Machines that makeselliando dias
 
Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.elliando dias
 
Hadoop and Hive Development at Facebook
Hadoop and Hive Development at FacebookHadoop and Hive Development at Facebook
Hadoop and Hive Development at Facebookelliando dias
 
Multi-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case StudyMulti-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case Studyelliando dias
 

Plus de elliando dias (20)

Clojurescript slides
Clojurescript slidesClojurescript slides
Clojurescript slides
 
Why you should be excited about ClojureScript
Why you should be excited about ClojureScriptWhy you should be excited about ClojureScript
Why you should be excited about ClojureScript
 
Functional Programming with Immutable Data Structures
Functional Programming with Immutable Data StructuresFunctional Programming with Immutable Data Structures
Functional Programming with Immutable Data Structures
 
Nomenclatura e peças de container
Nomenclatura  e peças de containerNomenclatura  e peças de container
Nomenclatura e peças de container
 
Geometria Projetiva
Geometria ProjetivaGeometria Projetiva
Geometria Projetiva
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agility
 
Javascript Libraries
Javascript LibrariesJavascript Libraries
Javascript Libraries
 
How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!
 
Ragel talk
Ragel talkRagel talk
Ragel talk
 
A Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the WebA Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the Web
 
Introdução ao Arduino
Introdução ao ArduinoIntrodução ao Arduino
Introdução ao Arduino
 
Minicurso arduino
Minicurso arduinoMinicurso arduino
Minicurso arduino
 
Incanter Data Sorcery
Incanter Data SorceryIncanter Data Sorcery
Incanter Data Sorcery
 
Rango
RangoRango
Rango
 
Fab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine DesignFab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine Design
 
The Digital Revolution: Machines that makes
The Digital Revolution: Machines that makesThe Digital Revolution: Machines that makes
The Digital Revolution: Machines that makes
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.
 
Hadoop and Hive Development at Facebook
Hadoop and Hive Development at FacebookHadoop and Hive Development at Facebook
Hadoop and Hive Development at Facebook
 
Multi-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case StudyMulti-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case Study
 

Dernier

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 

Dernier (20)

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 

Cwinters Intro To Rest And JerREST and Jersey Introductionsey

  • 1. REST and Jersey Introduction Chris Winters Pittsburgh Java User Group 21 April 2009    
  • 2. Did you update the URLs? (slide 13: update with IP so people can access)    
  • 3. Anyone want to vent?    
  • 4. Who am I?  http://www.cwinters.com/ (not the male model)  Dad of awesome two year­old  Software Architect at Vocollect Healthcare Systems  Most experience on very small teams  AccuNurse: voice­assisted care for nursing homes  We use many, many opensource libraries  Not a REST expert, just very interested    
  • 5. REST  Representational State Transfer  Defined in Roy Fielding dissertation  One primary implementation to­date: web + HTTP  Why the interest?  Web: ubiquitous, scalable, enabling platform    
  • 6. HTTP Success  Text­based!  Simple!  Universal!  Clients and servers aren't tightly bound    
  • 7. HTTP Success, Deeper  Supports very simple + very complex apps  Lots of options to scale, not just single path  Stateless by default  ...which means it's easy to test  Those aren't documents, they're resources!  ...and a resource ~~ distributed object    
  • 8. So? I'm not building Amazon  Simplicity  Flexibility  Evolvability  Testability  Discoverability  ...all good things, not related to scaling    
  • 9. A few initial warnings  Resource­oriented very useful approach  ...tough to purely implement with browsers  ...and it requires some mind bending  Still worthwhile!  REST != HTTP (but we'll use it anyway)  Show a good deal of code    
  • 10. Map  What is REST?  REST in Java  What is REST?  REST in Java  ...    
  • 11. In the beginning...  quot;RESTquot; was created looking back at HTTP  But the guy who created REST  also helped create HTTP  His dissertation is very readable!    
  • 12. REST boiled down  Give every quot;thingquot; an ID  Link things together  Use standard methods  Resources with multiple representations  Communicate statelessly   (from Stefan Tilkov, awesome REST guy)  
  • 13. Our dorky little application  Notem: record notes, become group memory  Potential: Dynamic notes (~~IRC bots)    
  • 14. Access Notem now!  Crude interface, but easy to navigate  Web: http://10.4.13.146:8765  Data: http://10.4.13.146:8765/r/  Distribution: http://10.4.13.146:8765/notem-0.25.zip  Slides: http://10.4.13.146:8765/cwinters_rest.pdf    
  • 15. Notem resources  Resource = 'state with URI' (lots else too)  Every note  Every collection of notes   Initial workspace    
  • 16. Jersey intro  RI of JSR­311, Sun  folks primary on team  Heavily reliant on  annotations  Skeptical before, but  I'm a believer!    
  • 17. Jersey Extensibility  Highly extensible  @Provider means: quot;Hey Jersey, plug this in!quot;  Examples: TemplateProvider, JAXB items  Contextual items can be injected with @Context  Contextual: UriInfo, HttpHeaders, Security  Interesting bit: getting contextual data down to  objects manipulated by other frameworks (JAXB)     
  • 18. RBD #1: An ID for everything  ID == URI  I == Identifier, L == Location  Globally unique, routeable identifier  They don't have to be pretty!  'Thing' can have broad meaning:  Collection of other things  Process that can report state    
  • 19. 'Routeable' identifier?  Most think of ID as primary key: 42  Maybe: table:ID  Maybe: server:database:table:ID  ...where 'server' lookup into local registry  Even if that worked, what would it return?    
  • 20. URI works everywhere  Built on top of basic plumbing (DNS, hostnames)  Protocol specification built­in (http://, ftp://)  Abstraction built­in too:  what I want (URL)  how to shuffle it around (HTTP)  not how to fetch/generate    
  • 21. Common misconception: URI design  quot;Hackablequot; URIs nice, not necessary  Only constraint is that they're unique  BDUF: Lay out entire URI scheme  Agile: Define as you go, refactor mercilessly    
  • 22. RBD #1: Jersey help  Every resource has an enforced unique URI  ...not much beyond that    
  • 23. RBD #2: Link things together  Use server­provided URIs as references  Clients building URIs is a common mistake!   Limit URI templates to query­building hints  HATEOAS    
  • 24. URI templates?  On server­side, hugely useful  Declare variables from URI, map to method params  Also available: regex matching    
  • 25. HATEOAS?  Hypertext As The Engine  of Application State  RTF uses quot;the hypermedia  constraintquot; instead    
  • 26. HATEOAS!  Server­controlled links define what clients can do  You can move hosts!  Shard data!  Change URIs!  And potentially all this without taking systems down    
  • 27. HATEOAS + refactoring  Refactoring another benefit of HATEOAS  Client dependent on server for state transitions  ...immediately change  client behavior  Seems simple, but  we're just used to it  Start simple, grow  organically    
  • 28. Clients cannot assume resource structure!  Everything the client can do is created by server  Client and server can know beforehand about media  types and types of transitions  Different 'rel' types in 'link' element...  OPTIONS informs about allowed methods  Jersey: application.wadl  Ways to know you're not doing HATEOAS...    
  • 29. 'REST endpoint'  “Here's the endpoint for our REST API”  REST exposes resources many URIs  Not actions via a few    
  • 30. URI scheme up front  “Here are all the URIs in our REST API”  ...implies out­of­band info important to app flow   Client discover resources moving through system  Publishing your URI structure is coupling    
  • 31. Clients parse URIs  “Here's the data you'll need from the URI”  URI is opaque identifier  Content of resource should be standalone  Example: /blog/2009/04/20/my_hair_isnt_that_bad  Does content have date in it too?  API forces client to parse URIs: more coupling    
  • 32. URIs name actions  Flickr API URIs name actions vs resources /services/rest/?method=flickr.test.echo...  REST has uniform interface! (more later)  Specifying methods/actions == RPC    
  • 34. So bad about coupling?  Evolvability  Dependencies on structure inhibits evolution  Do you expose your database tables?  Or your libraries?  If you choose to, it's a trade­off  ...just one that REST explicitly chooses differently    
  • 35. URIs and the real world  Easier to publish API that says quot;Send datablob A to  URI B and X will occurquot;  IMO REST client development, generic or  otherwise, still early days...  ...you do what you can    
  • 36. More HATEOAS  Lots of recent discussion on this:  rest­discuss posts (including Solomon Duskis)  Subbu: quot;On Linkingquot;  Craig McC on Sun Cloud API    
  • 37. Generating links  Underdeveloped area  Componentize link generation?  Should a resource generate its own URI?  How to inject context (host/port) down?  Manipulate rules at runtime?  Example: Reference all Employee objects at host frodo  Example: ...all Buildings with area > 25000 to gondor    
  • 38. RBD #2: Jersey Help “...this is probably the hardest area. JAX­RS  provides a bunch of ways to construct URIs but  there is no such URI binding facility with a  modeling API, such as JAXB.” ­ Paul Sandoz InfoQ announcement: JSR 311 Final    
  • 39. RBD #3: Use standard methods  AKA, 'uniform interface'  Methods never vary based on resources  Key constraint that allows intermediaries to function  Google knows GET is safe, can spider your site  ...except when it's not safe    
  • 40. Dangers of unsafe GET quot;[The Alexa toolbar] logged into the  administrative area and followed the  'delete' link for every entry,quot; the admin  says. quot;My dumb­ass boss still didn't  want to uninstall Alexa ­­ could have  strangled the man.quot; ­ Stupid user tricks 3: IT admin follies    
  • 41. Methods have semantics  Key difference from RPC systems  HTTP defines what GET/PUT/DELETE mean  ...on any resource  Idempotent: invoke multiple times with same effect  What will service.updateOrder() do if called twice?  What about service.takeOrder()?  POST is the catch­all, the 'process' method    
  • 42. Standard methods + idempotency Method Purpose Idempotent? Safe? =================================================== GET Retrieve representation Y Y PUT Provide representation Y N POST Create/extend resource N N DELETE Delete resource Y N HEAD GET minus body Y Y OPTIONS Find methods for resource Y Y    
  • 43. Which does RPC-over-HTTP use? Method Purpose Idempotent? Safe? =================================================== POST Create/extend resource **N** **N**    
  • 44. Benefits of standard methods  Original name of REST: HTTP Object Model   All objects on the web can be manipulated similarly  Implementation hiding: what language? what  model? who cares?  Generic invocation: no need to generate code for  actions, only data    
  • 45. Where are my methods? Constraint!  Yes, GET/PUT/DELETE/POST are constraints  Ask anyone who writes: can sharpen focus  Thinking in uniform  methods key to ROA    
  • 46. Nouning verbs  One pattern for adapting action­centric designs is  [1] nouning verbs  Canonical example: transactions  Treat the transaction as a resource with status  Reference the resource in your actions – client  maintains application state! (more later)  [1] Because “resourcing verbs” sounds too Office Space-y    
  • 48. TMTOWTDI  Instead of referencing the resource, maybe I could   POST different resources to the transaction?  ...transaction resource could passthru resources  There are multiple ways to do it: that's the point  Actions­as­resources takes a while, but useful    
  • 49. RBD #3: Jersey support  Awesome  Annotations for all major HTTP methods  @HEAD coming in JAX­RS 1.1    
  • 50. Sidetrack: Jersey resources  “How does Jersey discover my resources?”  Define Application which explicitly names  Tell Jersey to scan your package  Wire into your DI framework (Spring/Guice)  Also true of @Provider implementations    
  • 52. Avoiding evil  Great presentation by Steve Vinoski on RPC history  discusses RPC issues  Summary: Avoid  ...if remote looks local, you will eventually lose    
  • 53. Current distributed systems  Highly dependent on code generation, stubs  Winds up treating  data­over­wire as opaque   ...will be difficult to reuse  on the same platform  cross­platform? ha!    
  • 55. Problems with remote calls  RPC should have high barrier to entry: it's hard!  Very tight coupling  Synchronization required (pre­3.0 entity beans?)  Restricted failure modes  Closed protocol (typically)  And...    
  • 56. Fallacies of distributed computing 1) The network is reliable. 2) Latency is zero. 3) Bandwidth is infinite. 4) The network is secure.    
  • 57. Fallacies of distributed computing 5) Topology doesn't change. 6) There is one administrator. 7) Transport cost is zero. 8) The network is homogeneous. More: Fallacies of Distributed Computing Explained    
  • 58. RPC hopes  System that solves problems inherent in distributed  computing.  Examples Vinoski uses: REST and Erlang    Make explicit tradeoffs to work around limitations  Echoing Fielding dissertation: it's all about tradeoffs    
  • 59. Focus on data!  All this means: you're pushing the problem to data.  This is good! You wind up there anyway.     
  • 60. Sending data  Historically representation tied to RPC system  IIOP, DCE, RMI, SOAP + XML  Instead, your data identified by media type  Allows you to separate concerns:  Library for processing media type  Library for moving data through logic    
  • 61. RBD #4: Multiple representations  'Resource' is an abstract entity, a concept  You only interact with representations  With HTTP, content negotiation informs    
  • 62. HTTP: Accept  Every request has an 'Accept' HTTP header  Useful tools for seeing this in browser  Useful tools for specifying from CLI  RESTful service provides appropriate representation    
  • 63. Representations in Notem  Three main ones, not applicable in all cases  text/html, application/xml, application/json  When using programmatic HTTP access it's easier  to control     
  • 64. Representation communicates resource  Others we could use?    
  • 65. Representation communicates resource  audio/mpeg: output of TTS engine  application/ssml+xml: Speech synthesis markup (so  your TTS can speak the note)  application/morse­code (madeup)  Representations can be derived: not every one needs  to be PUTable    
  • 66. Designing representations  Behooves you to use widely known media types  quot;Get over the idea that your domain is a unique and  special snowflakequot;  See Bill de Hora  quot;Snowflake APIsquot;    
  • 68. RBD #4: Jersey support  Awesome  Declare @Produces and @Accepts for class or  methods  Jersey parses Accept header and dispatches to the  right one    
  • 69. What's a valid return value?  No interface required  One known: javax.ws.rs.core.Response: status  + cookies, etag, entity...  Others: try to match with MessageBodyWriter  ...including list/array, though may be useful to have  explicit 'collection representation' to model  additional state    
  • 70. MessageBodyWriter examples  byte[] ­> ByteArrayProvider  Viewable ­> ViewableMessageBodyWriter ­>  TemplateProvider  JAXB­registered object ­>  JSONJAXBElementProvider ||  XMLJAXBElementProvider    
  • 71. Brief digression on JAXB  Nifty technology!  Tutorials focus on XML schemas and code  generation  Skip all that, basic use is pretty easy    
  • 72. Marshalling sucks  How many libraries? JiBX, XmlBeans, XStream...  No silver bullet  Marshalling always sucks, anyone who says  differently is selling you something    
  • 73. RBD #5: Communicate statelessly “...communication must be stateless in  nature...such that each request from client to  server must contain all of the information  necessary to understand the request, and cannot  take advantage of any stored context on the  server. Session state is therefore kept entirely on  the client.” ­ Roy Fielding, p.78­9.    
  • 74. Benefits of statelessness  Caching  Scale out, not up  Simple in some senses, not others    
  • 75. Different types of state  Client: Application state is 'where' you are  Server: Resource state is what you're manipulating  Possible to represent application state as resource?    
  • 76. Examples of state  Phone conversation: all 'application' state  Client/server app: server holds open transactions,  current 'screen', relies on open connection  Web app: current page of results, shopping cart,  current 'item' being worked on, GUI  customizations...    
  • 77. Shopping cart example  Assuming a fully featured client  ...how might we design a RESTful shopping cart?    
  • 78. RBD #5: Jersey support  Really an implementation detail  Jersey helps you DTRT, but you're free to break it    
  • 79. Why caching?  The fastest DB query is the one never executed  Nearly all applications are read­mostly: optimize!  Transparently­added caching even better  (view 'Many intermediaries image')  The network is not transparent    
  • 80. Faking statefulness (test)  Form data just key/value pairs  Cookies just text  HTTP Authentication just a header    
  • 82. 'Architectural Style'  Abstraction for component interaction  An architecture reflects its environment  ...but hard to compare those from different  environments   It is not a set of defined messages    
  • 83. 'Architecture Style'  Alan Dean:  A style can be applied to many different architectures.  An architecture can consist of many different styles.    
  • 84. Pieces of the Style  Client/Server (separation of concerns)  Stateless communication  Caching  Uniform interface  Layered system  Code on demand    
  • 85. Style implications  You will not be buying a 'REST Toolkit'  One level up from tools allows evaluation of fit for  purpose  Fielding dissertation opens with reference to Monty  Python sketch : quot;It might very well be the best slaughterhouse design ever  conceived, but that would be of little comfort to the  prospective tenants as they are whisked along hallways  containing rotating knives.quot; ­ Fielding    
  • 86. Other styles  POX: Plain old XML: not bad <em>a priori</em>,  but,  ... typically everything goes through POST (XML­RPC)  MEST ('processThis()', see Jim Webber for more)  quot;Low RESTquot; vs quot;High RESTquot; (RTF says it's  hogwash)    
  • 87. Now what?  Evolvability is underrated  Distributed systems are hard  Try it! Building even a small system will introduce  new 'resources' that you probably haven't thought of  Jersey is proof that JSRs can work    
  • 89. Resources on REST Collected on my site, slides are terrible for this: http://www.cwinters.com/rest/    
  • 90. Attributions  Testudo Shrug  Tinkertoy Sticks   I hate zombies  Mike Tomlin (Gregory Shamus/Getty Images)  I Hate Mondays