Multi-Client Development with Spring

1,126 views
984 views

Published on

Speakers: Roy Clarkson and Josh Long
No application is an island and this is more obvious today than ever as applications extend their reach into people's pockets, desktops, tablets, TVs, Blu-ray players and cars. What's a modern developer to do to support these many platforms? In this talk, join Josh Long to learn how Spring can extend your reach through (sometimes Spring Security OAuth-secured) RESTful services exposed through Spring MVC, HTML5 and client-specific rendering thanks to Spring Mobile, and powerful, native support for Android with Spring Android.

Published in: Technology
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,126
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
20
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

Multi-Client Development with Spring

  1. 1. Building Smart Clients with Spring by Josh Long and Roy Clarkson © 2013 SpringOne 2GX. All rights reserved. Do not distribute without permission.
  2. 2. WHAT IS REST? REST is an architectural constraint based on HTTP 1.1, and created as part of Roy Fielding’s doctoral dissertation in 2000. It embraces HTTP. It’s a style, not a standard http://en.wikipedia.org/wiki/Representational_state_transfer
  3. 3. WHAT IS REST? REST has no hard and fast rules. REST is an architectural style, not a standard. REST uses Headers to describe requests & responses REST embraces HTTP verbs
  4. 4. HTTP VERBS GET requests retrieve information. GET can have side-effects (but it’s unexpected) GET can be conditional, or partial: If-Modified-Since, Range GET /users/21
  5. 5. HTTP VERBS DELETE requests that a resource be removed, though the deletion doesn’t have to be immediate. DELETE /users/21
  6. 6. HTTP VERBS POST requests that the resource do something with the enclosed entity POST can be used to create or update. POST /users { “firstName”: “Juergen” }
  7. 7. HTTP VERBS PUT requests that the entity be stored at a URI PUT can be used to create or update. PUT /users/21 { “firstName”: “Juergen” }
  8. 8. THE MATURITY MODEL The Richardson Maturity Model is a way to grade your API according to the REST constraints with 4 levels of increasing compliance http://martinfowler.com/articles/richardsonMaturityModel.html
  9. 9. THE MATURITY MODEL The Richardson Maturity Model Level 0: swamp of POX Uses HTTP mainly as a tunnel through one URI e.g., SOAP, XML-RPC Usually features on HTTP verb (POST) http://martinfowler.com/articles/richardsonMaturityModel.html
  10. 10. THE MATURITY MODEL The Richardson Maturity Model Level 1: resources Multiple URIs to distinguish related nouns e.g., /articles/1, /articles/2, vs. just /articles http://martinfowler.com/articles/richardsonMaturityModel.html
  11. 11. THE MATURITY MODEL The Richardson Maturity Model Level 2: HTTP verbs leverage transport-native properties to enhance service e.g., HTTP GET and PUT and DELETE and POST Uses idiomatic HTTP controls like status codes, headers http://martinfowler.com/articles/richardsonMaturityModel.html
  12. 12. HTTP VERBS GET /users/21 DELETE /users/21 POST /users PUT /users/21 retrieves a resource from a URI removes the resource creates a new record; returns a Location updates a resource <filter> <filter-name>hiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>hiddenHttpMethodFilter</filter-name> <url-pattern>/</url-pattern> <servlet-name>appServlet</servlet-name> </filter-mapping>
  13. 13. STATUS CODES status codes convey the result of the server’s attempt to satisfy the request. Categories: 1xx: informational 2xx: success 3xx: redirection 4xx: client error 5xx: server error
  14. 14. REST 101 200 OK - Everything worked 201 Created - Returns a Location header for new resource 202 Accepted - server has accepted the request, but it is not yet complete. Status URI optionally conveyed in Location header
  15. 15. REST DESIGN WITH SPRING 101 406: NOT ACCEPTABLE
  16. 16. REST 101 400 Bad Request - Malformed Syntax. Retry with change. 401 Unauthorized - authentication is required 403 Forbidden - server has understood, but refuses request 404 Not Found - server can’t find a resource for URI 406 Not Found - incompatible Accept headers specified 409 Conflict - resource conflicts with client request
  17. 17. REST 101 Clients and services must agree on a representation media type through content negotiation. Client specifies what it wants through Accept header Server specifies what it produces through Content-Type header
  18. 18. REST 101 Spring MVC supports multiple types of content negotiation through its ContentNegotiationStrategy: e.g., Accept header, URL extension, request parameters, or a fixed type
  19. 19. Demonstration Basic RESTful service, REST shells
  20. 20. HATEOAS The Richardson Maturity Model Level 3: Hypermedia Controls (aka, HATEOAS) No a priori knowledge of service required Navigation options are provided by service and hypermedia controls Promotes longevity through a uniform interface http://martinfowler.com/articles/richardsonMaturityModel.html
  21. 21. HATEOAS Links provide possible navigations from a given resource Links are dynamic, based on resource state. <link href=“http://...:8080/users/232/customers” rel= “customers”/>
  22. 22. Demonstration Spring HATEOAS, Rest Shell
  23. 23. SPRING DATA REST Spring Data REST simplifies the generic data-centric @Controllers Builds on top of Spring Data Repository support: @RestResource (path = "users", rel = "users") public interface UserRepository extends PagingAndSortingRepository<User, Long> { User findByUsername(@Param ("username") String username);
  24. 24. SPRING DATA REST Spring Data REST simplifies the generic data-centric @Controllers Builds on top of Spring Data Repository support: @RestResource (path = "users", rel = "users") public interface UserRepository extends PagingAndSortingRepository<User, Long> { User findByUsername(@Param ("username") String username); select u from User where u.username = ?
  25. 25. SPRING DATA REST Spring Data REST simplifies the generic data-centric @Controllers Builds on top of Spring Data Repository support: @RestResource (path = "users", rel = "users") public interface UserRepository extends PagingAndSortingRepository<User, Long> { } List<User> findUsersByFirstNameOrLastNameOrUsername( @Param ("firstName") String firstName, @Param ("lastName") String lastName, @Param ("username") String username);
  26. 26. SPRING DATA REST Spring Data REST simplifies the generic data-centric @Controllers Builds on top of Spring Data Repository support: @RestResource (path = "users", rel = "users") public interface UserRepository extends PagingAndSortingRepository<User, Long> { } List<User> findUsersByFirstNameOrLastNameOrUsername( @Param ("firstName") String firstName, @Param ("lastName") String lastName, @Param ("username") String username); select u from User u where u.username = ? or u.firstName = ? or u.lastName = ?
  27. 27. Demonstration Spring Data, Spring Data REST
  28. 28. SECURITY Security can be as simple, or complex, as you want... If you can trust the client to keep a secret like a password: ...HTTP Basic if you have TLS ... HTTP Digest if you want extra security
  29. 29. OAUTH Security can be as simple, or complex, as you want... Can’t trust the client to keep a secret? (HTML page?) Application has a user context and you don’t want clients to have a user’s password? ...use OAuth
  30. 30. OAUTH
  31. 31. OAUTH
  32. 32. OAUTH
  33. 33. Demonstration Spring Security OAuth
  34. 34. SPRING SOCIAL Spring Social provides an authentication and authorization client for OAuth (1.0, 1.0a, 2.0) Provides type-safe API bindings for various services
  35. 35. BINDINGS...
  36. 36. ...LOTS OF BINDINGS
  37. 37. Demonstration Spring Social
  38. 38. SPRING ANDROID Spring Social provides an authentication and authorization client for OAuth (1.0, 1.0a, 2.0) Provides type-safe API bindings for various services
  39. 39. SPRING ANDROID Spring Android brings Spring core’s RestTemplate. Spring Social and Spring HATEOAS work as well.
  40. 40. SPRING ANDROID More than than 500,000 500,000 activations activations every day day
  41. 41. Demonstration Spring Android-powered UI client
  42. 42. USING REST AND OAUTH FROM IOS
  43. 43. REST DESIGN WITH SPRING iOS provides an HTTP client (NSURLConnection), a JSON processor (NSJSONSerialization), and a rich set of data structures (NSData, NSDictionary, and NSArray)
  44. 44. BASIC HTTP REQUEST NSURL *url = [NSURL URLWithString:@"http://localhost"]; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
  45. 45. BASIC HTTP REQUEST... IMPROVED NSURL *url = [NSURL URLWithString:@"http://localhost"]; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; NSURLResponse *response; NSError *error; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSInteger status = [(NSHTTPURLResponse *)response statusCode]; if (status == 200 && data.length > 0 && error == nil) { // do something with data }
  46. 46. ASYNCHRONOUS HTTP REQUESTS NSURL *url = [NSURL URLWithString:@"http://localhost"]; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { NSInteger status = [(NSHTTPURLResponse *)response statusCode]; if (status == 200 && data.length > 0 && error == nil) { // do something with data } }
  47. 47. HTTP HEADERS NSURL *url = [NSURL URLWithString:@"http://localhost"]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; [request setHTTPMethod:@"PUT"]; [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setValue:contentLength forHTTPHeaderField:@"Content-Length"]; [request setHTTPBody:postData];
  48. 48. JSON SERIALIZATION // deserialize JSON data NSError *error; NSDictionary *d = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; // serialize JSON data NSError *error; NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
  49. 49. • HTTP Client – NSURLConnection • JSON Processor (iOS 5) – NSJSONSerialization • Data – NSData – NSDictionary – NSArray 49
  50. 50. • Loading Data Synchronously + sendSynchronousRequest:returningResponse:error: • Loading Data Asynchronously + sendAsynchronousRequest:queue:completionHandler: 50
  51. 51. NSURL *url = [NSURL URLWithString:@"http://localhost"]; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 51
  52. 52. NSURL *url = [NSURL URLWithString:@"http://localhost"]; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; NSURLResponse *response; NSError *error; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSInteger status = [(NSHTTPURLResponse *)response statusCode]; if (status == 200 && data.length > 0 && error == nil) { // do something with data } 52
  53. 53. NSURL *url = [NSURL URLWithString:@"http://localhost"]; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { NSInteger status = [(NSHTTPURLResponse *)response statusCode]; if (status == 200 && data.length > 0 && error == nil) { // do something with data } } 53
  54. 54. NSURL *url = [NSURL URLWithString:@"http://localhost"]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; [request setHTTPMethod:@"PUT"]; [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setValue:contentLength forHTTPHeaderField:@"Content-Length"]; [request setHTTPBody:postData]; 54
  55. 55. // deserialize JSON data NSError *error; NSDictionary *d = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; // serialize JSON data NSError *error; NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error]; 55
  56. 56. iOS Demo
  57. 57. Q&A
  58. 58. • Spring MVC Reference http://static.springsource.org/spring-framework/docs/current/spring-frameworkreference/html/mvc.html • URL Loading System Programming Guide http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ URLLoadingSystem/URLLoadingSystem.html • Ben Hale’s presentation at SpringOne 2GX http://www.youtube.com/watch?v=wylViAqNiRA 58
  59. 59. • 59 Spring Roo Beginning Guide http://static.springsource.org/spring-roo/reference/html/ beginning.html#beginning-step-1
  60. 60. GREAT RESOURCES Roy Fielding’s Dissertation introduces REST http://www.ics.uci.edu/~fielding/pubs/dissertation/evaluation.htm#sec_6_1%7C The Spring REST Shell http://github.com/jbrisbin/rest-shell Spring Security, Security OAuth, Spring Data REST, HATEOAS, Social http://github.com/SpringSource Spring MVC Test Framework http://static.springsource.org/spring-framework/docs/current/spring-framework-reference/ html/testing.html#spring-mvc-test-framework
  61. 61. GREAT RESOURCES Oliver Gierke’s talk on Hypermedia from Øredev @ http://vimeo.com/53214577 Lez Hazelwood’s talk on designing a beautiful JSON+REST API Ben Hale’s talk on REST API design with Spring from SpringOne2GX 2012 @ http://www.youtube.com/watch?v=wylViAqNiRA My links: github.com/joshlong/the-spring-rest-stack slideshare.net/joshlong/rest-apis-with-spring @starbuxman
  62. 62. REST DESIGN WITH SPRING Any ? Questions github.com/joshlong/the-spring-rest-stack @starbuxman | jlong@gopivotal.com | http://slideshare.net/joshlong @royclarkson | rclarkson@gopivotal.com |http://www.slideshare.net/royclarkson

×