RESTfully Async with Grails 2.3 By Graeme Rocher

© 2013 SpringOne 2GX. All rights reserved. Do not distribute without permission.

Friday, September 13, 13

RESTfully Async with Grails 2.3 By Graeme Rocher

© 2013 SpringOne 2GX. All rights reserved. Do not distribute without permission.

Friday, September 13, 13

SPRING IO EXECUTION:

Grails

Friday, September 13, 13

Agenda § Detailed Look at REST § Fun with Grails Async APIs § Summary / Q & A

Friday, September 13, 13

Goals of REST Support in Grails 2.3

• • • •

Be Grails-y (i.e. dead simple) Be Flexible (start simple, get deep) Be pluggable (extend and conquer) Be current (support latest techniques)

5 Friday, September 13, 13

2.3

REST Features in 2.3

• RESTful URL Mappings • Domain Classes as REST resources • Controllers as REST resources • Renderers and Binders

6 Friday, September 13, 13

2.3

GRAILS

Demo Domain classes as REST resources

Friday, September 13, 13

REST: @Resource Transformation • Automatically exposes a domain class as a REST resource • Configurable formats • Configuration HTTP methods

8 Friday, September 13, 13

REST: @Resource Transformation • Automatically exposes a domain class as a REST resource • Configurable formats • Configuration HTTP methods

8 Friday, September 13, 13

import  grails.rest.* @Resource class  Person  {        String  name }

GRAILS

Demo RESTful URL Mappings

Friday, September 13, 13

REST: URL Mappings • RESTful Mappings – Single or Multiple resources – Versioning – Nested resources

• New url-mappings-report command to mappings

10 Friday, September 13, 13

REST: Multiple Resources

HTTP Method

URI

Action

GET

/books

index

POST

/books

save

GET

/books/${id}

show

PUT

/books/${id}

update

DELETE

/books/${id}

delete

11 Friday, September 13, 13

REST: Multiple Resources "/books"(resources:'book')   HTTP Method

URI

Action

GET

/books

index

POST

/books

save

GET

/books/${id}

show

PUT

/books/${id}

update

DELETE

/books/${id}

delete

11 Friday, September 13, 13

REST: Singular Resources

HTTP Method

URI

Action

GET

/book

show

POST

/book

save

PUT

/book

update

DELETE

/book

delete

12 Friday, September 13, 13

REST: Singular Resources "/book"(resource:'book')  

HTTP Method

URI

Action

GET

/book

show

POST

/book

save

PUT

/book

update

DELETE

/book

delete

12 Friday, September 13, 13

GRAILS

Demo Nested Resources

Friday, September 13, 13

REST: Nested URL Mappings • You can nest resources or other URL mappings within resources

14 Friday, September 13, 13

REST: Nested URL Mappings • You can nest resources or other URL mappings within resources "/books"(resources:'book')  {    "/authors"(resources:"author") } "/books"(resources:  "book")  {        "/publisher"(controller:"publisher") } 14 Friday, September 13, 13

REST: Nested Resources

HTTP Method

URI

Action

GET

/books/${bookId}/authors

index

POST

/books/${bookId}/authors

save

GET

/books/${bookId}/authors/${id}

show

PUT

/books/${bookId}/authors/${id}

update

DELETE

/books/${bookId}/authors/${id}

delete

15 Friday, September 13, 13

REST: Nested Resources "/books"(resources:'book')  {    "/authors"(resources:"author") } HTTP Method

URI

Action

GET

/books/${bookId}/authors

index

POST

/books/${bookId}/authors

save

GET

/books/${bookId}/authors/${id}

show

PUT

/books/${bookId}/authors/${id}

update

DELETE

/books/${bookId}/authors/${id}

delete

15 Friday, September 13, 13

GRAILS

Demo Versioned Resources

Friday, September 13, 13

REST: Versioned Resources • Version by URI • Version by “Accept-Version” header • Version by Media Type

17 Friday, September 13, 13

REST: Versioned Resources • Version by URI • Version by “Accept-Version” header • Version by Media Type

"/books"(version:'1.0',  resources:"book") "/books"(version:'2.0',  resources:"bookV2")

17 Friday, September 13, 13

GRAILS

Demo Controllers as REST resources

Friday, September 13, 13

REST: RestfulController Super Class • Implements methods for all the typical REST operations (save, delete etc.) • Subclasses can override / augment as necessary

19 Friday, September 13, 13

REST: RestfulController Super Class • Implements methods for all the typical REST operations (save, delete etc.) • Subclasses can override / augment as necessary import  grails.rest.* class  PersonController  extends  RestfulController{        PersonController()  {          super(Person)        } } 19 Friday, September 13, 13

REST: RestfulController for Nested Resources • Super class makes it easy to implement nested resources

20 Friday, September 13, 13

REST: RestfulController for Nested Resources • Super class makes it easy to implement nested resources class  PersonController  extends  RestfulController{ ... protected  queryForResource(Serializable  id)  { def  city  =  City.load(params.cityId)    Person.findByCityAndId(city,  id)           } } 20 Friday, September 13, 13

REST: Scaffolding 2.0 • Scaffolding support now a plugin – http://grails.org/plugin/scaffolding

• Generated controllers now RESTful • New generate-asynccontroller command for Async support

21 Friday, September 13, 13

GRAILS

Demo Renderers

Friday, September 13, 13

REST: Renderers • Rendering customizable in resources.groovy, just render a Spring bean • JSON, XML, HAL, Atom, Vnd.Error renders included • Renderer can use any library (Jackson, GSON etc.)

23 Friday, September 13, 13

REST: Renderers • Rendering customizable in resources.groovy, just render a Spring bean • JSON, XML, HAL, Atom, Vnd.Error renders included • Renderer can use any library (Jackson, GSON etc.) import  grails.rest.render.json.* beans  =  {   personRenderer(JsonRenderer,    Person)  {     excludes  =  ['class',  'age']   } } 23 Friday, September 13, 13

REST: What is a Render? • Class that implements the Renderer interface

24 Friday, September 13, 13

REST: What is a Render? • Class that implements the Renderer interface interface  Renderer  extends  MimeTypeProvider{        /**  @return  The  target  type    */        Class  getTargetType()        /**          *  Renders  the  object          */        void  render(T  object,  RenderContext  context) }

24 Friday, September 13, 13

REST: Container Renderers • Container renderers render containers (Lists, Maps, Errors) of a particular type • You want different output from a single resources vs viewing multiple

25 Friday, September 13, 13

REST: Container Renderers • Container renderers render containers (Lists, Maps, Errors) of a particular type • You want different output from a single resources vs viewing multiple interface  ContainerRenderer   extends  Renderer{        /*  The  generic  type  of  the  container*/        Class  getComponentType() }

25 Friday, September 13, 13

GRAILS

Demo Hypermedia & Mime / Media Types

Friday, September 13, 13

REST: Hyper Media and Mime Types • Declare Mime Types in Config.groovy • Don’t declare new types first!

27 Friday, September 13, 13

REST: Hyper Media and Mime Types • Declare Mime Types in Config.groovy • Don’t declare new types first! grails.mime.types  =  [        all:                      '*/*',        person:  "application/vnd.foo.org.person+json",        people:    "application/vnd.foo.org.people+json",        

27 Friday, September 13, 13

REST: Hyper Media and Mime Types • Define Renderers that use those types in resources.groovy

28 Friday, September 13, 13

REST: Hyper Media and Mime Types • Define Renderers that use those types in resources.groovy def  personMimeType  =        new  MimeType("application/vnd.foo.org.person+json") beans  =  {   personRenderer(JsonRenderer,                    Person,                    personMimeType) }

28 Friday, September 13, 13

GRAILS

Demo Versioning with Hyper Media

Friday, September 13, 13

REST: Hyper Media Versioning • You can version custom media types and use the media type to render different outputs

30 Friday, September 13, 13

REST: Hyper Media Versioning • You can version custom media types and use the media type to render different outputs def  personMimeType  =        new  MimeType("application/vnd.foo.org.person+json",      [v:  "1.0"]  ) beans  =  {   personRenderer(JsonRenderer,                    Person,                    personMimeType) }

30 Friday, September 13, 13

GRAILS

Demo HAL Support

Friday, September 13, 13

REST: Hyper Media with HAL • HAL is a standardized format used in conjunction with HATEOS principals

32 Friday, September 13, 13

REST: Hyper Media with HAL • HAL is a standardized format used in conjunction with HATEOS principals def  personMimeType  =        new  MimeType("application/vnd.foo.org.person+json",      [v:  "1.0"]  ) beans  =  {   personRenderer(HalJsonRenderer,                    Person,                    personMimeType) }

32 Friday, September 13, 13

GRAILS

Demo Binders / BindingSource

Friday, September 13, 13

REST: Binding / BindingSource • If you define a custom render you may need to define a custom binding source to make binding work

34 Friday, September 13, 13

REST: Binding / BindingSource • If you define a custom render you may need to define a custom binding source to make binding work protected  DataBindingSource                          createBindingSource(Reader  reader)  {   def  json  =  JSON.parse(reader)   def  map  =  [     firstName:json.first_name,     lastName:json.last_name   ]   new  SimpleMapDataBindingSource(map) }

34 Friday, September 13, 13

Goals of Async Support in Grails 2.3

• • • •

Be Grails-y (i.e. dead simple) Be Flexible (start simple, get deep) Be pluggable (extend and conquer) Be current (support latest techniques)

35 Friday, September 13, 13

2.3

Async Features in 2.3

• Async Primitives (Promises, Lists, Maps etc.) • Async Data (GORM) • Async Everywhere (Tasks) • Async Request Handling

36 Friday, September 13, 13

2.3

GRAILS

Demo Async Primitives

Friday, September 13, 13

Async: Promise Primitives • Foundational API for Async programming • Includes notion of Promise • Ability to combine / chain promises

38 Friday, September 13, 13

Async: Promise Primitives • Foundational API for Async programming • Includes notion of Promise • Ability to combine / chain promises

38 Friday, September 13, 13

import  static   grails.async.Promises.* def  p1  =  task  {  2  *  2  } def  p2  =  task  {  4  *  4  } def  p3  =  task  {  8  *  8  } assert  [  4,  16,  64  ]  ==   waitAll(p1,  p2,  p3)

Async: Promise Chaining • Chain promises to formulate a value asynchronously

39 Friday, September 13, 13

Async: Promise Chaining • Chain promises to formulate a value asynchronously import  static  grails.async.Promises.* import  static  grails.async.* Promise  p  =        task  {  2  *  2  }  <<  {  it  *  4  }  <<  {  it  *  8  } p.onComplete  {  Integer  value  -­‐>        println  "Total:  $value" }   39 Friday, September 13, 13

Async: Promise Chaining • Create list and map data structures from promises!

40 Friday, September 13, 13

Async: Promise Chaining • Create list and map data structures from promises! import  static  grails.async.Promises.* import  static  grails.async.* PromiseList  p  =        task  {  2  *  2  }  <<  {  it  *  4  }  <<  {  it  *  8  } p.onComplete  {  Integer  value  -­‐>        println  "Total:  $value" }   40 Friday, September 13, 13

Async: Promise Factory • Override the creation of promise instances – Plugin in Reactor – Change to synchronous promises for testing

41 Friday, September 13, 13

Async: Promise Factory • Override the creation of promise instances – Plugin in Reactor – Change to synchronous promises for testing import  org.grails.async.factory.* import  grails.async.* Promises.promiseFactory  =      new  SynchronousPromiseFactory()

41 Friday, September 13, 13

Async: @DelegateAsync Transform • Transform any synchronous API into an asynchronous one • Takes each method and returns a promise

42 Friday, September 13, 13

Async: @DelegateAsync Transform • Transform any synchronous API into an asynchronous import  grails.async.* one • Takes each method and class  AsyncBookService  { returns a promise      @DelegateAsync        BookService  bookService }

42 Friday, September 13, 13

GRAILS

Demo Async Data (GORM)

Friday, September 13, 13

Async: GORM • Makes all GORM methods async • Each method returns a Promise • Deals with binding session to background thread • Works across all datastores (MongoDB, GORM for REST etc.) 44 Friday, September 13, 13

Async: GORM • Makes all GORM methods async • Each method returns a Promise • Deals with binding session to background thread • Works across all datastores (MongoDB, GORM for REST etc.) 44 Friday, September 13, 13

def  p1  =  Person.async.get(1) def  p2  =  Person.async.get(2) def  p3  =  Person.async.get(3) def  results  =                waitAll(p1,  p2,  p3)

Async: GORM Tasks • Batch up a bunch of Grails queries to be executed asynchronously

45 Friday, September 13, 13

Async: GORM Tasks • Batch up a bunch of Grails queries to be executed asynchronously def  promise  =  Person.async.task  {        withTransaction  {              def  person  =  findByFirstName("Homer")              person.firstName  =  "Bart"              person.save(flush:true)                } } Person  updatedPerson  =  promise.get() 45 Friday, September 13, 13

GRAILS

Demo Async Request Handling

Friday, September 13, 13

Async: Request Processing • Handle requests asynchronously • Uses Servlet 3.0 async under the covers • Create asynchronous models

47 Friday, September 13, 13

Async: Request Processing • Handle requests asynchronously • Uses Servlet 3.0 async under the covers • Create asynchronous models

47 Friday, September 13, 13

import  static   grails.async.Promises.* class  PersonController  {    def  index()  {      tasks  books:  Book.async.list(),                total:  Book.async.count(),                otherValue:  {                      //  do  hard  work                }      } }

REST: Generating Async Controllers • New scaffolding can generate an example Async controller – http://grails.org/plugin/scaffolding

• Use generate-asynccontroller command

48 Friday, September 13, 13

Q&A REST & Async

3.0 Friday, September 13, 13

Learn More. Stay Connected.

Web: grails.org Twitter: twitter.com/grailsframework LinkedIn: http://linkedin.com/groups/Grails-User-Group-39757 Google +: https://plus.google.com/communities/ 109558563916416343008

Friday, September 13, 13

RESTfully Async with Grails 2.3 - GitHub

Sep 13, 2013 - Goals of REST Support in Grails 2.3 ... Be current (support latest techniques). 5 .... Define Renderers that use those types in resources.groovy.

5MB Sizes 8 Downloads 213 Views

Recommend Documents

Grails In The Enterprise - GitHub
Developer Program portals for all kinds of companies, ... Employer had very antiquated Struts/OJB application. ➢ ..... Blog: http://rvanderwerf.blogspot.com.

Deploying, Scaling, and Running Grails on AWS and VPC - GitHub
Page 5 ... Very different that EC2 'Classic' which has no private network layer. Costs nothing extra .... to Manage S3 storage and SES Service (vs Java wrapper) ...

SOT-23 Plastic-Encapsulate Transistors - GitHub
MARKING: J3. MAXIMUM RATINGS (Ta=25℃ unless otherwise noted). Symbol. Parameter. Value. Unit. VCBO. Collector-Base Voltage. 40. V. VCEO.

Google Async Tracking Case Study
an opportunity to update the site's existing traditional Google Analytics snippet to the ... the cutting edge with Google's best practices, this was done to improve site speed ... region helps to determine marketing strategy and financing for various

Grails in Action.pdf
Sign in. Loading… Whoops! There was a problem loading more pages. Whoops! There was a problem previewing this document. Retrying... Download. Connect ...

CP2K with LIBXSMM - GitHub
make ARCH=Linux-x86-64-intel VERSION=psmp AVX=2. To target for instance “Knights ... //manual.cp2k.org/trunk/CP2K_INPUT/GLOBAL/DBCSR.html).

Java with Generators - GitHub
processes the control flow graph and transforms it into a state machine. This is required because we can then create states function SCOPEMANGLE(node).

grails in action pdf download
Retrying... Download. Connect more apps... Try one of the apps below to open or edit this item. grails in action pdf download. grails in action pdf download. Open.

1 of 3 4/28/15, 19:23 - GitHub
Apr 28, 2015 - Populating the interactive namespace from numpy and matplotlib. Out[5]: (3168, 4752). Out[6]: (array([7972546, 76184, 1027385, 1151136, ...

O'Reilly - You Don't Know JS. Async & Performance.pdf
Page 2 of 8. Phần hướng dẫn. Vòng 1. Câu 2... 22 2 2. 2 2. 22 22. 2 2. 2. 11 2 1111 0. 111 1111. 0 1 10. 11 11. 1 0 1( ) 2. x y xy x xy y xy. xy y xy x xy y y xy x x. x xy y xy. x y xy xy vi x y S...... Câu 2. a) PhÆ°Æ¡ng trình hoành đá»

OpenBMS connection with CAN - GitHub
Arduino with BMS- and CAN-bus shield as BMS a master. - LTC6802-2 or LTC6803-2 based boards as cell-level boards. - CAN controlled Eltek Valere as a ...

Better performance with WebWorkers - GitHub
Chrome52 on this Laptop. » ~14kbyte. String => 133ms ... 3-4 Seks processing time on samsung galaxy S5 with crosswalk to finish the transition with ... Page 17 ...

with ZeroMQ and gevent - GitHub
Normally, the networking of distributed systems is ... Service Oriented .... while True: msg = socket.recv() print "Received", msg socket.send(msg). 1. 2. 3. 4. 5. 6. 7.

Getting Started with CodeXL - GitHub
10. Source Code View . ..... APU, a recent version of Radeon Software, and the OpenCL APP SDK. This document describes ...... lel_Processing_OpenCL_Programming_Guide-rev-2.7.pdf. For GPU ... trademarks of their respective companies.

Getting Started with Go - GitHub
Jul 23, 2015 - The majority of my experience is in PHP. I ventured into Ruby, ... Compiled, Statically Typed, Concurrent, Imperative language. Originally ...

Getting Acquainted with R - GitHub
In this case help.search(log) returns all the functions with the string 'log' in them. ... R environment your 'working directory' (i.e. the directory on your computer's file ... Later in the course we'll discuss some ways of implementing sanity check

Training ConvNets with Torch - GitHub
Jan 17, 2014 - ... features + SVM. – Neural Nets (and discuss discovering graph structure automařcally). – ConvNets. • Notebook Setup ... Page 9 ...

Examples with importance weights - GitHub
Page 3 ... Learning with importance weights y. wT t x wT t+1x s(h)||x||2 ... ∣p=(wt−s(h)x)Tx s (h) = η. ∂l(p,y). ∂p. ∣. ∣. ∣. ∣p=(wt−s(h)x)Tx. Finally s(0) = 0 ...

Digital Design with Chisel - GitHub
Dec 27, 2017 - This lecture notes (to become a book) are an introduction into hardware design with the focus on using the hardware construction language Chisel. The approach of this book is to present small to medium sized typical hardware components

Deep Learning with H2O.pdf - GitHub
best-in-class algorithms such as Random Forest, Gradient Boosting and Deep Learning at scale. .... elegant web interface or fully scriptable R API from H2O CRAN package. · grid search for .... takes to cut the learning rate in half (e.g., 10−6 mea

Async Buffered Disk IO using preadv2 with Samba PDF
There was a problem loading more pages. Async Buffered Disk IO using preadv2 with Samba PDF. Async Buffered Disk IO using preadv2 with Samba PDF.

Async Buffered Disk IO using preadv2 with Samba PDF
Page 3 of 8. IO thread pool pattern. Page 3 of 8. Async Buffered Disk IO using preadv2 with Samba PDF. Async Buffered Disk IO using preadv2 with Samba PDF.