Mais conteúdo relacionado
Semelhante a RESTful SOA and the Spring Framework (EMCWorld 2011) (20)
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