SlideShare a Scribd company logo
1 of 48
Download to read offline
MONTREAL JUNE 30, JULY 1ST AND 2ND 2012




ERRest in Depth
Pascal Robert
MacTI.ca
The Menu

•   Request/response loop

•   Behavior changes

•   Formats

•   Transactions

•   Same Origin Policy

•   Date and time management
Request handling
Request
               Application.dispatchRequest




ERXRouteRequestHandler(WOActionRequestHandler).handleR
                       equest




 YourController(ERXRouteController).performActionNamed
performActionNamed
checkAccess()



•   Default implementation in ERXRouteController does nothing

•   Override it in your controller for security check
performHtmlActionNamed

•   Does <EntityName><ActionName>Page component exists?

    •   No: fall back to controller

    •   Yes: Check if component implements IEXRouteComponent

        •   Yes: return the component

        •   No: fall back to controller
shouldFailOnMissingHtmlPage


•   Does the component was not found or don't implement
    IEXRouteComponent?

    •   If shouldFailOnMissingHtmlPage() returns true, call
        performUnknownAction (will return a 404 NotFound)

    •   Default is false, override it in your controller if needed.
performRouteActionNamed


•   Try to find <actionName>Action method.

    •   Not found? Try to find <actionName> method.

    •   Still nothing? Check for annotations.

    •   Still nothing? Call performUnknownAction

    •   Got something? Call performActionWithArguments
performUnknownAction


•   if (ERXRest.strictMode)

    •   throw ERXNotAllowedException (HTTP code 405)

•   else

    •   throw FileNotFoundException (HTTP code 404)
performActionWithArguments




•   Will invoke the method with the arguments
Objects management
Objects in routes

•   /ra/<entityName>/{entity:EntityName}

•   routeObjectForKey(key)

•   create(filter)

•   update(object, filter)
routeObjectForKey


•   {<keyName>:<keyType>} in route = keyType result =
    routeObjectForKey(<keyName>)

•   Object is obtained by ERXRestUtils.coerceValueToTypeNamed
coerceValueToTypeNamed

•   Where value is transformed to a object or primitive

•   If it's an EO or POJO, will use
    ERXRestClassDescriptionFactory.classDescriptionForEntityName to find the
    class

•   Will call
    IERXRestDelegate.Factory.delegateForClassDescription().objectOfEntityWithI
    D()
create(filter)

•   Will call ERXRestClassDescriptionFactory.classDescriptionForEntityName

•   Will call
    IERXRestDelegate.Factory.delegateForClassDescription().createObjectOfEnti
    tyWithID to create a basic EO/POJO

•   Will call updateObjectWithFilter()
update(object, filter)



•   As with create(filter), will simply call updateObjectWithFilter
updateObjectWithFilter



•   Major method

•   Will take content from request and update object (PUT request)

•   Also used to populate new object (POST request)
Response handling
response(object, filter)


•   Will built up the object graph with
    ERXRestRequestNode.requestNodeWithObjectAndFilter

•   Will call response(format, responseNode)
requestNodeWithObjectAndFilter




•   If primitive/simple object, will set the value

•   If EO/POJO, will call _fillInWithObjectAndFilter
_fillInWithObjectAndFilter



•   If object is an array, method take itself

•   If not array, will use object's delegate to call primaryKeyForObject, and
    call _addAttributesAndRelationshipsForObjectOfEntity
response(format, responseNode)



•   Returns result of ERXRouteResults(context, restContext, format,
    responseNode)

•   ERXRouteResults.generateResponse() will actually generate the response
    in requested format
response(ERXRestFetchSpecification,
                 filter)


•   Useful to return list of objects ("index" action)
•   ERXRestFetchSpecification allow you to set ordering, range, filtering and
    batching from request

•   Will also call response(format, responseNode)
response(int)


•   Use that one to send a response without any content in the body

•   Check ERXHttpStatusCodes
There's a property for that
"id" key


•   ERXRest.idKey : what to use instead of "id"
    Default: {"id":2 }
    ERRest.idKey=primaryKey {"primaryKey":2 }
"nil" key
•   ERXRest.nilKey
    To rewrite the "nil" attribute
    Default: <someAttribute nil="true"/>

    ERXRest.nilKey=cestVide -> <someAttribute cestVide="true"/>

•   ERXRest.writeNilKey
    Skip the "nil" attribute
    Default: <someAttribute nil="true"/>

    ERXRest.writeNilKey=false -> <someAttribute nil="true"/>
"type" key
•   ERXRest.typeKey
    Allow you to change the name of the "type" attribute

    Default: {"type":"NameOfEntity"}

    ERXRest.typeKey=entityName {"entityName":"NameOfEntity"}

•   ERXRest.writeTypeKey
    If false, won't write the "type" attribute in the response

    ERXRest.writeTypeKey=false -> {id: 2, "type":"NameOfEntity"}
ERXRest.pluralEntityNames


•   Default is true

•   If set to false, can't use pluralized names
    Default: /ra/restEntities

    Set to false: /ra/restEntities
ERXRest.suppressTypeAttributesForSimpl
                   eTypes
•   Only for XML format

•   Default value is false

•   Default rendering:
    <RestEntity primaryKey="1">
     <someAttribute type = "integer">2</someAttribute>
    </RestEntity>

•   When set to false:
    <RestEntity primaryKey="1">
     <someAttribute type = "integer">2</someAttribute>
ERXRest.strictMode


•   Default is: true

•   For missing route, will send 405 (Not Allowed) code, if set to false,
    will send 404 (Not Found)

•   POST requests: will send 201 (Created), if false will send 200 (OK)
ERXRest.routeCase

•   ERXRest.routeCase=LowerCamelCase
    /ra/restEntities

•   ERXRest.routeCase=CamelCase
    /ra/RestEntities

•   ERXRest.routeCase=LowercaseUnderscore
    /ra/rest_entities
ERXRest.parseUnknownExtensions


•   /ra/restEntities/3.fsdfsd

•   If set to true (the default):
    HTTP/1.1 200 Apple WebObjects

    Content-Type: text/html

•   If set to false:
    HTTP/1.0 400 Apple WebObjects
Formats
ERXRest.defaultFormat



•   ERXRest.defaultFormat=json|xml|plist|html|...

•   Let you specify the default format for all controllers

•   Can override it per controller:
    protected ERXRestFormat defaultFormat() {
        return ERXRestFormat.json();
    }
Format detection

•   Format detection is in ERXRouteController.format()

•   Order of detection

    •   From extension (.json). Set in
        ERXRouteRequestHandler.routeForMethodAndPath()

    •   From the Content-Type header

    •   Default format (defaultFormat() in controller)
Adding new format


•   Your own private format? Use
    ERXRestFormat.registerFormatNamed()

•   Format useful for the commumity? Add them to ERXRestFormat
Same Domain Policy
Same Origin Policy

•   Problem: browsers won't load data if client and server not on same
    domain

•   Numerous ways: window.name transport, JSONP and Cross-origin
    resource sharing (CORS)

•   CORS and window.name transport support is part of ERRest
CORS

•   Works with Gecko 1.9.1 (Firefox 3.5+), WebKit (Safari 4+, Google
    Chrome 3+), Opera 12 and IE 8+

•   Send extra headers to server

•   Client specifiy origin, requested HTTP verb and allowed headers,
    server returns allowed origin, methods, headers and max-age
CORS preflight
Client request:

OPTIONS /resources/post-here/ HTTP/1.1
Origin: http://foo.example
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-PINGOTHER

Server response:

HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER
Access-Control-Max-Age: 1728000

Client request:

GET /resources/post-here/ HTTP/1.1
Origin: http://foo.example

Server response:

HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://foo.example
CORS

•   ERXRest.accessControlAllowRequestHeaders

•   ERXRest.accessControlAllowRequestMethods

•   ERXRest.accessControlMaxAge (default: 1728000)

•   ERXRest.accessControlAllowOrigin ('*' to allow all)
window.name Transport

•   Dojo use that trick

•   Client send ?windowname=true in URL

•   Enable it on server with:
    ERXRest.allowWindowNameCrossDomainTransport=true

•   Will wrap response in HTML code:
    <html><script type="text/javascript">window.name='{"id":
    4,"type":"RestEntity","someAttribute":"commit transaction"}';</script></html>
Status codes
Status code and exceptions
•   ObjectNotAvailableException, FileNotFoundException,
    NoSuchElementException: returns a 404 (Not Found)

•   SecurityException: returns a 403 (Forbidden)

•   ERXNotAllowedException: returns a 405 (Method Not Allowed)

•   ERXValidationException, NSValidation.ValidationException: returns a 400 (Bad
    Request)

•   Anything else: returns a 500 (Internal Server Error)

•   Avoid sending 5xx codes if the client made a mistake!
Adding support for new data types

•   Add a processor in _ERXJSONConfig

•   Add support code in ERXRestUtils
    •   isPrimitive()

    •   coerceValueToString()

    •   coerceValueToTypeNamed

•   For dates: add formatter in ERXRestUtils
MONTREAL JUNE 30, JULY 1ST AND 2ND 2012




Q&A

More Related Content

What's hot

Web весна 2013 лекция 6
Web весна 2013 лекция 6Web весна 2013 лекция 6
Web весна 2013 лекция 6
Technopark
 
Web осень 2012 лекция 6
Web осень 2012 лекция 6Web осень 2012 лекция 6
Web осень 2012 лекция 6
Technopark
 
Developing Useful APIs
Developing Useful APIsDeveloping Useful APIs
Developing Useful APIs
Dmitry Buzdin
 

What's hot (20)

QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
 
Web весна 2013 лекция 6
Web весна 2013 лекция 6Web весна 2013 лекция 6
Web весна 2013 лекция 6
 
Solr workshop
Solr workshopSolr workshop
Solr workshop
 
Jstl Guide
Jstl GuideJstl Guide
Jstl Guide
 
QA Lab: тестирование ПО. Яков Крамаренко: "KISS Automation"
QA Lab: тестирование ПО. Яков Крамаренко: "KISS Automation"QA Lab: тестирование ПО. Яков Крамаренко: "KISS Automation"
QA Lab: тестирование ПО. Яков Крамаренко: "KISS Automation"
 
Web осень 2012 лекция 6
Web осень 2012 лекция 6Web осень 2012 лекция 6
Web осень 2012 лекция 6
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScript
 
ExtJs Basic Part-1
ExtJs Basic Part-1ExtJs Basic Part-1
ExtJs Basic Part-1
 
55 New Features in Java 7
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web Stack
 
Object Oriented Exploitation: New techniques in Windows mitigation bypass
Object Oriented Exploitation: New techniques in Windows mitigation bypassObject Oriented Exploitation: New techniques in Windows mitigation bypass
Object Oriented Exploitation: New techniques in Windows mitigation bypass
 
Codegeneration With Xtend
Codegeneration With XtendCodegeneration With Xtend
Codegeneration With Xtend
 
JSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTLJSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTL
 
Django Pro ORM
Django Pro ORMDjango Pro ORM
Django Pro ORM
 
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007
 
J query
J queryJ query
J query
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsUsing the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service Clients
 
Advanced Django ORM techniques
Advanced Django ORM techniquesAdvanced Django ORM techniques
Advanced Django ORM techniques
 
Developing Useful APIs
Developing Useful APIsDeveloping Useful APIs
Developing Useful APIs
 
J query1
J query1J query1
J query1
 

Similar to ERRest in Depth

Hidden Treasures in Project Wonder
Hidden Treasures in Project WonderHidden Treasures in Project Wonder
Hidden Treasures in Project Wonder
WO Community
 
Lucene for Solr Developers
Lucene for Solr DevelopersLucene for Solr Developers
Lucene for Solr Developers
Erik Hatcher
 
Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010
Rob Windsor
 
Concurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksConcurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background Tasks
WO Community
 
appengine java night #1
appengine java night #1appengine java night #1
appengine java night #1
Shinichi Ogawa
 
Appengine Java Night #2a
Appengine Java Night #2aAppengine Java Night #2a
Appengine Java Night #2a
Shinichi Ogawa
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
Michelangelo van Dam
 

Similar to ERRest in Depth (20)

Hidden Treasures in Project Wonder
Hidden Treasures in Project WonderHidden Treasures in Project Wonder
Hidden Treasures in Project Wonder
 
Lucene for Solr Developers
Lucene for Solr DevelopersLucene for Solr Developers
Lucene for Solr Developers
 
Tutorial, Part 3: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 3: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...Tutorial, Part 3: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 3: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
 
Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010
 
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
 
Developer testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing FanaticDeveloper testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing Fanatic
 
AJAX.ppt
AJAX.pptAJAX.ppt
AJAX.ppt
 
Phoenix + Reactで 社内システムを 密かに作ってる
Phoenix + Reactで 社内システムを 密かに作ってるPhoenix + Reactで 社内システムを 密かに作ってる
Phoenix + Reactで 社内システムを 密かに作ってる
 
Custom EOAdaptors and ERSolr
Custom EOAdaptors and ERSolrCustom EOAdaptors and ERSolr
Custom EOAdaptors and ERSolr
 
Requery overview
Requery overviewRequery overview
Requery overview
 
AJAX Transport Layer
AJAX Transport LayerAJAX Transport Layer
AJAX Transport Layer
 
Building High Performance Web Applications and Sites
Building High Performance Web Applications and SitesBuilding High Performance Web Applications and Sites
Building High Performance Web Applications and Sites
 
Tutorial on developing a Solr search component plugin
Tutorial on developing a Solr search component pluginTutorial on developing a Solr search component plugin
Tutorial on developing a Solr search component plugin
 
Concurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksConcurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background Tasks
 
Refactoring
RefactoringRefactoring
Refactoring
 
appengine java night #1
appengine java night #1appengine java night #1
appengine java night #1
 
Appengine Java Night #2a
Appengine Java Night #2aAppengine Java Night #2a
Appengine Java Night #2a
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
 
Full Text Search In PostgreSQL
Full Text Search In PostgreSQLFull Text Search In PostgreSQL
Full Text Search In PostgreSQL
 

More from WO Community

More from WO Community (20)

In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engine
 
Using Nagios to monitor your WO systems
Using Nagios to monitor your WO systemsUsing Nagios to monitor your WO systems
Using Nagios to monitor your WO systems
 
Build and deployment
Build and deploymentBuild and deployment
Build and deployment
 
High availability
High availabilityHigh availability
High availability
 
Reenabling SOAP using ERJaxWS
Reenabling SOAP using ERJaxWSReenabling SOAP using ERJaxWS
Reenabling SOAP using ERJaxWS
 
Chaining the Beast - Testing Wonder Applications in the Real World
Chaining the Beast - Testing Wonder Applications in the Real WorldChaining the Beast - Testing Wonder Applications in the Real World
Chaining the Beast - Testing Wonder Applications in the Real World
 
D2W Stateful Controllers
D2W Stateful ControllersD2W Stateful Controllers
D2W Stateful Controllers
 
Deploying WO on Windows
Deploying WO on WindowsDeploying WO on Windows
Deploying WO on Windows
 
Unit Testing with WOUnit
Unit Testing with WOUnitUnit Testing with WOUnit
Unit Testing with WOUnit
 
Life outside WO
Life outside WOLife outside WO
Life outside WO
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO Devs
 
Advanced Apache Cayenne
Advanced Apache CayenneAdvanced Apache Cayenne
Advanced Apache Cayenne
 
Migrating existing Projects to Wonder
Migrating existing Projects to WonderMigrating existing Projects to Wonder
Migrating existing Projects to Wonder
 
iOS for ERREST - alternative version
iOS for ERREST - alternative versioniOS for ERREST - alternative version
iOS for ERREST - alternative version
 
iOS for ERREST
iOS for ERRESTiOS for ERREST
iOS for ERREST
 
"Framework Principal" pattern
"Framework Principal" pattern"Framework Principal" pattern
"Framework Principal" pattern
 
WOver
WOverWOver
WOver
 
Localizing your apps for multibyte languages
Localizing your apps for multibyte languagesLocalizing your apps for multibyte languages
Localizing your apps for multibyte languages
 
WOdka
WOdkaWOdka
WOdka
 
ERGroupware
ERGroupwareERGroupware
ERGroupware
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

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
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
"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 ...
 
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
 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptx
 
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...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using Ballerina
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Quantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation ComputingQuantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation Computing
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 

ERRest in Depth

  • 1. MONTREAL JUNE 30, JULY 1ST AND 2ND 2012 ERRest in Depth Pascal Robert MacTI.ca
  • 2. The Menu • Request/response loop • Behavior changes • Formats • Transactions • Same Origin Policy • Date and time management
  • 4. Request Application.dispatchRequest ERXRouteRequestHandler(WOActionRequestHandler).handleR equest YourController(ERXRouteController).performActionNamed
  • 6. checkAccess() • Default implementation in ERXRouteController does nothing • Override it in your controller for security check
  • 7. performHtmlActionNamed • Does <EntityName><ActionName>Page component exists? • No: fall back to controller • Yes: Check if component implements IEXRouteComponent • Yes: return the component • No: fall back to controller
  • 8. shouldFailOnMissingHtmlPage • Does the component was not found or don't implement IEXRouteComponent? • If shouldFailOnMissingHtmlPage() returns true, call performUnknownAction (will return a 404 NotFound) • Default is false, override it in your controller if needed.
  • 9. performRouteActionNamed • Try to find <actionName>Action method. • Not found? Try to find <actionName> method. • Still nothing? Check for annotations. • Still nothing? Call performUnknownAction • Got something? Call performActionWithArguments
  • 10. performUnknownAction • if (ERXRest.strictMode) • throw ERXNotAllowedException (HTTP code 405) • else • throw FileNotFoundException (HTTP code 404)
  • 11. performActionWithArguments • Will invoke the method with the arguments
  • 13. Objects in routes • /ra/<entityName>/{entity:EntityName} • routeObjectForKey(key) • create(filter) • update(object, filter)
  • 14. routeObjectForKey • {<keyName>:<keyType>} in route = keyType result = routeObjectForKey(<keyName>) • Object is obtained by ERXRestUtils.coerceValueToTypeNamed
  • 15. coerceValueToTypeNamed • Where value is transformed to a object or primitive • If it's an EO or POJO, will use ERXRestClassDescriptionFactory.classDescriptionForEntityName to find the class • Will call IERXRestDelegate.Factory.delegateForClassDescription().objectOfEntityWithI D()
  • 16. create(filter) • Will call ERXRestClassDescriptionFactory.classDescriptionForEntityName • Will call IERXRestDelegate.Factory.delegateForClassDescription().createObjectOfEnti tyWithID to create a basic EO/POJO • Will call updateObjectWithFilter()
  • 17. update(object, filter) • As with create(filter), will simply call updateObjectWithFilter
  • 18. updateObjectWithFilter • Major method • Will take content from request and update object (PUT request) • Also used to populate new object (POST request)
  • 20. response(object, filter) • Will built up the object graph with ERXRestRequestNode.requestNodeWithObjectAndFilter • Will call response(format, responseNode)
  • 21. requestNodeWithObjectAndFilter • If primitive/simple object, will set the value • If EO/POJO, will call _fillInWithObjectAndFilter
  • 22. _fillInWithObjectAndFilter • If object is an array, method take itself • If not array, will use object's delegate to call primaryKeyForObject, and call _addAttributesAndRelationshipsForObjectOfEntity
  • 23. response(format, responseNode) • Returns result of ERXRouteResults(context, restContext, format, responseNode) • ERXRouteResults.generateResponse() will actually generate the response in requested format
  • 24. response(ERXRestFetchSpecification, filter) • Useful to return list of objects ("index" action) • ERXRestFetchSpecification allow you to set ordering, range, filtering and batching from request • Will also call response(format, responseNode)
  • 25. response(int) • Use that one to send a response without any content in the body • Check ERXHttpStatusCodes
  • 26. There's a property for that
  • 27. "id" key • ERXRest.idKey : what to use instead of "id" Default: {"id":2 } ERRest.idKey=primaryKey {"primaryKey":2 }
  • 28. "nil" key • ERXRest.nilKey To rewrite the "nil" attribute Default: <someAttribute nil="true"/> ERXRest.nilKey=cestVide -> <someAttribute cestVide="true"/> • ERXRest.writeNilKey Skip the "nil" attribute Default: <someAttribute nil="true"/> ERXRest.writeNilKey=false -> <someAttribute nil="true"/>
  • 29. "type" key • ERXRest.typeKey Allow you to change the name of the "type" attribute Default: {"type":"NameOfEntity"} ERXRest.typeKey=entityName {"entityName":"NameOfEntity"} • ERXRest.writeTypeKey If false, won't write the "type" attribute in the response ERXRest.writeTypeKey=false -> {id: 2, "type":"NameOfEntity"}
  • 30. ERXRest.pluralEntityNames • Default is true • If set to false, can't use pluralized names Default: /ra/restEntities Set to false: /ra/restEntities
  • 31. ERXRest.suppressTypeAttributesForSimpl eTypes • Only for XML format • Default value is false • Default rendering: <RestEntity primaryKey="1"> <someAttribute type = "integer">2</someAttribute> </RestEntity> • When set to false: <RestEntity primaryKey="1"> <someAttribute type = "integer">2</someAttribute>
  • 32. ERXRest.strictMode • Default is: true • For missing route, will send 405 (Not Allowed) code, if set to false, will send 404 (Not Found) • POST requests: will send 201 (Created), if false will send 200 (OK)
  • 33. ERXRest.routeCase • ERXRest.routeCase=LowerCamelCase /ra/restEntities • ERXRest.routeCase=CamelCase /ra/RestEntities • ERXRest.routeCase=LowercaseUnderscore /ra/rest_entities
  • 34. ERXRest.parseUnknownExtensions • /ra/restEntities/3.fsdfsd • If set to true (the default): HTTP/1.1 200 Apple WebObjects Content-Type: text/html • If set to false: HTTP/1.0 400 Apple WebObjects
  • 36. ERXRest.defaultFormat • ERXRest.defaultFormat=json|xml|plist|html|... • Let you specify the default format for all controllers • Can override it per controller: protected ERXRestFormat defaultFormat() { return ERXRestFormat.json(); }
  • 37. Format detection • Format detection is in ERXRouteController.format() • Order of detection • From extension (.json). Set in ERXRouteRequestHandler.routeForMethodAndPath() • From the Content-Type header • Default format (defaultFormat() in controller)
  • 38. Adding new format • Your own private format? Use ERXRestFormat.registerFormatNamed() • Format useful for the commumity? Add them to ERXRestFormat
  • 40. Same Origin Policy • Problem: browsers won't load data if client and server not on same domain • Numerous ways: window.name transport, JSONP and Cross-origin resource sharing (CORS) • CORS and window.name transport support is part of ERRest
  • 41. CORS • Works with Gecko 1.9.1 (Firefox 3.5+), WebKit (Safari 4+, Google Chrome 3+), Opera 12 and IE 8+ • Send extra headers to server • Client specifiy origin, requested HTTP verb and allowed headers, server returns allowed origin, methods, headers and max-age
  • 42. CORS preflight Client request: OPTIONS /resources/post-here/ HTTP/1.1 Origin: http://foo.example Access-Control-Request-Method: POST Access-Control-Request-Headers: X-PINGOTHER Server response: HTTP/1.1 200 OK Access-Control-Allow-Origin: http://foo.example Access-Control-Allow-Methods: POST, GET, OPTIONS Access-Control-Allow-Headers: X-PINGOTHER Access-Control-Max-Age: 1728000 Client request: GET /resources/post-here/ HTTP/1.1 Origin: http://foo.example Server response: HTTP/1.1 200 OK Access-Control-Allow-Origin: http://foo.example
  • 43. CORS • ERXRest.accessControlAllowRequestHeaders • ERXRest.accessControlAllowRequestMethods • ERXRest.accessControlMaxAge (default: 1728000) • ERXRest.accessControlAllowOrigin ('*' to allow all)
  • 44. window.name Transport • Dojo use that trick • Client send ?windowname=true in URL • Enable it on server with: ERXRest.allowWindowNameCrossDomainTransport=true • Will wrap response in HTML code: <html><script type="text/javascript">window.name='{"id": 4,"type":"RestEntity","someAttribute":"commit transaction"}';</script></html>
  • 46. Status code and exceptions • ObjectNotAvailableException, FileNotFoundException, NoSuchElementException: returns a 404 (Not Found) • SecurityException: returns a 403 (Forbidden) • ERXNotAllowedException: returns a 405 (Method Not Allowed) • ERXValidationException, NSValidation.ValidationException: returns a 400 (Bad Request) • Anything else: returns a 500 (Internal Server Error) • Avoid sending 5xx codes if the client made a mistake!
  • 47. Adding support for new data types • Add a processor in _ERXJSONConfig • Add support code in ERXRestUtils • isPrimitive() • coerceValueToString() • coerceValueToTypeNamed • For dates: add formatter in ERXRestUtils
  • 48. MONTREAL JUNE 30, JULY 1ST AND 2ND 2012 Q&A