SlideShare uma empresa Scribd logo
1 de 60
RESTful SOA and the
                                                   Spring Framework
                                                   XML REST Framework and Spring
                                                   MVC
                                                   Cornelia Davis
                                                   Sr. Technologist
                                                   EMC CTO Office




© Copyright 2011 EMC Corporation. All rights reserved.                             1
Overview
Drivers for this work at EMC
Ÿ  Goal: Establish an integration architecture that will help EMC bring
    together its own and partner products.

                                                         RESTful SOA

Ÿ  We’re basing it on REST because:
         –  In order to get some standardization the principles need to be easy
         –  The environment is highly distributed and potentially very large
            – that is, CLOUD
         –  Product groups are all building RESTful interfaces
         –  Resource focus
                   §  With media-type handling
                   §  With hyperlinking
                   §  With caching




© Copyright 2011 EMC Corporation. All rights reserved.                            2
Elements of Cloud Computing

             Cloud computing: “A style of computing where scalable
             and elastic IT-enabled capabilities are delivered as a
             service to customers using Internet technologies.”

•  Five defining attributes1                                                •  Best Practices2,3
         –      Service-based                                                       –  Design for Failure (and nothing
         –      Scalable and elastic                                                   will fail)
         –      Shared                                                              –  Decouple your components
         –      Metered by use                                                      –  Implement elasticity
         –      Uses Internet technologies                                          –  Think parallel
                                                                                    –  Data/compute proximity
                                                                                    –  Security
        1http://blogs.gartner.com/thomas_bittman/2010/05/18/clarifying-private-cloud-computing/ 2http://www.slideshare.net/

        AmazonWebServices/aws-architectingjvariafinal?src=related_normal&rel=3862774 3http://
        media.amazonwebservices.com/AWS_Cloud_Best_Practices.pdf
© Copyright 2011 EMC Corporation. All rights reserved.                                                                        3
A Typical, Pre-cloud Application
      Architecture

                                                                                         Persistence




                                                                        Business Logic



                                                         Presentation




             Client




© Copyright 2011 EMC Corporation. All rights reserved.                                                 4
In the Cloud…
     Scalable and Elastic




                                                                                                      Persistence




                                                                              Business Logic

                                                                                                  Service Oriented
                                                         Presentation




             Client
                                                                        Internet Infrastructure



© Copyright 2011 EMC Corporation. All rights reserved.                                                               5
Agenda
                                                   REST Principles

                                                   Implementing RESTful Services with
                                                   Spring MVC and the XML REST
                                                   Framework

                                                   What’s next?


© Copyright 2011 EMC Corporation. All rights reserved.                                  6
REST Principles
 •  REST is an architectural style that depends upon:
 Ÿ Identification and addressability of resources
           –  All interesting bits of information are identified with URIs and
              are usually accessed via URL
 Ÿ The uniform interface
           –  Interaction with resources through a standardized set of
              operations, with well understood semantics
 Ÿ Manipulation of resources
    through representations
           –  Media types
 Ÿ Hypermedia as the engine of
    application state
           –  Hyperlink your resources


© Copyright 2011 EMC Corporation. All rights reserved.                           7
REST Principle –
Resource Centricity and Addressability
•  What: Interface is defined by a set of resources that are
   addressable
•  Why: are resources and addressability important?
         –  Data is king!
         –  Relationships between entities are part of the representation – that is,
            hyperlinks.
         –  URLs provide a hierarchical, global address space suitable for cloud-
            based applications
         –  Achieving scale through a layered, cache-rich infrastructure.


                                                         C


                                                             C



© Copyright 2011 EMC Corporation. All rights reserved.                                 8
REST Principle –
Uniform Interface
                                                         GET       Retrieve a resource       Safe,
•  What: Each resource                                             representation            Idempotent,
   supports one of a fixed                                                                   Cacheable
   set of operations                                     HEAD      Retrieve resource         Safe,
         –  Internet based                                         headers                   Idempotent
            infrastructure: GET, PUT,
            POST, DELETE, HEAD                           OPTIONS Used to get the list of     Safe,
            and OPTIONS                                          verbs supported by this     Idempotent
         –  PATCH, for partial                                   resource
            update of resource                           PUT       Replace the resource      Idempotent
•  Why: is a uniform                                     PATCH     Update a resource         --
   interface important?
                                                         DELETE    Delete the resource       Idempotent
         –  Supports certain
            application patterns (i.e.                   POST      Another operation on a    --
            retry on fail)                                         resource
         –  Allows infrastructure to                               Often used for resource
            perform operations and                                 creation
            optimization


© Copyright 2011 EMC Corporation. All rights reserved.                                                     9
REST Principle –
Uniform Interface: Safe
•  What: A safe operation is one that can be invoked 0, 1 or more
   times leaving the resource unchanged
•  GET and HEAD SHOULD be safe – (I’d like to say MUST)
•  Why: is it good to have safe operations?
         –  Allows the infrastructure to optimize certain operations – i.e. prefetching
            resources
         –  The now defunct Google Web Accelerator did prefetching in the
            browser
         –  Real win: User Perceived Performance


                                                   GET /mySavingsAccount/delete



© Copyright 2011 EMC Corporation. All rights reserved.                                    10
REST Principle –
Uniform Interface: Idempotent
•  What: An idempotent operation is one that can be invoked once or
   more than one time with the same resource state as a result
                                                    Idempotent ≠ side effect free
•  All safe operations are idempotent
•  Additionally, PUT and DELETE are idempotent
•  Why: is it good to have idempotent operations?
         –  #1 fallacy of distributed computing: The network is reliable
         –  When an operation is idempotent a client can retry if they get no
            response
                                                         DELETE /photos/badone.jpg
                                        ?                DELETE /photos/badone.jpg

                                                               204 No Content


© Copyright 2011 EMC Corporation. All rights reserved.                               11
REST Principle –
Uniform Interface: Cacheable
•  What: A cacheable operation is one where the result may be
   cached by intermediaries between the client and the server
•  GET is cacheable
•  Why: is it good to have cachable operations?
         –  Scalability – intermediaries can cache results lessening the load on the
            origin server
•  Stable URLs are critical!

                                                         C


                                                             C



© Copyright 2011 EMC Corporation. All rights reserved.                                 12
REST Principle –
Media Types
•  What: A RESTful interface does not serve resources, rather it
   serves representations of resources.
         –  A media type describes the format of the resource representation
         –  Requests and responses include headers indicating media types
•  Why: are media types relevant in RESTful interfaces?
         –  Key information for client to be able to process results
         –  Content negotiation
                §    Client can indicate which content
                      types they can accept – i.e. HTTP      GET /patients/123
                      Accept header                          Accept: application/atom+xml, text/xml
                §    Server indicates the content type of
                      the representation returned – i.e.
                      HTTP Content-type header               HTTP/1.1 200 OK
                                                             Content-Type: application/atom+xml
          –  Intermediaries can perform                      ...
             transformations                                 <atom:entry xmlns=“www.w3.org/2005/Atom”>
                                                               ...
          –  AtomPub embraces media                          </atom:entry>
             types in collection abstraction

© Copyright 2011 EMC Corporation. All rights reserved.                                                   13
REST Principle –
    Hypertext Driven
    •  What: Hypermedia As The Engine Of Application State
       (HATEOAS)
             –  Resource representation must be hyperlink rich
             –  Links to related resources AND for application state transitions (some of
                which may be resource state transitions)
             –  Links minimally include a “rel” value and an “href” value
             –  The Atom Syndication Format1 defines a <link> that is now in
                widespread use
    •  Why: are hyperlinks in resource representations important?
             –  Smaller fixed API and generally looser coupling between the client and
                server
                       •  URI templates may change
             –  Client can focus on the semantics of the relationship types (the “rel”
                values)
             –  Interoperability – the CMIS2 proposed standard is a good example -
                RESTful interface defines relationship types but no URI templates
             –  Standardize link relations – within global3 and within more local scopes
1 http://tools.ietf.org/html/rfc4287
                              2      http://tools.ietf.org/html/rfc4287
3   http://www.iana.org/assignments/link-relations/link-relations.xhtml
    © Copyright 2011 EMC Corporation. All rights reserved.                                  14
REST Principle –
   Hypertext Driven

<?xml version="1.0" encoding="UTF-16"?>
<Patients xmlns="http://www.emc.com/cto/PMR" xmlns:atom="http://www.w3.org/2005/Atom">
  <atom:link rel="self" href="http://localhost:8080/PatientService-xDB/services/patients"/>
  <atom:link rel="init" href="http://localhost:8080/PatientService-xDB/services/patients/init"/>
  <Patient xmlns="http://www.patient.org" xmlns:atom="http://www.w3.org/2005/Atom">
    <atom:link rel="self" href="http://localhost:8080/PatientService-xDB/services/patients/A000015"/>
    <atom:link rel="edit" href="http://localhost:8080/PatientService-xDB/services/patients/A000015"/>
    <atom:link rel="http://www.emc.com/cto/PMR/relationships/prescriptions"
               href="http://localhost:8080/PatientService-xDB/services/patients/A000015/activeprescriptions"/>
    <atom:link rel="http://www.emc.com/cto/PMR/relationships/episodes"
               href="http://localhost:8080/PatientService-xDB/services/patients/A000015/careepisodes"/>
    <name>Steve Scott</name>
    <pid>A000015</pid>
    <dob>05051956</dob>
    <address>Upland, CA</address>
    <ssn>098231234</ssn>
    <insurance>Tufts</insurance>
    <sex>Male</sex>
  </Patient>
</Patients>




   © Copyright 2011 EMC Corporation. All rights reserved.                                                        15
Resources

 •  An Introduction to REST, video by Joe Gregorio,
    http://bitworking.org/news/373/An-Introduction-to-REST
 •  RESTful Web Services, book by Leonard Richardson and Sam Ruby,
    http://www.amazon.com/RESTful-Web-Services-Leonard-Richardson/dp/0596529260
 •  REST in Practice, book by Jim Webber, Savas Parastatidis and Ian Robinson,
    http://www.amazon.com/REST-Practice-Hypermedia-Systems-Architecture/dp/0596805829
 •  REST in Practice, slides by Jim Webber, Savas Parastatidis and Ian Robinson,
    http://www.slideshare.net/guilhermecaelum/rest-in-practice
 •  HTTP 1.1: http://www.w3.org/Protocols/rfc2616/rfc2616.html
 •  Architectural Styles and the Design of Network-based Software Architectures, Roy Fielding’s
      dissertation: http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm




© Copyright 2011 EMC Corporation. All rights reserved.                                            16
Agenda
                                                   REST Principles

                                                   Implementing RESTful Services with
                                                   Spring MVC and the XML REST
                                                   Framework

                                                   What’s next?


© Copyright 2011 EMC Corporation. All rights reserved.                                  17
Implementing the RESTful Interface
    From Richardson and Ruby

                                                             •  Steps 1 & 2: Figure out the data set and identify
                                                                the resources
                                                             •  Step 3: Name the resource with URI
                                                                 –  URI Templates2

                                                             •  Step 4: Define the parts of the uniform interface
                                                                that apply
                                                                 –  Most widely adopted uniform interface includes GET, PUT,
                                                                    POST and DELETE 3
                                                                 –  PATCH is up and coming 4

                                                             •  Steps 5&6: Define resource representations
                                                                 –  Media-types
                                                        1
                                                             •  Step 7: Link to other resources
                                                                 –  Resource representations must include hyperlinks

                                                             •  Steps 8&9: Application flow and error handling

1 http://www.amazon.com/Restful-Web-Services-Leonard-Richardson/dp/0596529260
2   http://tools.ietf.org/html/draft-gregorio-uritemplate-04 3 http://tools.ietf.org/html/rfc2616 4 http://tools.ietf.org/html/rfc5789



    © Copyright 2011 EMC Corporation. All rights reserved.                                                                               18
Design: Steps 1 - 4
Define resources, name them and define uniform interface

                 Patient                                     Resource   URI Template                        Uniform
                                                                                                            Interface
                                                             Patients   /patients                           GET
         Care            Active
         Eps             RXs                                                                                POST
                                                             Patient    /patients/{id}                      GET

Care          Care
                                                                                                            PUT
                        … RX               RX        …
Ep.           Ep.
                                                                                                            DELETE
                                                             Care       /patients/{id}/careepisodes         GET
                                                             Episodes                                       POST
Notes           ORDs           RXs
                                                             Care       /patients/{id}/careepisodes/{cid}   GET
                                                             Episode
O1            O2         …     RX            RX          …   …




© Copyright 2011 EMC Corporation. All rights reserved.                                                                  19
Implementing Resources using Spring
  MVC
•  Resources have classes                                  @Controller
                                                           @RequestMapping("/patients")
   defined with annotations for                            public class Patients {
        –  Resource naming (URI                              ...
           templates)                                        @RequestMapping(method = RequestMethod.GET)
                                                             @ResponseStatus(HttpStatus.OK)
        –  Uniform interface
                                                             public String getPatients
        –  Status codes                                                      (HttpServletRequest request,
                                                                              Model model) {
•  Views provide mechanism                                     ...
   for content negotiation                                   }

                                                               @RequestMapping(method = RequestMethod.POST)
•  Other Java REST frameworks                                  @ResponseStatus(HttpStatus.CREATED)
   available - include Apache CXF2, and                        public String addPatient
   Jersey3 - these support Java API for                                        (HttpServletRequest request,
   RESTful Web Services (Jax-RS)1                                               Model model) {
        –     (Weak) media type support through                  ...
              integration with Jax-B4                          }
                                                               ...
                                                           }
  1   https://jsr311.dev.java.net/ 2 http://cxf.apache.org/    3   https://jersey.dev.java.net/ 4 http://jcp.org/jsr/detail/222.jsp



  © Copyright 2011 EMC Corporation. All rights reserved.                                                                              20
RESTful Service Written in Java


                                        Spring                      Service POJO
                                        Parses URL,                 Accesses
                                        instantiates the right      persistence,
                                        annotated POJO    Patient
                                                                    instantiates model     Results

                                        and calls it.               object and populates
                                                                    with data
                                                                        Patient
                                       … then uses…

                                           String


                                        Marshallers/
                                        Unmarshallers
                                        Serializes model
                                        object into XML or
                                        JSON String




© Copyright 2011 EMC Corporation. All rights reserved.                                               21
…now if we also want Atom
representations


                                        Spring                     Service POJO
                                        Parses URL,                Accesses
                                        instantiates the right     persistence,
                                        annotated POJO             instantiates model Results
                                        and calls it.              object and populates
                                                                   with data
                                                                         FOM-Pat

                                       … then uses …

                                                                 String


                                        Marshallers/
                                                                     Abdera
                                        Unmarshallers                Serializes FOM
                                        Serializes model             object into XML or
                                        object into XML or           JSON String
                                        JSON String




© Copyright 2011 EMC Corporation. All rights reserved.                                          22
How Well Does Spring MVC Address the
Core REST Principles?
                                                         Spring
                                                         MVC
            Feature                                      (alone)   Comments
            Named Resources                                ˜      URI template support -
                                                                   @RequestMapping("/patients/{pid}")
            Define Uniform                                 ˜      @RequestMapping
            Interface                                                     (method =
                                                                   RequestMethod.GET)
                                                                   (+ PUT, POST, DELETE, PATCH,
                                                           ¼



                                                                   etc.)
            Handle media types                             ¼      Handled in the view
            Link to other                                  ™      nothing
            resources
            Implementation                                         Generally happens with a bunch of
                                                                   java code.

© Copyright 2011 EMC Corporation. All rights reserved.                                                  23
The REST XML Framework
 •  We’ve developed a framework that:
           –  Supports rapid development of domain specific RESTful Web Services
           –  Addresses all four REST principles – resources, uniform interface, media
              types, hyperlinking
           –  Promotes reusability and deployment time configuration
           –  Heavily leverages XML
 •  Our framework embraces and extends:
           –  Spring
                     •  Core
                     •  MVC
                     •  AOP
           –  EMC XML Technology
                     •  XML Database – EMC Documentum xDB (w/ XQuery)
                     •  Xproc Engine – Calumet (+ XSLT)
 •  Follows an XRX style
     (Xforms on the client • RESTful interfaces • XQuery on the server)

 O’Reilly published piece: XRX: Simple, Elegant, Disruptive
 http://www.oreillynet.com/xml/blog/2008/05/xrx_a_simple_elegant_disruptiv_1.html


© Copyright 2011 EMC Corporation. All rights reserved.                                   24
RESTful Service – XML as the Dial Tone


                                        Spring                   Service POJO
                                        Parses URL,              Accesses
                                        instantiates the right   persistence,
                                        annotated POJO           generates XML
                                        and calls it.            model and returns




© Copyright 2011 EMC Corporation. All rights reserved.                               25
Model-View-Controller

                                                                  Model
                                                         •  Encapsulates application
                                                            state

                 Queries                                                                              Changes
                   State                    Change                                                    State
                                            Notifications


                               View                                                          Controller
                                                                 Selects View
             •  Renders the model                                                      •  Business Logic
                                                                                       •  Updates Model
                                                              User Selections          •  Selects view for response




© Copyright 2011 EMC Corporation. All rights reserved.                                                                26
Spring MVC & REST

                                                                  Model
                                                         •  Encapsulates application
                                                            state




                               View                                                          Controller
             •  Renders the model                                                      •  Business Logic
                                                                                       •  Updates Model
                                                                                       •  Selects view for response




© Copyright 2011 EMC Corporation. All rights reserved.                                                                27
XML REST Framework
                                                   The (MV) Controller
                                                                Model




                                                         View           Controller




© Copyright 2011 EMC Corporation. All rights reserved.                               28
XML-Centric Implementation
                                                                     XProc Pipeline
                                                              core services implementation

                                                                                      XSLT
                         POJO
                                                            XQuery                 for hyperlink
                     for RESTful
                                                         interface to the         insertion and
                       Service
                                                         persistence tier           media type
                    “declaration”
                                                                                      support




                                                                                   XProc pipeline steps
                                                         XML Database




© Copyright 2011 EMC Corporation. All rights reserved.                                                    29
Our Persistence – EMC Documentum
xDB
Ÿ  Native XML database
Ÿ  Designed for content-oriented
    applications
Ÿ  Ideal for warehousing content
    in an application-neutral format
Ÿ  More flexible than RDBMS for
    unstructured content and for
    aggregating diverse data sets
Ÿ  Extensive, highly productive
    application development
Ÿ  XQuery: powerful search,
    retrieval, linking, and updates
Ÿ  Transaction and full ACID
    support
Ÿ  High-performance, scalable
    architecture, with minimal
    overhead


© Copyright 2011 EMC Corporation. All rights reserved.   30
xDB Multi-node Architecture
•  New in V10.0
•  Data partitioning
   mechanism used
   to scale out
   database
•  Coupled with
   replication
   provides the basis
   of a scale-out
   architecture.


The XML REST FW does not
yet take advantage of the
multi-node feature




© Copyright 2011 EMC Corporation. All rights reserved.   31
(Recall) Design: Steps 1 - 4
Define resources, name them and define uniform interface

                 Patient                                     Resource   URI Template                        Uniform
                                                                                                            Interface
                                                             Patients   /patients                           GET
         Care            Active
         Eps             RXs                                                                                POST
                                                             Patient    /patients/{id}                      GET

Care          Care
                                                                                                            PUT
                        … RX               RX        …
Ep.           Ep.
                                                                                                            DELETE
                                                             Care       /patients/{id}/careepisodes         GET
                                                             Episodes                                       POST
Notes           ORDs           RXs
                                                             Care       /patients/{id}/careepisodes/{cid}   GET
                                                             Episode
O1            O2         …     RX            RX          …   …




© Copyright 2011 EMC Corporation. All rights reserved.                                                                  32
Declaring Services
In the POJO:                                             Encapsulate operation pipeline and design time bindings
          @Controller
          @RequestMapping("/patients")
          public class Patients {
              private static XMLProcessingContext m_getPatientsProcessing = null;
              private static XMLProcessingContext m_addPatientProcessing = null;
              public void setAddPatientProcessing (XMLProcessingContext val) {
                m_addPatientProcessing = val;
              }
              ...
              @RequestMapping(method = RequestMethod.POST)
              @ResponseStatus(HttpStatus.CREATED)
              public String addPatient(HttpServletRequest request,
                                       HttpServletResponse response, Model model) {
                PipelineInputCache pi = new PipelineInputCache();
                  // supply http body as the source for the resource Create pipeline
                  pi.setInputPort("source", request.getInputStream());
                  // supply current resource URL as the base URL to craft hyperlinks
                  String baseUrl = request.getRequestURL().toString();
                  pi.addParameter("stylesheetParameters", new QName("baseURL"),
                                  request.getRequestURL().toString());
                  PipelineOutput output = m_addPatientProcessing.executeOn(pi);

                  ...
              }                                           Runtime XProc pipeline parameter bindings
          }

© Copyright 2011 EMC Corporation. All rights reserved.                                                             33
XProc pipeline
                                                         Source XML                           XSLT
•  Steps (can) have                                      document                             stylesheet

         –  Input ports                                        source                       stylesheet
         –  Output ports
         –  Options                                            source

•  Parameter input ports                                         XQuery


•  Atomic vs. compound steps
                                                                      source                stylesheet
•  Standard atomic step library
                                                                               XSLT
         –  xslt, xquery, http-request,
            xinclude, …
•  Custom steps
         –  Custom compound steps
         –  Step libraries                                                     Result XML
                                                                               document




© Copyright 2011 EMC Corporation. All rights reserved.                                                     34
Binding Operations to XProc Pipelines
 The Spring config:                                            One XML processing context per
<bean id="Patients"                                            operation
                                     class="com.emc.cto.healthcare.Patients">
  <property name="getPatients" ref="getPatientsXMLProcessingContext" />
  <property name="addPatient" ref="addPatientXMLProcessingContext" />
  <property name="getPatient" ref="getPatientXMLProcessingContext" />
  <property name="replacePatient" ref="replacePatientXMLProcessingContext" />
  <property name="deletePatient" ref="deletePatientXMLProcessingContext" />
</bean>

<bean id="addPatientXMLProcessingContext“ class="com.emc.cto.xproc.XProcXMLProcessingContext">
  <property name="xprocPool" ref="xprocPool" />
  <property name="pipelineSource"><value>classpath:resourceCreate.xpl</value></property>
  <property name="inputs">
    <map>
      <entry key="xqueryscript" value="classpath:addPatient.xq" />
      <entry key="stylesheet" value="classpath:hyperlinksPatient.xslt" />
    </map>
  </property>
  <property name="options">
    <map>
      <entry key-ref="iDAssignmentxPath" value="pat:Patient/pat:pid" />
    </map>
  </property>                                              Configure the operation with
  <property name="parameters"><map/></property>
</bean>                                                    the XProc pipeline
                    Set design time parameters
                    into the pipeline
 © Copyright 2011 EMC Corporation. All rights reserved.                                          35
Binding Resource Model to Physical
Model
                              (typically) One xQuery per operation per resource!!

Resource                URI                              Uniform       getPatient.xq
                        Template                         IF             uptPatient.xq

Patients                /patients                        GET
                                                         POST      delPatient.xq
Patient                 /patients/{id}                   GET
                                                         PATCH
                                                         DELETE    getEOC.xq
Care                    /patients/{id}/                  GET
Episodes                careepisodes                     POST
Care                    /patients/{id}/                  GET
Episode                 careepisodes
                        /{cid}
…



© Copyright 2011 EMC Corporation. All rights reserved.                                  36
XSLT Transformations per Resource
Resource                URI                              Uniform   One XSLT per representation
                        Template                         IF
                                                                                PatientsHyperlinks.xslt
Patients                /patients                        GET           Inserts hyperlinks at the collection and entry level
                                                         POST                       PatientHyperlinks.xslt
Patient                 /patients/{id}                   GET                    Inserts hyperlinks in a single Patient

                                                         PATCH                         EOCsHyperlinks.xslt
                                                                           Inserts hyperlinks at the collection and entry level
                                                         DELETE
                                                         GET                             EOCsHyperlinks.xslt
Care                    /patients/{id}/                                       Inserts hyperlinks at the collection and entry level
Episodes                careepisodes                     POST
Care                    /patients/{id}/                  GET                      …
Episode                 careepisodes
                        /{cid}                                              Injected into beans
                                                                            (in spring config)
…
                                                                                                    …


© Copyright 2011 EMC Corporation. All rights reserved.                                                                               37
Sample XSLT for Inserting Hyperlinks
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"   … namespace declarations …>

  <xsl:import href="classpath:insertHyperlinks.xslt" />
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

  <xsl:param name="baseURL"/>

  <xsl:template match="p:Patient" mode="inserthere">
    <atom:link rel="self">
      <xsl:attribute name="href"><xsl:value-of select="$baseURL" /></xsl:attribute>
    </atom:link>
    <atom:link rel="prescriptions">
      <xsl:attribute name="href"><xsl:value-of select="concat($baseURL,'/activeprescriptions')"/>
      </xsl:attribute>
    </atom:link>
    <atom:link rel="episodes">
       <xsl:attribute name="href“><xsl:value-of select="concat($baseURL,'/careepisodes')" />
       </xsl:attribute>
    </atom:link>
    <atom:link rel="up">
      <xsl:attribute name="href">
         <xsl:value-of select="functx:substring-before-last($baseURL,'/')"/></xsl:attribute>
    </atom:link>
  </xsl:template>

</xslt:stylesheet>

  © Copyright 2011 EMC Corporation. All rights reserved.                                                   38
XProc Pipeline Parmeters Passed to
Steps
                                                         Input to XSLT come from XQuery output


       <!-- insert hyperlinks -->
       <p:xslt name="xslt">
              <p:input port='source'>
                        <p:pipe step='xquery' port='result'/>
              </p:input>
              <p:input port='stylesheet'>
                                                                  Input set      at design time
                        <p:pipe step='main' port='stylesheet'/>
              </p:input>
              <p:input port='parameters'>
                        <p:pipe step='main' port='stylesheetParameters'/>

              </p:input>
              <p:with-param port='parameters' name='baseURL' select='/location/text()'>
                        <p:pipe step='locXML' port='result'/>
              </p:with-param>
       </p:xslt>

         Additional parameters passed in from                 Parameters passed from runtime
         earlier steps in the pipeline                        context down to step


© Copyright 2011 EMC Corporation. All rights reserved.                                            39
Controller Returns the Model Entity
In the POJO:
          public class Patients {
               private static XMLProcessingContext m_getPatientsProcessing = null;
               private static XMLProcessingContext m_addPatientProcessing = null;
               public void setAddPatientProcessing (XMLProcessingContext val) {
                 m_addPatientProcessing = val;
               }
               ...
               @RequestMapping(method = RequestMethod.POST)
               @ResponseStatus(HttpStatus.CREATED)
               public String addPatient(HttpServletRequest request,
                                        HttpServletResponse response, Model model) {
                 PipelineInputCache pi = new PipelineInputCache();
                   // supply runtime parameters to the pipeline
                   ...
                   // execute the pipeline
                   PipelineOutput output = m_addPatientProcessing.executeOn(pi);
                   // return model and select view
                   model.addAttribute("pipelineOutput", output);
                   return "pipelineOutput";
              }                                                    Model as XML in PipelineOutput
          }
                     Controller Selects View (note doesn’t select content type)

© Copyright 2011 EMC Corporation. All rights reserved.                                              40
XML REST Framework
                                                   The Model (VC)
                                                                Model




                                                         View           Controller




© Copyright 2011 EMC Corporation. All rights reserved.                               41
RESTful Services
•  Return:                                               HTTP/1.0 201 Created
                                                         Content-Type: application/xml
         –  Resource                                     Location: http://example.com/patients/
                                                         e4abb49c-4a03-4f50-8bab-77e395803ae2
            Representations                              ...
         –  Headers                                      <?xml version="1.0"?>
                                                         <pat:Patient xmlns:pat="http://www.emc.com/cto/PMR">
         –  Status Codes                                     <pat:name>Mary Jane</pat:name>
                                                             <pat:pid>
                                                                e4abb49c-4a03-4f50-8bab-77e395803ae2
                                                             </pat:pid>
•  For example, in Java                                      <pat:dob>07231950</pat:dob>
                                                             <pat:address>Boston</pat:address>
   with Spring MVC, for                                      <pat:ssn>098231234</pat:ssn>
                                                             <pat:insurance>Tufts</pat:insurance>
   HTTP, this is done with                                   <pat:sex>Female</pat:sex>
                                                         </pat:Patient>
   the HttpServletResponse
•  If the implementation is in XProc (and XQuery and XSLT)
   then how do we represent these parts of the model?


© Copyright 2011 EMC Corporation. All rights reserved.                                                          42
XProc Pipeline - Ports
                                                           Source XML                          Base URL
•  XProc pipelines can have multiple                       document

   input and multiple output ports                                source                     parameters


•  The XML REST Framework defines                                source

   a format for multiple output ports:                            replaceNonUuids
        –  Primary output port carries resource
           entity
                                                                               source
        –  Output port named header carries a
           sequence of key value pairs:                             XQuery
                                                                                                          parameters
                                                                                   source
                  <Location>http://example.com/
                          patients/123</Location>                                       XSLT
        –  Output port named error carries
           XML structure with code and
                                                                           Check for
           description:                                                    error
                  <error>
                    <code>404</code>
                    <description>not found</description>
                  </error>

                                                                Headers         Error       Result XML
                                                                                s           document

© Copyright 2011 EMC Corporation. All rights reserved.                                                             43
XProc Port Definitions
Example: for Resource Create Pipeline
           <p:declare-step name="main" xmlns:p="http://www.w3.org/ns/xproc"
                xmlns:c="http://www.w3.org/ns/xproc-step"
                xmlns:pat="http://www.emc.com/cto/PMR"
                version="1.0">
                     <p:input             port='xqueryscript' />
                     <p:input             port='xqueryParameters' kind='parameter'/>
                     <p:input             port='stylesheet'/>
                     <p:input             port='stylesheetParameters' kind='parameter'/>
                     <p:input             port='source'/>
                     <p:output port='result' primary='true'>
                         <p:pipe step='xslt' port='result'/>
                     </p:output>
                     <p:output port='headers' sequence='true'>
                         <p:pipe step='locXML' port='result'/>
                     </p:output>
                     <p:output port='error'>
                         <p:pipe step='checkXquery' port='error' />
                     </p:output>
                  ...




© Copyright 2011 EMC Corporation. All rights reserved.                                     44
Calumet PipelineOutput API
    How the model is surfaced in the POJO
public class Patients {                                      •  The XML REST
      ...                                                       Framework allows the
      @RequestMapping(method = RequestMethod.POST)              PipelineOutput returned
      @ResponseStatus(HttpStatus.CREATED)                       from the pipeline
      public String addPatient
                (HttpServletRequest request,
                                                                execution to be the
                 Model model) {                                 model entity.
      ...
        // execute the pipeline                              •  The services developer
          PipelineOutput output =                               need only return the
             m_addPatientProcessing.executeOn(pi);              Pipeline Output
          // return model and select view
          model.addAttribute
                       ("pipelineOutput", output);
          return "pipelineOutput";
      }                                                      … view classes included in the
}                                                            framework know how to render
                                                             these model objects.



    © Copyright 2011 EMC Corporation. All rights reserved.                                    45
XML REST Framework
                                                   The (M) View (C)
                                                                Model




                                                         View           Controller




© Copyright 2011 EMC Corporation. All rights reserved.                               46
Loose Coupling = Greater Agility
“Just because you can, doesn’t mean you should”
•  Even Spring MVC allows you to build controllers that
   generate resource representations.
    public class Patients {
        ...
        @RequestMapping(method = RequestMethod.POST, headers="content-type=application/xml")
        @ResponseStatus(HttpStatus.CREATED)
        @ResponseBody
        public String addPatientXML(HttpServletRequest request) {
          ...
          // generate response string
          return responseString;
        }

        @RequestMapping(method = RequestMethod.POST, headers="content-type=application/json")
        @ResponseBody
        @ResponseStatus(HttpStatus.CREATED)
        public String addPatientJSON(HttpServletRequest request) {
          ...
          // generate response string
          return responseString; }
    }




© Copyright 2011 EMC Corporation. All rights reserved.                                          47
The Model-View-Controller Pattern
  Encourages loose coupling
Recall the model is a Pipeline Output:
 // return model and select view
 model.addAttribute("pipelineOutput", output);
 return "pipelineOutput";

                   The Framework includes a view that renders PipelineOutput:
                         public class PipelineOutputXMLView extends AbstractView {

                             public PipelineOutputXMLView() {
                               setContentType("application/xml");
                             }

                             @Override
                             protected void renderMergedOutputModel(Map<String, Object> model,
                                        HttpServletRequest request, HttpServletResponse response) {

                                 response.setContentType("application/xml");

                                 PipelineOutput output = (PipelineOutput) model.get("pipelineOutput");
                                 // remember, this is multi-part

                                 ... cont ...




  © Copyright 2011 EMC Corporation. All rights reserved.                                                 48
Rendering the Model (PipelineOutput) -
cont
        ...
        // write the content to the output stream
        // primary output port will be the content
        List<com.emc.documentum.xml.xproc.io.Source> content =
                                                output.getSources(output.getPrimaryOutputPort());

        // handle different datatypes that make come out of an output port
        Node node = sources.get(0).getNode();
        InputStream is = sources.get(0).getInputStream();
        Reader rdr = sources.get(0).getReader();
        ...

        // Transfer headers from the pipeline output to HTTP response headers
        List<com.emc.documentum.xml.xproc.io.Source> headers = output.getSources("headers");
        // Iterate over headers and transfer them to HttpServletResponse
        ...

        // Check for errors
        List<com.emc.documentum.xml.xproc.io.Source> error = output.getSources("error");
        if (error != null) {
          if (!error.isEmpty()) {
            Node errorNode = output.getSources("error").get(0).getNode().getFirstChild();
            response.setStatus(... The right part of the error XML ...);
            return;
          }
        }
    }
}

© Copyright 2011 EMC Corporation. All rights reserved.                                              49
Configuring the View
In the Spring Config File list the view resolvers:
  <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="viewResolvers">
      <list>
        <bean class="org.springframework.web.servlet.view.XmlViewResolver">
          <property name="location"><value>/WEB-INF/viewXML.xml</value></property>
        </bean>
        <bean id="xsltViewResolver"
              class="org.springframework.web.servlet.view.xslt.XsltViewResolver">
          <property name="viewClass"
                    value="com.emc.cto.xproc.spring.view.PipelineOutputAtomView"/>
          <property name="sourceKey" value="pipelineOutput"/>
          <property name="suffix" value=".xsl"/>
          <property name="prefix" value="/WEB-INF/xsl/"/>
        </bean>
      </list>
    </property>
  </bean>

                   And configure the XmlViewResolver (in viewXML.xml) to point to our class:
                         <beans xmlns="http://www.springframework.org/schema/beans"
                               ... more namespace declarations ...>
                           <bean id="pipelineOutput"
                                  class="com.emc.cto.xproc.spring.view.PipelineOutputXMLView" />
                         </beans>




  © Copyright 2011 EMC Corporation. All rights reserved.                                           50
What’s with that XSLT View Resolver?
It renders the Atom media type


                                        Spring                   Service POJO
                                        Parses URL,              Accesses
                                        instantiates the right   persistence,
                                        annotated POJO           generates XML
                                        and calls it.            model and returns




                                                                 And there is more we can do in the
                                           XSLT View
                                           XML transformation                  View…




© Copyright 2011 EMC Corporation. All rights reserved.                                                51
Summarizing the
                                                   Implementation




© Copyright 2011 EMC Corporation. All rights reserved.               52
Implementation Steps
Preconditions: Resource Model and Physical Model are
designed
1.  Craft Java classes – one class per resource type
         –  Declare one XMLProcessingContext per uniform interface operation supported
         –  One method per uniform interface operation supported
                   •  Mostly boilerplate code that sets parameters and invokes XProc pipeline

2.  Craft XProc pipelines (or use templates)
         –  Decide which parameters are bound at design and which at run time
         –  XProc pipeline returns multi-part model object
                   •  Resource
                   •  Header values
                   •  Error codes

3.  Craft XQueries to be invoked in the pipeline
4.  Craft XSLTs to be invoked in the pipeline
         –  Some are part of the creation of the model
         –  Others may be for view creation
5.  Configure views
6.  Glue it all together in the Spring configuration file

© Copyright 2011 EMC Corporation. All rights reserved.                                          53
How Our Framework Measures Up
                                                         Spring
                                                         MVC
   Feature                                               (alone)   Our FW   Comments
   Name Resources                                          ˜        ˜     Use Spring MVC annotated POJOs

   Define Uniform                                          ˜        ˜     Use Spring MVC annotated POJOs
   Interface
   Handle media types                                      ¼        ¼     Spring MVC is goodness.
                                                           ¼



                                                                     ¼
                                                                            Currently exploring stronger typing
   Hyperlinking                                            ™        ˜     Via XSLT

   Implementation                                                    ˜     XML-centric, rapid application
                                                                            development




© Copyright 2011 EMC Corporation. All rights reserved.                                                            54
Agenda
                                                   REST Principles

                                                   Implementing RESTful Services with
                                                   Spring MVC and the XML REST
                                                   Framework

                                                   What’s next?


© Copyright 2011 EMC Corporation. All rights reserved.                                  55
Today…
•  We are leveraging the framework in many
   projects internally, including one product to
   be released later this year.
•  The XMLREST Framework is available on
   the EMC Developer Network:
         –  Version 1, basic framework supporting xDB and
            XQuery:
            https://community.emc.com/docs/DOC-6434
         –  Version 2, adds hyperlink insertion and XSLT
            application:
            https://community.emc.com/docs/DOC-6485
         –  Version 3, moves to Spring MVC and includes
            XProc:
            https://community.emc.com/docs/DOC-10494


•  Includes:
         –  Framework source code
         –  Sample application
         –  Documentation


© Copyright 2011 EMC Corporation. All rights reserved.      56
Continued Areas of Exploration…
 •  Finite State Machine for modeling application state
           –  The hyperlinks inserted to date are part of the model –
              relationships between resources.
           –  Other hyperlinks drive the application state. Examples:
                     •  eCommerce: “check out” link
                     •  vCloud: “shutdown” link
           –  The hyperlinks included in a resource representation are
              dependent on the current state (and other things like ACLs)
 •  Exploring the development environment for constructing
    XQueries, XSLTs and XProc Pipelines
 •  Extending Spring Security (as applied to RESTful services)
    with Obligations
           –  E.g. Access is permitted but requires HTTP and logging.

 •  … Any requests???


© Copyright 2011 EMC Corporation. All rights reserved.                      57
Q&A




© Copyright 2011 EMC Corporation. All rights reserved.   58
© Copyright 2011 EMC Corporation. All rights reserved.   59
THANK YOU



© Copyright 2011 EMC Corporation. All rights reserved.   60

Mais conteúdo relacionado

Mais procurados

Развитие технологий SDN для сетей ЦОД
Развитие технологий SDN для сетей ЦОДРазвитие технологий SDN для сетей ЦОД
Развитие технологий SDN для сетей ЦОД
Cisco Russia
 
Key to Efficient Tiered Storage Infrastructure
Key to Efficient Tiered  Storage InfrastructureKey to Efficient Tiered  Storage Infrastructure
Key to Efficient Tiered Storage Infrastructure
IMEX Research
 
Talk IT_ Oracle_이범_110727
Talk IT_ Oracle_이범_110727Talk IT_ Oracle_이범_110727
Talk IT_ Oracle_이범_110727
Cana Ko
 

Mais procurados (20)

Innovations in Data Grid Technology with Oracle Coherence
Innovations in Data Grid Technology with Oracle CoherenceInnovations in Data Grid Technology with Oracle Coherence
Innovations in Data Grid Technology with Oracle Coherence
 
The Java EE 7 Platform: Developing for the Cloud
The Java EE 7 Platform: Developing for the CloudThe Java EE 7 Platform: Developing for the Cloud
The Java EE 7 Platform: Developing for the Cloud
 
Java EE Technical Keynote at JavaOne Latin America 2011
Java EE Technical Keynote at JavaOne Latin America 2011Java EE Technical Keynote at JavaOne Latin America 2011
Java EE Technical Keynote at JavaOne Latin America 2011
 
Java EE 7: Developing for the Cloud at Geecon, JEEConf, Johannesburg
Java EE 7: Developing for the Cloud at Geecon, JEEConf, JohannesburgJava EE 7: Developing for the Cloud at Geecon, JEEConf, Johannesburg
Java EE 7: Developing for the Cloud at Geecon, JEEConf, Johannesburg
 
The Cloud Concierge
The Cloud ConciergeThe Cloud Concierge
The Cloud Concierge
 
Engineered Systems: Oracle’s Vision for the Future
Engineered Systems: Oracle’s Vision for the FutureEngineered Systems: Oracle’s Vision for the Future
Engineered Systems: Oracle’s Vision for the Future
 
WebLogic 12c Developer Deep Dive at Oracle Develop India 2012
WebLogic 12c Developer Deep Dive at Oracle Develop India 2012WebLogic 12c Developer Deep Dive at Oracle Develop India 2012
WebLogic 12c Developer Deep Dive at Oracle Develop India 2012
 
Java Summit Chennai: Java EE 7
Java Summit Chennai: Java EE 7Java Summit Chennai: Java EE 7
Java Summit Chennai: Java EE 7
 
TDC 2011: OSGi-enabled Java EE Application
TDC 2011: OSGi-enabled Java EE ApplicationTDC 2011: OSGi-enabled Java EE Application
TDC 2011: OSGi-enabled Java EE Application
 
Развитие технологий SDN для сетей ЦОД
Развитие технологий SDN для сетей ЦОДРазвитие технологий SDN для сетей ЦОД
Развитие технологий SDN для сетей ЦОД
 
Extending The Value Of Oracle Crm On Demand Through Cloud Based Extensibility
Extending The Value Of Oracle Crm On Demand Through Cloud Based ExtensibilityExtending The Value Of Oracle Crm On Demand Through Cloud Based Extensibility
Extending The Value Of Oracle Crm On Demand Through Cloud Based Extensibility
 
Key to Efficient Tiered Storage Infrastructure
Key to Efficient Tiered  Storage InfrastructureKey to Efficient Tiered  Storage Infrastructure
Key to Efficient Tiered Storage Infrastructure
 
Java EE 7 at JAX London 2011 and JFall 2011
Java EE 7 at JAX London 2011 and JFall 2011Java EE 7 at JAX London 2011 and JFall 2011
Java EE 7 at JAX London 2011 and JFall 2011
 
PaaSing a Java EE 6 Application at Geecon 2012
PaaSing a Java EE 6 Application at Geecon 2012PaaSing a Java EE 6 Application at Geecon 2012
PaaSing a Java EE 6 Application at Geecon 2012
 
GlassFish Community Update @ JavaOne 2011
GlassFish Community Update @ JavaOne 2011GlassFish Community Update @ JavaOne 2011
GlassFish Community Update @ JavaOne 2011
 
Talk IT_ Oracle_이범_110727
Talk IT_ Oracle_이범_110727Talk IT_ Oracle_이범_110727
Talk IT_ Oracle_이범_110727
 
Cisco Unified Computing Systems Update
Cisco Unified Computing Systems UpdateCisco Unified Computing Systems Update
Cisco Unified Computing Systems Update
 
21st Century SOA
21st Century SOA21st Century SOA
21st Century SOA
 
EMC #1 Open XML Database (OEM)
EMC #1 Open XML Database (OEM)EMC #1 Open XML Database (OEM)
EMC #1 Open XML Database (OEM)
 
The Java EE 7 Platform: Developing for the Cloud
The Java EE 7 Platform: Developing for the CloudThe Java EE 7 Platform: Developing for the Cloud
The Java EE 7 Platform: Developing for the Cloud
 

Destaque

Ergonomie des applications web
Ergonomie des applications webErgonomie des applications web
Ergonomie des applications web
madsgraphics
 
вивчення мотивації вибору професії
вивчення  мотивації вибору професіївивчення  мотивації вибору професії
вивчення мотивації вибору професії
Татьяна Глинская
 
Fri papal response to luther
Fri papal response to lutherFri papal response to luther
Fri papal response to luther
Travis Klein
 
Electrical panel builders in rajasthan www.srelectricals.co.in
Electrical panel builders in rajasthan www.srelectricals.co.inElectrical panel builders in rajasthan www.srelectricals.co.in
Electrical panel builders in rajasthan www.srelectricals.co.in
jkprs
 

Destaque (20)

SpringMVC
SpringMVCSpringMVC
SpringMVC
 
Design REST-ful Web Service
Design REST-ful Web ServiceDesign REST-ful Web Service
Design REST-ful Web Service
 
Designing REST services with Spring MVC
Designing REST services with Spring MVCDesigning REST services with Spring MVC
Designing REST services with Spring MVC
 
Spring Mvc Rest
Spring Mvc RestSpring Mvc Rest
Spring Mvc Rest
 
Ergonomie des applications web
Ergonomie des applications webErgonomie des applications web
Ergonomie des applications web
 
3349
33493349
3349
 
White Paper: EMC FAST Cache — A Detailed Review
White Paper: EMC FAST Cache — A Detailed Review   White Paper: EMC FAST Cache — A Detailed Review
White Paper: EMC FAST Cache — A Detailed Review
 
вивчення мотивації вибору професії
вивчення  мотивації вибору професіївивчення  мотивації вибору професії
вивчення мотивації вибору професії
 
20121025cafesemi
20121025cafesemi20121025cafesemi
20121025cafesemi
 
Formulario devoluciones
Formulario devolucionesFormulario devoluciones
Formulario devoluciones
 
Sub formulario2
Sub formulario2Sub formulario2
Sub formulario2
 
Fri papal response to luther
Fri papal response to lutherFri papal response to luther
Fri papal response to luther
 
Mit2 092 f09_lec15
Mit2 092 f09_lec15Mit2 092 f09_lec15
Mit2 092 f09_lec15
 
Basketball
BasketballBasketball
Basketball
 
20160326Sat「今ここで学びたい!父母になるために本当に大切な産後のこと」
20160326Sat「今ここで学びたい!父母になるために本当に大切な産後のこと」20160326Sat「今ここで学びたい!父母になるために本当に大切な産後のこと」
20160326Sat「今ここで学びたい!父母になるために本当に大切な産後のこと」
 
All About Virtualization
All About VirtualizationAll About Virtualization
All About Virtualization
 
らくがき
らくがきらくがき
らくがき
 
Electrical panel builders in rajasthan www.srelectricals.co.in
Electrical panel builders in rajasthan www.srelectricals.co.inElectrical panel builders in rajasthan www.srelectricals.co.in
Electrical panel builders in rajasthan www.srelectricals.co.in
 
Mon banking
Mon bankingMon banking
Mon banking
 
Frutos da Beneficência Cristã
Frutos da Beneficência CristãFrutos da Beneficência Cristã
Frutos da Beneficência Cristã
 

Semelhante a RESTful SOA and the Spring Framework (EMCWorld 2011)

Cloud foundry elastic architecture and deploy based on openstack
Cloud foundry elastic architecture and deploy based on openstackCloud foundry elastic architecture and deploy based on openstack
Cloud foundry elastic architecture and deploy based on openstack
OpenCity Community
 
Ss Wrap Up Session 13 Aug
Ss Wrap Up Session 13 AugSs Wrap Up Session 13 Aug
Ss Wrap Up Session 13 Aug
WSO2
 
Fusion app tech_con8707_pdf_8707_0001
Fusion app tech_con8707_pdf_8707_0001Fusion app tech_con8707_pdf_8707_0001
Fusion app tech_con8707_pdf_8707_0001
jucaab
 
Oracle my sql cluster cge
Oracle my sql cluster cgeOracle my sql cluster cge
Oracle my sql cluster cge
seungdon1
 
EclipseCon 2013 Learn and share about integrations using Eclipse Lyo, OSLC an...
EclipseCon 2013 Learn and share about integrations using Eclipse Lyo, OSLC an...EclipseCon 2013 Learn and share about integrations using Eclipse Lyo, OSLC an...
EclipseCon 2013 Learn and share about integrations using Eclipse Lyo, OSLC an...
Steve Speicher
 
彭—Elastic architecture in cloud foundry and deploy with openstack
彭—Elastic architecture in cloud foundry and deploy with openstack彭—Elastic architecture in cloud foundry and deploy with openstack
彭—Elastic architecture in cloud foundry and deploy with openstack
OpenCity Community
 

Semelhante a RESTful SOA and the Spring Framework (EMCWorld 2011) (20)

Cloud Computing - Making IT Simple
Cloud Computing - Making IT SimpleCloud Computing - Making IT Simple
Cloud Computing - Making IT Simple
 
Cloud Computing - Making IT Simple
 Cloud Computing - Making IT Simple Cloud Computing - Making IT Simple
Cloud Computing - Making IT Simple
 
Vincent Desveronnieres, Oracle
Vincent Desveronnieres,  OracleVincent Desveronnieres,  Oracle
Vincent Desveronnieres, Oracle
 
An Introduction to IaaS Framework
An Introduction to IaaS FrameworkAn Introduction to IaaS Framework
An Introduction to IaaS Framework
 
Cloud foundry elastic architecture and deploy based on openstack
Cloud foundry elastic architecture and deploy based on openstackCloud foundry elastic architecture and deploy based on openstack
Cloud foundry elastic architecture and deploy based on openstack
 
Research ON Big Data
Research ON Big DataResearch ON Big Data
Research ON Big Data
 
Research on big data
Research on big dataResearch on big data
Research on big data
 
Framework
FrameworkFramework
Framework
 
Ss Wrap Up Session 13 Aug
Ss Wrap Up Session 13 AugSs Wrap Up Session 13 Aug
Ss Wrap Up Session 13 Aug
 
SOA Summer School: Best of SOA Summer School – Encore Session
SOA Summer School: Best of SOA Summer School – Encore Session SOA Summer School: Best of SOA Summer School – Encore Session
SOA Summer School: Best of SOA Summer School – Encore Session
 
Fusion app tech_con8707_pdf_8707_0001
Fusion app tech_con8707_pdf_8707_0001Fusion app tech_con8707_pdf_8707_0001
Fusion app tech_con8707_pdf_8707_0001
 
Transform Microsoft Application Environment With EMC Information Infrastructure
Transform Microsoft Application Environment With EMC Information InfrastructureTransform Microsoft Application Environment With EMC Information Infrastructure
Transform Microsoft Application Environment With EMC Information Infrastructure
 
Oracle my sql cluster cge
Oracle my sql cluster cgeOracle my sql cluster cge
Oracle my sql cluster cge
 
Oracle Cloud Reference Architecture
Oracle Cloud Reference ArchitectureOracle Cloud Reference Architecture
Oracle Cloud Reference Architecture
 
Chris Phillips SCIM Mace-Dir Internet2 Fall Member Meeting Refresh
Chris Phillips SCIM Mace-Dir Internet2 Fall Member Meeting RefreshChris Phillips SCIM Mace-Dir Internet2 Fall Member Meeting Refresh
Chris Phillips SCIM Mace-Dir Internet2 Fall Member Meeting Refresh
 
OSCON 2012 OpenStack Automation and DevOps Best Practices
OSCON 2012 OpenStack Automation and DevOps Best PracticesOSCON 2012 OpenStack Automation and DevOps Best Practices
OSCON 2012 OpenStack Automation and DevOps Best Practices
 
Tech editors conf tucker yen-jacoby revised final for may 24 2012
Tech editors conf tucker yen-jacoby revised final  for may 24 2012Tech editors conf tucker yen-jacoby revised final  for may 24 2012
Tech editors conf tucker yen-jacoby revised final for may 24 2012
 
EclipseCon 2013 Learn and share about integrations using Eclipse Lyo, OSLC an...
EclipseCon 2013 Learn and share about integrations using Eclipse Lyo, OSLC an...EclipseCon 2013 Learn and share about integrations using Eclipse Lyo, OSLC an...
EclipseCon 2013 Learn and share about integrations using Eclipse Lyo, OSLC an...
 
Data center Technologies
Data center TechnologiesData center Technologies
Data center Technologies
 
彭—Elastic architecture in cloud foundry and deploy with openstack
彭—Elastic architecture in cloud foundry and deploy with openstack彭—Elastic architecture in cloud foundry and deploy with openstack
彭—Elastic architecture in cloud foundry and deploy with openstack
 

Mais de EMC

Modern infrastructure for business data lake
Modern infrastructure for business data lakeModern infrastructure for business data lake
Modern infrastructure for business data lake
EMC
 
Virtualization Myths Infographic
Virtualization Myths Infographic Virtualization Myths Infographic
Virtualization Myths Infographic
EMC
 
Data Science and Big Data Analytics Book from EMC Education Services
Data Science and Big Data Analytics Book from EMC Education ServicesData Science and Big Data Analytics Book from EMC Education Services
Data Science and Big Data Analytics Book from EMC Education Services
EMC
 

Mais de EMC (20)

INDUSTRY-LEADING TECHNOLOGY FOR LONG TERM RETENTION OF BACKUPS IN THE CLOUD
INDUSTRY-LEADING  TECHNOLOGY FOR LONG TERM RETENTION OF BACKUPS IN THE CLOUDINDUSTRY-LEADING  TECHNOLOGY FOR LONG TERM RETENTION OF BACKUPS IN THE CLOUD
INDUSTRY-LEADING TECHNOLOGY FOR LONG TERM RETENTION OF BACKUPS IN THE CLOUD
 
Cloud Foundry Summit Berlin Keynote
Cloud Foundry Summit Berlin Keynote Cloud Foundry Summit Berlin Keynote
Cloud Foundry Summit Berlin Keynote
 
EMC GLOBAL DATA PROTECTION INDEX
EMC GLOBAL DATA PROTECTION INDEX EMC GLOBAL DATA PROTECTION INDEX
EMC GLOBAL DATA PROTECTION INDEX
 
Transforming Desktop Virtualization with Citrix XenDesktop and EMC XtremIO
Transforming Desktop Virtualization with Citrix XenDesktop and EMC XtremIOTransforming Desktop Virtualization with Citrix XenDesktop and EMC XtremIO
Transforming Desktop Virtualization with Citrix XenDesktop and EMC XtremIO
 
Citrix ready-webinar-xtremio
Citrix ready-webinar-xtremioCitrix ready-webinar-xtremio
Citrix ready-webinar-xtremio
 
EMC FORUM RESEARCH GLOBAL RESULTS - 10,451 RESPONSES ACROSS 33 COUNTRIES
EMC FORUM RESEARCH GLOBAL RESULTS - 10,451 RESPONSES ACROSS 33 COUNTRIES EMC FORUM RESEARCH GLOBAL RESULTS - 10,451 RESPONSES ACROSS 33 COUNTRIES
EMC FORUM RESEARCH GLOBAL RESULTS - 10,451 RESPONSES ACROSS 33 COUNTRIES
 
EMC with Mirantis Openstack
EMC with Mirantis OpenstackEMC with Mirantis Openstack
EMC with Mirantis Openstack
 
Modern infrastructure for business data lake
Modern infrastructure for business data lakeModern infrastructure for business data lake
Modern infrastructure for business data lake
 
Force Cyber Criminals to Shop Elsewhere
Force Cyber Criminals to Shop ElsewhereForce Cyber Criminals to Shop Elsewhere
Force Cyber Criminals to Shop Elsewhere
 
Pivotal : Moments in Container History
Pivotal : Moments in Container History Pivotal : Moments in Container History
Pivotal : Moments in Container History
 
Data Lake Protection - A Technical Review
Data Lake Protection - A Technical ReviewData Lake Protection - A Technical Review
Data Lake Protection - A Technical Review
 
Mobile E-commerce: Friend or Foe
Mobile E-commerce: Friend or FoeMobile E-commerce: Friend or Foe
Mobile E-commerce: Friend or Foe
 
Virtualization Myths Infographic
Virtualization Myths Infographic Virtualization Myths Infographic
Virtualization Myths Infographic
 
Intelligence-Driven GRC for Security
Intelligence-Driven GRC for SecurityIntelligence-Driven GRC for Security
Intelligence-Driven GRC for Security
 
The Trust Paradox: Access Management and Trust in an Insecure Age
The Trust Paradox: Access Management and Trust in an Insecure AgeThe Trust Paradox: Access Management and Trust in an Insecure Age
The Trust Paradox: Access Management and Trust in an Insecure Age
 
EMC Technology Day - SRM University 2015
EMC Technology Day - SRM University 2015EMC Technology Day - SRM University 2015
EMC Technology Day - SRM University 2015
 
EMC Academic Summit 2015
EMC Academic Summit 2015EMC Academic Summit 2015
EMC Academic Summit 2015
 
Data Science and Big Data Analytics Book from EMC Education Services
Data Science and Big Data Analytics Book from EMC Education ServicesData Science and Big Data Analytics Book from EMC Education Services
Data Science and Big Data Analytics Book from EMC Education Services
 
Using EMC Symmetrix Storage in VMware vSphere Environments
Using EMC Symmetrix Storage in VMware vSphere EnvironmentsUsing EMC Symmetrix Storage in VMware vSphere Environments
Using EMC Symmetrix Storage in VMware vSphere Environments
 
Using EMC VNX storage with VMware vSphereTechBook
Using EMC VNX storage with VMware vSphereTechBookUsing EMC VNX storage with VMware vSphereTechBook
Using EMC VNX storage with VMware vSphereTechBook
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
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
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

RESTful SOA and the Spring Framework (EMCWorld 2011)

  • 1. RESTful SOA and the Spring Framework XML REST Framework and Spring MVC Cornelia Davis Sr. Technologist EMC CTO Office © Copyright 2011 EMC Corporation. All rights reserved. 1
  • 2. Overview Drivers for this work at EMC Ÿ  Goal: Establish an integration architecture that will help EMC bring together its own and partner products. RESTful SOA Ÿ  We’re basing it on REST because: –  In order to get some standardization the principles need to be easy –  The environment is highly distributed and potentially very large – that is, CLOUD –  Product groups are all building RESTful interfaces –  Resource focus §  With media-type handling §  With hyperlinking §  With caching © Copyright 2011 EMC Corporation. All rights reserved. 2
  • 3. Elements of Cloud Computing Cloud computing: “A style of computing where scalable and elastic IT-enabled capabilities are delivered as a service to customers using Internet technologies.” •  Five defining attributes1 •  Best Practices2,3 –  Service-based –  Design for Failure (and nothing –  Scalable and elastic will fail) –  Shared –  Decouple your components –  Metered by use –  Implement elasticity –  Uses Internet technologies –  Think parallel –  Data/compute proximity –  Security 1http://blogs.gartner.com/thomas_bittman/2010/05/18/clarifying-private-cloud-computing/ 2http://www.slideshare.net/ AmazonWebServices/aws-architectingjvariafinal?src=related_normal&rel=3862774 3http:// media.amazonwebservices.com/AWS_Cloud_Best_Practices.pdf © Copyright 2011 EMC Corporation. All rights reserved. 3
  • 4. A Typical, Pre-cloud Application Architecture Persistence Business Logic Presentation Client © Copyright 2011 EMC Corporation. All rights reserved. 4
  • 5. In the Cloud… Scalable and Elastic Persistence Business Logic Service Oriented Presentation Client Internet Infrastructure © Copyright 2011 EMC Corporation. All rights reserved. 5
  • 6. Agenda REST Principles Implementing RESTful Services with Spring MVC and the XML REST Framework What’s next? © Copyright 2011 EMC Corporation. All rights reserved. 6
  • 7. REST Principles •  REST is an architectural style that depends upon: Ÿ Identification and addressability of resources –  All interesting bits of information are identified with URIs and are usually accessed via URL Ÿ The uniform interface –  Interaction with resources through a standardized set of operations, with well understood semantics Ÿ Manipulation of resources through representations –  Media types Ÿ Hypermedia as the engine of application state –  Hyperlink your resources © Copyright 2011 EMC Corporation. All rights reserved. 7
  • 8. REST Principle – Resource Centricity and Addressability •  What: Interface is defined by a set of resources that are addressable •  Why: are resources and addressability important? –  Data is king! –  Relationships between entities are part of the representation – that is, hyperlinks. –  URLs provide a hierarchical, global address space suitable for cloud- based applications –  Achieving scale through a layered, cache-rich infrastructure. C C © Copyright 2011 EMC Corporation. All rights reserved. 8
  • 9. REST Principle – Uniform Interface GET Retrieve a resource Safe, •  What: Each resource representation Idempotent, supports one of a fixed Cacheable set of operations HEAD Retrieve resource Safe, –  Internet based headers Idempotent infrastructure: GET, PUT, POST, DELETE, HEAD OPTIONS Used to get the list of Safe, and OPTIONS verbs supported by this Idempotent –  PATCH, for partial resource update of resource PUT Replace the resource Idempotent •  Why: is a uniform PATCH Update a resource -- interface important? DELETE Delete the resource Idempotent –  Supports certain application patterns (i.e. POST Another operation on a -- retry on fail) resource –  Allows infrastructure to Often used for resource perform operations and creation optimization © Copyright 2011 EMC Corporation. All rights reserved. 9
  • 10. REST Principle – Uniform Interface: Safe •  What: A safe operation is one that can be invoked 0, 1 or more times leaving the resource unchanged •  GET and HEAD SHOULD be safe – (I’d like to say MUST) •  Why: is it good to have safe operations? –  Allows the infrastructure to optimize certain operations – i.e. prefetching resources –  The now defunct Google Web Accelerator did prefetching in the browser –  Real win: User Perceived Performance GET /mySavingsAccount/delete © Copyright 2011 EMC Corporation. All rights reserved. 10
  • 11. REST Principle – Uniform Interface: Idempotent •  What: An idempotent operation is one that can be invoked once or more than one time with the same resource state as a result Idempotent ≠ side effect free •  All safe operations are idempotent •  Additionally, PUT and DELETE are idempotent •  Why: is it good to have idempotent operations? –  #1 fallacy of distributed computing: The network is reliable –  When an operation is idempotent a client can retry if they get no response DELETE /photos/badone.jpg ? DELETE /photos/badone.jpg 204 No Content © Copyright 2011 EMC Corporation. All rights reserved. 11
  • 12. REST Principle – Uniform Interface: Cacheable •  What: A cacheable operation is one where the result may be cached by intermediaries between the client and the server •  GET is cacheable •  Why: is it good to have cachable operations? –  Scalability – intermediaries can cache results lessening the load on the origin server •  Stable URLs are critical! C C © Copyright 2011 EMC Corporation. All rights reserved. 12
  • 13. REST Principle – Media Types •  What: A RESTful interface does not serve resources, rather it serves representations of resources. –  A media type describes the format of the resource representation –  Requests and responses include headers indicating media types •  Why: are media types relevant in RESTful interfaces? –  Key information for client to be able to process results –  Content negotiation §  Client can indicate which content types they can accept – i.e. HTTP GET /patients/123 Accept header Accept: application/atom+xml, text/xml §  Server indicates the content type of the representation returned – i.e. HTTP Content-type header HTTP/1.1 200 OK Content-Type: application/atom+xml –  Intermediaries can perform ... transformations <atom:entry xmlns=“www.w3.org/2005/Atom”> ... –  AtomPub embraces media </atom:entry> types in collection abstraction © Copyright 2011 EMC Corporation. All rights reserved. 13
  • 14. REST Principle – Hypertext Driven •  What: Hypermedia As The Engine Of Application State (HATEOAS) –  Resource representation must be hyperlink rich –  Links to related resources AND for application state transitions (some of which may be resource state transitions) –  Links minimally include a “rel” value and an “href” value –  The Atom Syndication Format1 defines a <link> that is now in widespread use •  Why: are hyperlinks in resource representations important? –  Smaller fixed API and generally looser coupling between the client and server •  URI templates may change –  Client can focus on the semantics of the relationship types (the “rel” values) –  Interoperability – the CMIS2 proposed standard is a good example - RESTful interface defines relationship types but no URI templates –  Standardize link relations – within global3 and within more local scopes 1 http://tools.ietf.org/html/rfc4287 2 http://tools.ietf.org/html/rfc4287 3 http://www.iana.org/assignments/link-relations/link-relations.xhtml © Copyright 2011 EMC Corporation. All rights reserved. 14
  • 15. REST Principle – Hypertext Driven <?xml version="1.0" encoding="UTF-16"?> <Patients xmlns="http://www.emc.com/cto/PMR" xmlns:atom="http://www.w3.org/2005/Atom"> <atom:link rel="self" href="http://localhost:8080/PatientService-xDB/services/patients"/> <atom:link rel="init" href="http://localhost:8080/PatientService-xDB/services/patients/init"/> <Patient xmlns="http://www.patient.org" xmlns:atom="http://www.w3.org/2005/Atom"> <atom:link rel="self" href="http://localhost:8080/PatientService-xDB/services/patients/A000015"/> <atom:link rel="edit" href="http://localhost:8080/PatientService-xDB/services/patients/A000015"/> <atom:link rel="http://www.emc.com/cto/PMR/relationships/prescriptions" href="http://localhost:8080/PatientService-xDB/services/patients/A000015/activeprescriptions"/> <atom:link rel="http://www.emc.com/cto/PMR/relationships/episodes" href="http://localhost:8080/PatientService-xDB/services/patients/A000015/careepisodes"/> <name>Steve Scott</name> <pid>A000015</pid> <dob>05051956</dob> <address>Upland, CA</address> <ssn>098231234</ssn> <insurance>Tufts</insurance> <sex>Male</sex> </Patient> </Patients> © Copyright 2011 EMC Corporation. All rights reserved. 15
  • 16. Resources •  An Introduction to REST, video by Joe Gregorio, http://bitworking.org/news/373/An-Introduction-to-REST •  RESTful Web Services, book by Leonard Richardson and Sam Ruby, http://www.amazon.com/RESTful-Web-Services-Leonard-Richardson/dp/0596529260 •  REST in Practice, book by Jim Webber, Savas Parastatidis and Ian Robinson, http://www.amazon.com/REST-Practice-Hypermedia-Systems-Architecture/dp/0596805829 •  REST in Practice, slides by Jim Webber, Savas Parastatidis and Ian Robinson, http://www.slideshare.net/guilhermecaelum/rest-in-practice •  HTTP 1.1: http://www.w3.org/Protocols/rfc2616/rfc2616.html •  Architectural Styles and the Design of Network-based Software Architectures, Roy Fielding’s dissertation: http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm © Copyright 2011 EMC Corporation. All rights reserved. 16
  • 17. Agenda REST Principles Implementing RESTful Services with Spring MVC and the XML REST Framework What’s next? © Copyright 2011 EMC Corporation. All rights reserved. 17
  • 18. Implementing the RESTful Interface From Richardson and Ruby •  Steps 1 & 2: Figure out the data set and identify the resources •  Step 3: Name the resource with URI –  URI Templates2 •  Step 4: Define the parts of the uniform interface that apply –  Most widely adopted uniform interface includes GET, PUT, POST and DELETE 3 –  PATCH is up and coming 4 •  Steps 5&6: Define resource representations –  Media-types 1 •  Step 7: Link to other resources –  Resource representations must include hyperlinks •  Steps 8&9: Application flow and error handling 1 http://www.amazon.com/Restful-Web-Services-Leonard-Richardson/dp/0596529260 2 http://tools.ietf.org/html/draft-gregorio-uritemplate-04 3 http://tools.ietf.org/html/rfc2616 4 http://tools.ietf.org/html/rfc5789 © Copyright 2011 EMC Corporation. All rights reserved. 18
  • 19. Design: Steps 1 - 4 Define resources, name them and define uniform interface Patient Resource URI Template Uniform Interface Patients /patients GET Care Active Eps RXs POST Patient /patients/{id} GET Care Care PUT … RX RX … Ep. Ep. DELETE Care /patients/{id}/careepisodes GET Episodes POST Notes ORDs RXs Care /patients/{id}/careepisodes/{cid} GET Episode O1 O2 … RX RX … … © Copyright 2011 EMC Corporation. All rights reserved. 19
  • 20. Implementing Resources using Spring MVC •  Resources have classes @Controller @RequestMapping("/patients") defined with annotations for public class Patients { –  Resource naming (URI ... templates) @RequestMapping(method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) –  Uniform interface public String getPatients –  Status codes (HttpServletRequest request, Model model) { •  Views provide mechanism ... for content negotiation } @RequestMapping(method = RequestMethod.POST) •  Other Java REST frameworks @ResponseStatus(HttpStatus.CREATED) available - include Apache CXF2, and public String addPatient Jersey3 - these support Java API for (HttpServletRequest request, RESTful Web Services (Jax-RS)1 Model model) { –  (Weak) media type support through ... integration with Jax-B4 } ... } 1 https://jsr311.dev.java.net/ 2 http://cxf.apache.org/ 3 https://jersey.dev.java.net/ 4 http://jcp.org/jsr/detail/222.jsp © Copyright 2011 EMC Corporation. All rights reserved. 20
  • 21. RESTful Service Written in Java Spring Service POJO Parses URL, Accesses instantiates the right persistence, annotated POJO Patient instantiates model Results and calls it. object and populates with data Patient … then uses… String Marshallers/ Unmarshallers Serializes model object into XML or JSON String © Copyright 2011 EMC Corporation. All rights reserved. 21
  • 22. …now if we also want Atom representations Spring Service POJO Parses URL, Accesses instantiates the right persistence, annotated POJO instantiates model Results and calls it. object and populates with data FOM-Pat … then uses … String Marshallers/ Abdera Unmarshallers Serializes FOM Serializes model object into XML or object into XML or JSON String JSON String © Copyright 2011 EMC Corporation. All rights reserved. 22
  • 23. How Well Does Spring MVC Address the Core REST Principles? Spring MVC Feature (alone) Comments Named Resources ˜ URI template support - @RequestMapping("/patients/{pid}") Define Uniform ˜ @RequestMapping Interface (method = RequestMethod.GET) (+ PUT, POST, DELETE, PATCH, ¼ etc.) Handle media types ¼ Handled in the view Link to other ™ nothing resources Implementation Generally happens with a bunch of java code. © Copyright 2011 EMC Corporation. All rights reserved. 23
  • 24. The REST XML Framework •  We’ve developed a framework that: –  Supports rapid development of domain specific RESTful Web Services –  Addresses all four REST principles – resources, uniform interface, media types, hyperlinking –  Promotes reusability and deployment time configuration –  Heavily leverages XML •  Our framework embraces and extends: –  Spring •  Core •  MVC •  AOP –  EMC XML Technology •  XML Database – EMC Documentum xDB (w/ XQuery) •  Xproc Engine – Calumet (+ XSLT) •  Follows an XRX style (Xforms on the client • RESTful interfaces • XQuery on the server) O’Reilly published piece: XRX: Simple, Elegant, Disruptive http://www.oreillynet.com/xml/blog/2008/05/xrx_a_simple_elegant_disruptiv_1.html © Copyright 2011 EMC Corporation. All rights reserved. 24
  • 25. RESTful Service – XML as the Dial Tone Spring Service POJO Parses URL, Accesses instantiates the right persistence, annotated POJO generates XML and calls it. model and returns © Copyright 2011 EMC Corporation. All rights reserved. 25
  • 26. Model-View-Controller Model •  Encapsulates application state Queries Changes State Change State Notifications View Controller Selects View •  Renders the model •  Business Logic •  Updates Model User Selections •  Selects view for response © Copyright 2011 EMC Corporation. All rights reserved. 26
  • 27. Spring MVC & REST Model •  Encapsulates application state View Controller •  Renders the model •  Business Logic •  Updates Model •  Selects view for response © Copyright 2011 EMC Corporation. All rights reserved. 27
  • 28. XML REST Framework The (MV) Controller Model View Controller © Copyright 2011 EMC Corporation. All rights reserved. 28
  • 29. XML-Centric Implementation XProc Pipeline core services implementation XSLT POJO XQuery for hyperlink for RESTful interface to the insertion and Service persistence tier media type “declaration” support XProc pipeline steps XML Database © Copyright 2011 EMC Corporation. All rights reserved. 29
  • 30. Our Persistence – EMC Documentum xDB Ÿ  Native XML database Ÿ  Designed for content-oriented applications Ÿ  Ideal for warehousing content in an application-neutral format Ÿ  More flexible than RDBMS for unstructured content and for aggregating diverse data sets Ÿ  Extensive, highly productive application development Ÿ  XQuery: powerful search, retrieval, linking, and updates Ÿ  Transaction and full ACID support Ÿ  High-performance, scalable architecture, with minimal overhead © Copyright 2011 EMC Corporation. All rights reserved. 30
  • 31. xDB Multi-node Architecture •  New in V10.0 •  Data partitioning mechanism used to scale out database •  Coupled with replication provides the basis of a scale-out architecture. The XML REST FW does not yet take advantage of the multi-node feature © Copyright 2011 EMC Corporation. All rights reserved. 31
  • 32. (Recall) Design: Steps 1 - 4 Define resources, name them and define uniform interface Patient Resource URI Template Uniform Interface Patients /patients GET Care Active Eps RXs POST Patient /patients/{id} GET Care Care PUT … RX RX … Ep. Ep. DELETE Care /patients/{id}/careepisodes GET Episodes POST Notes ORDs RXs Care /patients/{id}/careepisodes/{cid} GET Episode O1 O2 … RX RX … … © Copyright 2011 EMC Corporation. All rights reserved. 32
  • 33. Declaring Services In the POJO: Encapsulate operation pipeline and design time bindings @Controller @RequestMapping("/patients") public class Patients { private static XMLProcessingContext m_getPatientsProcessing = null; private static XMLProcessingContext m_addPatientProcessing = null; public void setAddPatientProcessing (XMLProcessingContext val) { m_addPatientProcessing = val; } ... @RequestMapping(method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public String addPatient(HttpServletRequest request, HttpServletResponse response, Model model) { PipelineInputCache pi = new PipelineInputCache(); // supply http body as the source for the resource Create pipeline pi.setInputPort("source", request.getInputStream()); // supply current resource URL as the base URL to craft hyperlinks String baseUrl = request.getRequestURL().toString(); pi.addParameter("stylesheetParameters", new QName("baseURL"), request.getRequestURL().toString()); PipelineOutput output = m_addPatientProcessing.executeOn(pi); ... } Runtime XProc pipeline parameter bindings } © Copyright 2011 EMC Corporation. All rights reserved. 33
  • 34. XProc pipeline Source XML XSLT •  Steps (can) have document stylesheet –  Input ports source stylesheet –  Output ports –  Options source •  Parameter input ports XQuery •  Atomic vs. compound steps source stylesheet •  Standard atomic step library XSLT –  xslt, xquery, http-request, xinclude, … •  Custom steps –  Custom compound steps –  Step libraries Result XML document © Copyright 2011 EMC Corporation. All rights reserved. 34
  • 35. Binding Operations to XProc Pipelines The Spring config: One XML processing context per <bean id="Patients" operation class="com.emc.cto.healthcare.Patients"> <property name="getPatients" ref="getPatientsXMLProcessingContext" /> <property name="addPatient" ref="addPatientXMLProcessingContext" /> <property name="getPatient" ref="getPatientXMLProcessingContext" /> <property name="replacePatient" ref="replacePatientXMLProcessingContext" /> <property name="deletePatient" ref="deletePatientXMLProcessingContext" /> </bean> <bean id="addPatientXMLProcessingContext“ class="com.emc.cto.xproc.XProcXMLProcessingContext"> <property name="xprocPool" ref="xprocPool" /> <property name="pipelineSource"><value>classpath:resourceCreate.xpl</value></property> <property name="inputs"> <map> <entry key="xqueryscript" value="classpath:addPatient.xq" /> <entry key="stylesheet" value="classpath:hyperlinksPatient.xslt" /> </map> </property> <property name="options"> <map> <entry key-ref="iDAssignmentxPath" value="pat:Patient/pat:pid" /> </map> </property> Configure the operation with <property name="parameters"><map/></property> </bean> the XProc pipeline Set design time parameters into the pipeline © Copyright 2011 EMC Corporation. All rights reserved. 35
  • 36. Binding Resource Model to Physical Model (typically) One xQuery per operation per resource!! Resource URI Uniform getPatient.xq Template IF uptPatient.xq Patients /patients GET POST delPatient.xq Patient /patients/{id} GET PATCH DELETE getEOC.xq Care /patients/{id}/ GET Episodes careepisodes POST Care /patients/{id}/ GET Episode careepisodes /{cid} … © Copyright 2011 EMC Corporation. All rights reserved. 36
  • 37. XSLT Transformations per Resource Resource URI Uniform One XSLT per representation Template IF PatientsHyperlinks.xslt Patients /patients GET Inserts hyperlinks at the collection and entry level POST PatientHyperlinks.xslt Patient /patients/{id} GET Inserts hyperlinks in a single Patient PATCH EOCsHyperlinks.xslt Inserts hyperlinks at the collection and entry level DELETE GET EOCsHyperlinks.xslt Care /patients/{id}/ Inserts hyperlinks at the collection and entry level Episodes careepisodes POST Care /patients/{id}/ GET … Episode careepisodes /{cid} Injected into beans (in spring config) … … © Copyright 2011 EMC Corporation. All rights reserved. 37
  • 38. Sample XSLT for Inserting Hyperlinks <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" … namespace declarations …> <xsl:import href="classpath:insertHyperlinks.xslt" /> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> <xsl:param name="baseURL"/> <xsl:template match="p:Patient" mode="inserthere"> <atom:link rel="self"> <xsl:attribute name="href"><xsl:value-of select="$baseURL" /></xsl:attribute> </atom:link> <atom:link rel="prescriptions"> <xsl:attribute name="href"><xsl:value-of select="concat($baseURL,'/activeprescriptions')"/> </xsl:attribute> </atom:link> <atom:link rel="episodes"> <xsl:attribute name="href“><xsl:value-of select="concat($baseURL,'/careepisodes')" /> </xsl:attribute> </atom:link> <atom:link rel="up"> <xsl:attribute name="href"> <xsl:value-of select="functx:substring-before-last($baseURL,'/')"/></xsl:attribute> </atom:link> </xsl:template> </xslt:stylesheet> © Copyright 2011 EMC Corporation. All rights reserved. 38
  • 39. XProc Pipeline Parmeters Passed to Steps Input to XSLT come from XQuery output <!-- insert hyperlinks --> <p:xslt name="xslt"> <p:input port='source'> <p:pipe step='xquery' port='result'/> </p:input> <p:input port='stylesheet'> Input set at design time <p:pipe step='main' port='stylesheet'/> </p:input> <p:input port='parameters'> <p:pipe step='main' port='stylesheetParameters'/> </p:input> <p:with-param port='parameters' name='baseURL' select='/location/text()'> <p:pipe step='locXML' port='result'/> </p:with-param> </p:xslt> Additional parameters passed in from Parameters passed from runtime earlier steps in the pipeline context down to step © Copyright 2011 EMC Corporation. All rights reserved. 39
  • 40. Controller Returns the Model Entity In the POJO: public class Patients { private static XMLProcessingContext m_getPatientsProcessing = null; private static XMLProcessingContext m_addPatientProcessing = null; public void setAddPatientProcessing (XMLProcessingContext val) { m_addPatientProcessing = val; } ... @RequestMapping(method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public String addPatient(HttpServletRequest request, HttpServletResponse response, Model model) { PipelineInputCache pi = new PipelineInputCache(); // supply runtime parameters to the pipeline ... // execute the pipeline PipelineOutput output = m_addPatientProcessing.executeOn(pi); // return model and select view model.addAttribute("pipelineOutput", output); return "pipelineOutput"; } Model as XML in PipelineOutput } Controller Selects View (note doesn’t select content type) © Copyright 2011 EMC Corporation. All rights reserved. 40
  • 41. XML REST Framework The Model (VC) Model View Controller © Copyright 2011 EMC Corporation. All rights reserved. 41
  • 42. RESTful Services •  Return: HTTP/1.0 201 Created Content-Type: application/xml –  Resource Location: http://example.com/patients/ e4abb49c-4a03-4f50-8bab-77e395803ae2 Representations ... –  Headers <?xml version="1.0"?> <pat:Patient xmlns:pat="http://www.emc.com/cto/PMR"> –  Status Codes <pat:name>Mary Jane</pat:name> <pat:pid> e4abb49c-4a03-4f50-8bab-77e395803ae2 </pat:pid> •  For example, in Java <pat:dob>07231950</pat:dob> <pat:address>Boston</pat:address> with Spring MVC, for <pat:ssn>098231234</pat:ssn> <pat:insurance>Tufts</pat:insurance> HTTP, this is done with <pat:sex>Female</pat:sex> </pat:Patient> the HttpServletResponse •  If the implementation is in XProc (and XQuery and XSLT) then how do we represent these parts of the model? © Copyright 2011 EMC Corporation. All rights reserved. 42
  • 43. XProc Pipeline - Ports Source XML Base URL •  XProc pipelines can have multiple document input and multiple output ports source parameters •  The XML REST Framework defines source a format for multiple output ports: replaceNonUuids –  Primary output port carries resource entity source –  Output port named header carries a sequence of key value pairs: XQuery parameters source <Location>http://example.com/ patients/123</Location> XSLT –  Output port named error carries XML structure with code and Check for description: error <error> <code>404</code> <description>not found</description> </error> Headers Error Result XML s document © Copyright 2011 EMC Corporation. All rights reserved. 43
  • 44. XProc Port Definitions Example: for Resource Create Pipeline <p:declare-step name="main" xmlns:p="http://www.w3.org/ns/xproc" xmlns:c="http://www.w3.org/ns/xproc-step" xmlns:pat="http://www.emc.com/cto/PMR" version="1.0"> <p:input port='xqueryscript' /> <p:input port='xqueryParameters' kind='parameter'/> <p:input port='stylesheet'/> <p:input port='stylesheetParameters' kind='parameter'/> <p:input port='source'/> <p:output port='result' primary='true'> <p:pipe step='xslt' port='result'/> </p:output> <p:output port='headers' sequence='true'> <p:pipe step='locXML' port='result'/> </p:output> <p:output port='error'> <p:pipe step='checkXquery' port='error' /> </p:output> ... © Copyright 2011 EMC Corporation. All rights reserved. 44
  • 45. Calumet PipelineOutput API How the model is surfaced in the POJO public class Patients { •  The XML REST ... Framework allows the @RequestMapping(method = RequestMethod.POST) PipelineOutput returned @ResponseStatus(HttpStatus.CREATED) from the pipeline public String addPatient (HttpServletRequest request, execution to be the Model model) { model entity. ... // execute the pipeline •  The services developer PipelineOutput output = need only return the m_addPatientProcessing.executeOn(pi); Pipeline Output // return model and select view model.addAttribute ("pipelineOutput", output); return "pipelineOutput"; } … view classes included in the } framework know how to render these model objects. © Copyright 2011 EMC Corporation. All rights reserved. 45
  • 46. XML REST Framework The (M) View (C) Model View Controller © Copyright 2011 EMC Corporation. All rights reserved. 46
  • 47. Loose Coupling = Greater Agility “Just because you can, doesn’t mean you should” •  Even Spring MVC allows you to build controllers that generate resource representations. public class Patients { ... @RequestMapping(method = RequestMethod.POST, headers="content-type=application/xml") @ResponseStatus(HttpStatus.CREATED) @ResponseBody public String addPatientXML(HttpServletRequest request) { ... // generate response string return responseString; } @RequestMapping(method = RequestMethod.POST, headers="content-type=application/json") @ResponseBody @ResponseStatus(HttpStatus.CREATED) public String addPatientJSON(HttpServletRequest request) { ... // generate response string return responseString; } } © Copyright 2011 EMC Corporation. All rights reserved. 47
  • 48. The Model-View-Controller Pattern Encourages loose coupling Recall the model is a Pipeline Output: // return model and select view model.addAttribute("pipelineOutput", output); return "pipelineOutput"; The Framework includes a view that renders PipelineOutput: public class PipelineOutputXMLView extends AbstractView { public PipelineOutputXMLView() { setContentType("application/xml"); } @Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) { response.setContentType("application/xml"); PipelineOutput output = (PipelineOutput) model.get("pipelineOutput"); // remember, this is multi-part ... cont ... © Copyright 2011 EMC Corporation. All rights reserved. 48
  • 49. Rendering the Model (PipelineOutput) - cont ... // write the content to the output stream // primary output port will be the content List<com.emc.documentum.xml.xproc.io.Source> content = output.getSources(output.getPrimaryOutputPort()); // handle different datatypes that make come out of an output port Node node = sources.get(0).getNode(); InputStream is = sources.get(0).getInputStream(); Reader rdr = sources.get(0).getReader(); ... // Transfer headers from the pipeline output to HTTP response headers List<com.emc.documentum.xml.xproc.io.Source> headers = output.getSources("headers"); // Iterate over headers and transfer them to HttpServletResponse ... // Check for errors List<com.emc.documentum.xml.xproc.io.Source> error = output.getSources("error"); if (error != null) { if (!error.isEmpty()) { Node errorNode = output.getSources("error").get(0).getNode().getFirstChild(); response.setStatus(... The right part of the error XML ...); return; } } } } © Copyright 2011 EMC Corporation. All rights reserved. 49
  • 50. Configuring the View In the Spring Config File list the view resolvers: <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="viewResolvers"> <list> <bean class="org.springframework.web.servlet.view.XmlViewResolver"> <property name="location"><value>/WEB-INF/viewXML.xml</value></property> </bean> <bean id="xsltViewResolver" class="org.springframework.web.servlet.view.xslt.XsltViewResolver"> <property name="viewClass" value="com.emc.cto.xproc.spring.view.PipelineOutputAtomView"/> <property name="sourceKey" value="pipelineOutput"/> <property name="suffix" value=".xsl"/> <property name="prefix" value="/WEB-INF/xsl/"/> </bean> </list> </property> </bean> And configure the XmlViewResolver (in viewXML.xml) to point to our class: <beans xmlns="http://www.springframework.org/schema/beans" ... more namespace declarations ...> <bean id="pipelineOutput" class="com.emc.cto.xproc.spring.view.PipelineOutputXMLView" /> </beans> © Copyright 2011 EMC Corporation. All rights reserved. 50
  • 51. What’s with that XSLT View Resolver? It renders the Atom media type Spring Service POJO Parses URL, Accesses instantiates the right persistence, annotated POJO generates XML and calls it. model and returns And there is more we can do in the XSLT View XML transformation View… © Copyright 2011 EMC Corporation. All rights reserved. 51
  • 52. Summarizing the Implementation © Copyright 2011 EMC Corporation. All rights reserved. 52
  • 53. Implementation Steps Preconditions: Resource Model and Physical Model are designed 1.  Craft Java classes – one class per resource type –  Declare one XMLProcessingContext per uniform interface operation supported –  One method per uniform interface operation supported •  Mostly boilerplate code that sets parameters and invokes XProc pipeline 2.  Craft XProc pipelines (or use templates) –  Decide which parameters are bound at design and which at run time –  XProc pipeline returns multi-part model object •  Resource •  Header values •  Error codes 3.  Craft XQueries to be invoked in the pipeline 4.  Craft XSLTs to be invoked in the pipeline –  Some are part of the creation of the model –  Others may be for view creation 5.  Configure views 6.  Glue it all together in the Spring configuration file © Copyright 2011 EMC Corporation. All rights reserved. 53
  • 54. How Our Framework Measures Up Spring MVC Feature (alone) Our FW Comments Name Resources ˜ ˜ Use Spring MVC annotated POJOs Define Uniform ˜ ˜ Use Spring MVC annotated POJOs Interface Handle media types ¼ ¼ Spring MVC is goodness. ¼ ¼ Currently exploring stronger typing Hyperlinking ™ ˜ Via XSLT Implementation ˜ XML-centric, rapid application development © Copyright 2011 EMC Corporation. All rights reserved. 54
  • 55. Agenda REST Principles Implementing RESTful Services with Spring MVC and the XML REST Framework What’s next? © Copyright 2011 EMC Corporation. All rights reserved. 55
  • 56. Today… •  We are leveraging the framework in many projects internally, including one product to be released later this year. •  The XMLREST Framework is available on the EMC Developer Network: –  Version 1, basic framework supporting xDB and XQuery: https://community.emc.com/docs/DOC-6434 –  Version 2, adds hyperlink insertion and XSLT application: https://community.emc.com/docs/DOC-6485 –  Version 3, moves to Spring MVC and includes XProc: https://community.emc.com/docs/DOC-10494 •  Includes: –  Framework source code –  Sample application –  Documentation © Copyright 2011 EMC Corporation. All rights reserved. 56
  • 57. Continued Areas of Exploration… •  Finite State Machine for modeling application state –  The hyperlinks inserted to date are part of the model – relationships between resources. –  Other hyperlinks drive the application state. Examples: •  eCommerce: “check out” link •  vCloud: “shutdown” link –  The hyperlinks included in a resource representation are dependent on the current state (and other things like ACLs) •  Exploring the development environment for constructing XQueries, XSLTs and XProc Pipelines •  Extending Spring Security (as applied to RESTful services) with Obligations –  E.g. Access is permitted but requires HTTP and logging. •  … Any requests??? © Copyright 2011 EMC Corporation. All rights reserved. 57
  • 58. Q&A © Copyright 2011 EMC Corporation. All rights reserved. 58
  • 59. © Copyright 2011 EMC Corporation. All rights reserved. 59
  • 60. THANK YOU © Copyright 2011 EMC Corporation. All rights reserved. 60