SlideShare une entreprise Scribd logo
1  sur  67
REST with JAX-RS,
           Security, Java EE 6




Carol McDonald
Agenda
•   REST Primer
•   RESTful Design and API Elements
•   Building a Simple Service
•   Security
•   Q&A
REpresentational State Transfer

Get                                             Response XML data =
                               REST Web
http://www.depot.com/parts
                              Service            REpresentational State

           Client                     Transfer        Client
          State1                                     State2

     The URL identifies the resource
     Click on the url (resource) in page (hypermedia)
         html page is transferred to the browser
           REpresentational State transfer occurs
REST Tenets

• Resources (nouns)
  >   Identified by a URI, For example:
         http://www.parts-depot.com/parts

• Methods (verbs) to manipulate the nouns
  >   Small fixed set:
        GET, PUT, POST, DELETE
                Read, Update, Create, Delete
• Representation of the Resource
  > data and state transferred between client and server
  > XML, JSON...

• Use verbs to exchange application state and
 representation
method                           resource
Request: GET http://localhost:8080/RestfulCustomer/webresources/model.customer/1

Status: 200 (OK)

Time-Stamp: Fri, 14 Dec 2012 02:19:34 GMT

Received:
{"name":"Jumbo Eagle Corp","state":"FL","customerId":1,
"addressline1":"111 E. Las Olivas Blvd","addressline2":"Suite 51",
"city":"Fort Lauderdale","phone":"305-555-0188","fax":"305-555-0189",
"email":"jumboeagle@example.com","creditLimit":100000
}




                                              representation
Rest Uniform Interface:
Every thing is a Resource




    Every resource has an id, URI is the id
   http://company.com/customers/123456
Every Resource has an Id

    URI is the id, Every resource has a URI

          http://company.com/customers/123456

Resource Collection name
         Primary key
•    URIs identify :
     >   items, collections of items, virtual and physical objects, or computation results.


http://company.com/customers/123456/orders/12
http://example.com/orders/2007/11
http://example.com/products?color=green
Rest Standard Interface:
Use Standard HTTP Methods
•   Example
        GET /store/customers/123456
Use Standard Methods:
• /orders
   – GET - list all orders                      Order Customer
   – POST - submit a new order                  Mgmt Example
 /orders/{order-id}
   > GET - get an order representation
   > PUT - update an order
   > DELETE - cancel an order
 /orders/average-sale
   – GET - calculate average sale
• /customers                          http://www.infoq.com/articles/rest-
   – GET - list all customers         introduction
   – POST - create a new customer
 /customers/{cust-id}
   > GET - get a customer representation
   > DELETE- remove a customer
 /customers/{cust-id}/orders
   – GET - get the orders of a customer
Use Standard HTTP Methods


• HTTP Get, Head
    > Should not modify anything
    > Cache-able
       With Correct use of Last-Modified and
         ETag
•   Idempotency:
    > PUT, DELETE, GET, HEAD can be repeated
      and the results are the same
Link things together
• Hypermedia
• As
• The
• Engine
• Of
• Application
• State
HATEOAS




© Availity, LLC | All rights reserved.
Link Things Together

Representations contain links to other resources:
  <prop self="http://example.com/orders/101230">
    <customer ref="http://example.com/customers/bar">
    <product ref="http://example.com/products/21034"/>
    <amount value="1"/>
  </order>

• Service provides links in response to the Client
   > Enables client to move the application from
      one state to the next by following a link
Example




http://www.infoq.com/articles/webber-rest-workflow
  © Availity, LLC | All rights reserved.
Example




© Availity, LLC | All rights reserved.
Multiple Representations

•   Offer data in a variety of formats, for different needs
    > XML
    > JSON
    > (X)HTML



•   Support content negotiation
    >   Accept header
        GET /foo
        Accept: application/json
    >   URI-based
        GET /foo.json

    > Response header
    > Content-Type application/xml
content negotiation
Request: http://localhost:8080/RestfulCustomer/webresources/application.wadl


Status: 200 (OK)

Time-Stamp: Fri, 14 Dec 2012 03:11:50 GMT

Received:

<?xml version="1.0" encoding="UTF-8"?>
   <resources base="http://localhost:8080/RestfulCustomer/webresources/">
      <resource path="model.customer">
        <method id="findAll" name="GET">
          <response>
             <representation mediaType="application/xml"/>
             <representation mediaType="application/json"/>
          </response>
        </method>
Stateless Communications

 • HTTP protocol is stateless
 • Everything required to process a request   contained in the
   request
     > No client session on the server
     > Eliminates many failure conditions

 • application state kept on Client
 • Service responsible for resource state
Rest Common Patterns: Container, Item
Server in control of URI
• Container – a collection of items
• List catalog items: GET /catalog/items
• Add item to container: POST /catalog/items
    > with item in request
    > URI of item returned in HTTP response header
    > e.g. http://host/catalog/items/1


•   Update item: PUT /catalog/items/1
    >   with updated item in request


    Good example: Atom Publishing Protocol
Common Patterns: Map, Key, Value
Client in control of URI

 • List key-value pairs: GET /map
 • Put new value to map: PUT /map/{key}
     > with entry in request
     > e.g. PUT /map/dir/contents.xml


 • Read value: GET /map/{key}
 • Update value: PUT /map/{key}
     >   with updated value in request
 •   Remove value: DELETE /map/{key}

 •   Good example: Amazon S3
Rest Key Benefits
•   Server side
    > Uniform Interface
    > Cacheable
    > Scalable
    > Easy failover

•   Client side
    > Easy to experiment in browser
    > Broad programming language support
    > Choice of data formats
Agenda
•   REST Primer
•   RESTful Design and API Elements with JAX-RS
•   Building a Simple Service
•   Status
•   Q&A
JAX-RS: Clear mapping to REST concepts


•   High level, Declarative
    >   Uses @ annotation in POJOs
•   Jersey – reference implementation of JSR 311
          Download it from http://jersey.dev.java.net
          Comes with Glassfish, Java EE 6
          Tools support in NetBeans
Resources

•   Resource class
    >   POJO, No required interfaces
•   ID provided by @Path annotation
    > Relative to deployment context
    > Annotate class or “sub-resource locator” method



                                          http://host/ctx/orders/12
@Path("orders/{id}")
public class OrderResource {
    @Path("customer")
                                   http://host/ctx/orders/12/customer
    CustomerResource getCustomer(...) {...}
}
Request Mapping
•   Annotate resource class methods with standard method
     >   @GET, @PUT, @POST, @DELETE, @HEAD
• annotations on parameters specify mapping from request data
• Return value mapped to http response



@Path("orders/{order_id}")
public class OrderResource {
  @GET
  Order getOrder(@PathParam("order_id") String id) {
    ...
  }
}
Multiple Representations
Static and dynamic content negotiation

• Annotate methods or classes
  > @Produces matches Accepts header
  > @Consumes matches Content-Type
     header
@GET
@Consumes("application/json")
@Produces({"application/xml","application/json"})
String getOrder(@PathParam("order_id") String id) {
  ...
}
Multiple Representations: JAX-RS
consuming

@Path("/items/")
@ConsumeMime(“application/xml”)
public class ItemsResource {
                                   http://host/catalog/items/?start=0
    @GET
    ItemsConverter get(@QueryParam("start")
        int start) {
       ...
    }                              http://host/catalog/items/123
    @Path("{id}/")
    ItemResource getItemResource(@PathParam("id")Long id){
    ...
    }
}
Multiple Representations


@Post
@ConsumeMime(“application/x-www-form-urlencoded”)
@ProduceMime(“application/xml”)

public JAXBClass updateEmployee(
           MultivalueMap<String, String> form) {

      ...




 converted to XML                        Converted to a map for
                                         accessing form's field
Multiple Representations: producing a
response
@Path(“/items”)
class Items {
                                    Use Response class
                                    to build “created”response
    @POST
    @ProduceMime(“application/xml”)
    Response create(Ent e) {
       // persist the new entry, create       URI
      return Response.created(
               uriInfo.getAbsolutePath().
          resolve(uri+"/")).build();
    }
}
Uniform interface: HTTP request and response

C:   POST /items HTTP/1.1
C:   Host: host.com
C:   Content-Type: application/xml
C:   Content-Length: 35
C:
C:   <item><name>dog</name></item>
S: HTTP/1.1 201 Created
S: Location: http://host.com/employees/1234
S: Content-Length: 0
Link Things Together
• UriInfo provides information about the request URI and the
  route to the resource
• UriBuilder provides facilities to easily build URIs for
  resources




@Context UriInfo info;
OrderResource r = ...
UriBuilder b = info.getBaseUriBuilder();
URI u = b.path(OrderResource.class).build(r.id);
Agenda
•   REST Primer
•   RESTful Design and API Elements
•   Building a Simple Service
•   Deployment Options
•   Status
Example RESTful Catalog
URIs and Methods:
                                         Item Catalog Example
   /items
    – GET - list all items
    – POST – add item to catalog
 /items/{id}
    > GET - get an item representation
    > PUT - update an item
    > DELETE – remove an item

                                     http://www.infoq.com/articles/rest-
                                     introduction
Methods
@Path(“/items”)
class ItemsResource {
  @GET
  public List<Item> findAll() { ... }
  @POST Response create(Item) { ... }
  @PUT
  @Path("{id}")
  public void editp(Item entity) {}
  @GET
  @Path("{id}")
  public Item find(@PathParam("id")
    Integer id) { ... }
}
          Java method name is not significant
          The @HTTP method is the method
RESTful Catalog

     Javascript client, JAX-RS, JSON, JPA
      Registration Application
                     JAX-RS class     Entity Class
                                       JSON class
                                      Item           DB




                     ItemsResource


 javascript client
Item Entity JAXB annotated
@Entity
@Table(name = "ITEM")
@XmlRootElement
public class Item implements Serializable {
    @Id
    private Integer id;
    ...
}
XML
  <item uri="http://localhost/Web/resources/items/1/">
      <description> black cat is nice</description>
      <id>1</id>
      <imagethumburl>/images/anth.jpg</imagethumburl>
      <name>not Friendly Cat</name>
      <price>307.10</price>
      <productid>feline01</productid>
  </item>
JSON


   {
    "@uri":"http://host/catalog/resources/items/1/",
    "name":"Friendly Cat",
   "description":"This black and white colored cat is super friendly.",
    "id":"1",

 "imageurl":"http://localhost:8080/CatalogService/images/anthony.jpg"
    }
Resource Classes

   > Items Resource retrieves updates a collection of Item
     entities
   > /items – URI for a list of Items
   > /item/1 – URI for item 1


                   JAX-RS class         Entity Class


                                        Item           DB




                     ItemsResource


 Dojo client
Get Items
                     responds to the URI http://host/catalog/items/

@Path("/items/")                       responds to HTTP GET
public class ItemsResource {
                                            responds with JSON
   @GET
   @Produces("application/json")         JAXB class
   public List<Item> get(){
      CriteriaQuery cq = getEntityManager().
          getCriteriaBuilder().createQuery();
      cq.select(cq.from(Item));
      return getEntityManager().createQuery
         (cq).getResultList();
   }
                                                  Performs JPA
                                                  Query, returns list
                                                  of entities
JQuery Client
var rootURL = "http://localhost:8080/catalog/resources/item";
// Retrieve item list
function findAll() {
  $.ajax({
    type: 'GET',
    url: rootURL,
    dataType: "json",
   success: renderList });
}
function renderList(data) {
 var list =data;
 $('#itemList li').remove();
 $.each(list, function(index, item) {
 $('#itemList').append('<li><a href="#" data-identity="' + item.id + '">'+item.name+'</a></li>');
   });
}
Backbone.js client




© Availity, LLC | All rights reserved.
MVC




© Availity, LLC | All rights reserved.
Backbone.sync maps CRUD requests to REST
Save (new) → create → HTTP POST /url
Fetch → read → GET /url/id
Save → update → PUT /url/id
Destroy → delete → DELETE /url/id




© Availity, LLC | All rights reserved.
backbone Client
window.Item = Backbone.Model.extend({
    urlRoot: "resources/items",
    defaults: {
      id: null,
      name: "",
      description: "",
      imageurl: null
    }
});

window.ItemCollection = Backbone.Collection.extend({
    model: Item,
    url: "resources/items"
});
Agenda
•   REST Primer
•   RESTful Design and API Elements
•   Building a Simple Service
•   Security
•   Q&A
Securing your REST Web Service


• Authentication for Identity Verification
• Authorizaton
• Encryption
Authentication: Configure web.xml
 <login-config>
     <auth-method>BASIC</auth-method>
     <realm-name>admin</realm-name>
 </login-config>
Authentication: Configure web.xml
  <login-config>
      <auth-method>BASIC</auth-method>
      <realm-name>admin</realm-name>
  </login-config>
 • Login-config:
     >   defines how HTTP requests should be
         authenticated
 • Auth-method:
     >   BASIC, DIGEST, or CLIENT_CERT. corresponds
         to Basic, Digest, and Client Certificate
         authentication, respectively.
 • Realm-name:                                     realm
     >   Name for database of users and groups that
         identify valid users of a web application
Authentication: Configure web.xml
<security-constraint>
   <web-resource-collection>
     <url-pattern>/secure/*</url-pattern>
     <http-method>POST</http-method>
  </web-resource-collection>
...

• security constraint
      >  defines access privileges to a collection of
         resources
• url-pattern:
      >   URL pattern you want to secure
• Http-method:
      >  Methods to be protected
Authentication: Configure web.xml
<security-constraint>
...
  <auth-constraint>
     <description>only let admin login </description>
     <role-name>admin</role-name>
  </auth-constraint>


• auth-constraint:
     >  names the roles authorized to access the URL
        patterns and HTTP methods declared by this
        security constraint
Encryption: Configure web.xml
<security-constraint>
...
  <user-data-constraint>
    <description>SSL</description>
    <transport-guarantee>CONFIDENTIAL</transport-guarantee>
 </user-data-constraint>
</security-constraint>


 • user-data-constraint: NONE, INTEGRAL, or
   CONFIDENTIAL
      >   how the data will be transported between client
          and server
Authentication: Configure web.xml

  <security-role>
      <role-name>admin</role-name>
  </security-role>


 • security-role:
      lists all of the security roles used in the application
       >   For every <role-name> used in <auth-
           constraints> must define a corresponding
           <security-role>
 • http://java.sun.com/javaee/5/docs/tutorial/doc/bncas.html
Authentication: map roles to realm
<sun-web-app>
 <security-role-mapping>
   <role-name>admin</role-name>
   <principal-name>admin</principal-name>
 </security-role-mapping>
</sun-web-app>
                                          LDAP
 • security-role-mapping:                 realm
      >   Assigns security role to a group or user in
          Application Server realm
 • Realm:
     >  database of users and groups that identify valid
        users of a web application (FILE, LDAP
Authentication: map roles to realm
                                      file
                                     realm
Authorization Annotations
                           roles permitted to execute operation
@Path("/customers")
@RolesAllowed({"ADMIN", "CUSTOMER"})
public class CustomerResource {
   @GET
   @Path("{id}")
   @Produces("application/xml")
   public Customer getCustomer(@PathParam("id")
         int id) {...}
   @RolesAllowed("ADMIN")
   @POST
   @Consumes("application/xml")
   public void createCustomer(Customer cust) {...}
   @PermitAll
   @GET
   @Produces("application/xml") authenticated user
                               any
   public Customer[] getCustomers() {}
}
JAX-RS Security Context

public interface SecurityContext {
                               Determine the identity of the user
     public Principal getUserPrincipal();
                     check whether user belongs to a certain role
     public boolean isUserInRole(String role);
               whether this request was made using a secure channel
     public boolean isSecure();
     public String getAuthenticationScheme();
}
JAX-RS Security Context

@Path("/customers")                    check whether user
public class CustomerService {         belongs to a certain role
   @GET
   @Produces("application/xml")
   public Customer[] getCustomers(@Context
      SecurityContext sec) {
      if (sec.isSecure() && !sec.isUserInRole("ADMIN")){
        logger.log(sec.getUserPrincipal() +
                      " accessed customer database.");
      }
      ...
   }
}
                       Determine the identity of the user
Java EE 6

• JAX-RS is part of Java EE 6
• Gradle dependencies are easy

 apply plugin: 'war'
dependencies {
  testCompile 'org.glassfish.extras:glassfish-embedded-all:3.0.1'
  providedCompile 'org.glassfish.extras:glassfish-embedded-
   all:3.0.1’
}
Java EE 6 security
• Service/Façade
    • Declarative (@RolesAllowed)
    • Programmatic
• Web Controller
    • New annotations for authentication & authorization
    • @ServletSecurity @HttpConstraint , @HttpMethodConstraint

    • @WebFilter @DeclareRoles @RunAsPresentation
• Transport Layer
    • CONFIDENTIAL, INTEGRAL, NONE
    • ServletSecurity.TransportGuarantee

@WebServlet(name="UnderwritingServlet", urlPatterns={"/UnderwritingServlet"})
@ServletSecurity(@HttpConstraint(transportGuarantee=ServletSecurity.Transport
   Guarantee.CONFIDENTIAL),
))



© Availity, LLC | All rights reserved.
CDI

  • Bean discovery and wiring

public class ItemController {

 @Inject
 private CatalogService catalogService ;




© Availity, LLC | All rights reserved.
Bean Validation
public class Address {
  @NotNull @Size(max=30,
       message="longer than {max} characters")
  private String street1;
  ...
  @NotNull @Valid
  private Country country;
}

public class Country {
  @NotNull @Size(max=30)
  private String name;
  ...
}



© Availity, LLC | All rights reserved.
Servlet 3.0
  • Ease of Development
       @WebServlet(urlPatterns=“/foo”,
                name=”MyServlet”,
                asyncSupported=true)

  • @WebFilter("/secured/*")
  • Asynchronous Servlet
        >     Support Comet applications
  • Security enhancements




© Availity, LLC | All rights reserved.
Summary
•   REST architecture is gaining popularity
    >   Simple, scalable and the infrastructure is already in place
•   JAX-RS (JSR-311) provides a high level declarative
    programming model
    >   http://jersey.dev.java.net
For More Information
•    Reference Implementation
    • http://jersey.java.net/

•    Java EE 6 tutorial
    • http://docs.oracle.com/javaee/6/tutorial/doc/

•    Backbone.js JAX-RS example
    • http://coenraets.org/blog/2011/12/backbone-js-wine-cellar-tutorial-
     part-1-getting-started/
•    JAX-RS Comet example
    • http://www.oracle.com/technetwork/systems/articles/cometslideshow-
     139170.html
For More Information
• RESTful Java with JAX-RS

Contenu connexe

Tendances

JAX-RS 2.0: RESTful Web Services
JAX-RS 2.0: RESTful Web ServicesJAX-RS 2.0: RESTful Web Services
JAX-RS 2.0: RESTful Web ServicesArun Gupta
 
CouchDB : More Couch
CouchDB : More CouchCouchDB : More Couch
CouchDB : More Couchdelagoya
 
Java Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicJava Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicIMC Institute
 
5 Ways to Use Spark to Enrich your Cassandra Environment
5 Ways to Use Spark to Enrich your Cassandra Environment5 Ways to Use Spark to Enrich your Cassandra Environment
5 Ways to Use Spark to Enrich your Cassandra EnvironmentJim Hatcher
 
OUG Scotland 2014 - NoSQL and MySQL - The best of both worlds
OUG Scotland 2014 - NoSQL and MySQL - The best of both worldsOUG Scotland 2014 - NoSQL and MySQL - The best of both worlds
OUG Scotland 2014 - NoSQL and MySQL - The best of both worldsAndrew Morgan
 
CouchDB – A Database for the Web
CouchDB – A Database for the WebCouchDB – A Database for the Web
CouchDB – A Database for the WebKarel Minarik
 
What's new in DWR version 3
What's new in DWR version 3What's new in DWR version 3
What's new in DWR version 3Joe Walker
 
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...MongoDB
 
Power JSON with PostgreSQL
Power JSON with PostgreSQLPower JSON with PostgreSQL
Power JSON with PostgreSQLEDB
 
Introduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UK
Introduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UKIntroduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UK
Introduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UKSkills Matter
 
Schema Agnostic Indexing with Azure DocumentDB
Schema Agnostic Indexing with Azure DocumentDBSchema Agnostic Indexing with Azure DocumentDB
Schema Agnostic Indexing with Azure DocumentDBDharma Shukla
 
Hw09 Sqoop Database Import For Hadoop
Hw09   Sqoop Database Import For HadoopHw09   Sqoop Database Import For Hadoop
Hw09 Sqoop Database Import For HadoopCloudera, Inc.
 
The other Apache Technologies your Big Data solution needs
The other Apache Technologies your Big Data solution needsThe other Apache Technologies your Big Data solution needs
The other Apache Technologies your Big Data solution needsgagravarr
 
Leveraging Hadoop in Polyglot Architectures
Leveraging Hadoop in Polyglot ArchitecturesLeveraging Hadoop in Polyglot Architectures
Leveraging Hadoop in Polyglot ArchitecturesThanigai Vellore
 
Ldap Synchronization Connector @ 2011.RMLL
Ldap Synchronization Connector @ 2011.RMLLLdap Synchronization Connector @ 2011.RMLL
Ldap Synchronization Connector @ 2011.RMLLsbahloul
 
Synchronize AD and OpenLDAP with LSC
Synchronize AD and OpenLDAP with LSCSynchronize AD and OpenLDAP with LSC
Synchronize AD and OpenLDAP with LSCLDAPCon
 
Apache MetaModel - unified access to all your data points
Apache MetaModel - unified access to all your data pointsApache MetaModel - unified access to all your data points
Apache MetaModel - unified access to all your data pointsKasper Sørensen
 
Implementing and Visualizing Clickstream data with MongoDB
Implementing and Visualizing Clickstream data with MongoDBImplementing and Visualizing Clickstream data with MongoDB
Implementing and Visualizing Clickstream data with MongoDBMongoDB
 

Tendances (20)

JAX-RS 2.0: RESTful Web Services
JAX-RS 2.0: RESTful Web ServicesJAX-RS 2.0: RESTful Web Services
JAX-RS 2.0: RESTful Web Services
 
CouchDB : More Couch
CouchDB : More CouchCouchDB : More Couch
CouchDB : More Couch
 
Java Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicJava Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet Basic
 
L12: REST Service
L12: REST ServiceL12: REST Service
L12: REST Service
 
5 Ways to Use Spark to Enrich your Cassandra Environment
5 Ways to Use Spark to Enrich your Cassandra Environment5 Ways to Use Spark to Enrich your Cassandra Environment
5 Ways to Use Spark to Enrich your Cassandra Environment
 
OUG Scotland 2014 - NoSQL and MySQL - The best of both worlds
OUG Scotland 2014 - NoSQL and MySQL - The best of both worldsOUG Scotland 2014 - NoSQL and MySQL - The best of both worlds
OUG Scotland 2014 - NoSQL and MySQL - The best of both worlds
 
CouchDB – A Database for the Web
CouchDB – A Database for the WebCouchDB – A Database for the Web
CouchDB – A Database for the Web
 
What's new in DWR version 3
What's new in DWR version 3What's new in DWR version 3
What's new in DWR version 3
 
Couch db
Couch dbCouch db
Couch db
 
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
 
Power JSON with PostgreSQL
Power JSON with PostgreSQLPower JSON with PostgreSQL
Power JSON with PostgreSQL
 
Introduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UK
Introduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UKIntroduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UK
Introduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UK
 
Schema Agnostic Indexing with Azure DocumentDB
Schema Agnostic Indexing with Azure DocumentDBSchema Agnostic Indexing with Azure DocumentDB
Schema Agnostic Indexing with Azure DocumentDB
 
Hw09 Sqoop Database Import For Hadoop
Hw09   Sqoop Database Import For HadoopHw09   Sqoop Database Import For Hadoop
Hw09 Sqoop Database Import For Hadoop
 
The other Apache Technologies your Big Data solution needs
The other Apache Technologies your Big Data solution needsThe other Apache Technologies your Big Data solution needs
The other Apache Technologies your Big Data solution needs
 
Leveraging Hadoop in Polyglot Architectures
Leveraging Hadoop in Polyglot ArchitecturesLeveraging Hadoop in Polyglot Architectures
Leveraging Hadoop in Polyglot Architectures
 
Ldap Synchronization Connector @ 2011.RMLL
Ldap Synchronization Connector @ 2011.RMLLLdap Synchronization Connector @ 2011.RMLL
Ldap Synchronization Connector @ 2011.RMLL
 
Synchronize AD and OpenLDAP with LSC
Synchronize AD and OpenLDAP with LSCSynchronize AD and OpenLDAP with LSC
Synchronize AD and OpenLDAP with LSC
 
Apache MetaModel - unified access to all your data points
Apache MetaModel - unified access to all your data pointsApache MetaModel - unified access to all your data points
Apache MetaModel - unified access to all your data points
 
Implementing and Visualizing Clickstream data with MongoDB
Implementing and Visualizing Clickstream data with MongoDBImplementing and Visualizing Clickstream data with MongoDB
Implementing and Visualizing Clickstream data with MongoDB
 

Similaire à Rest

JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011Shreedhar Ganapathy
 
RESTful Web Services with JAX-RS
RESTful Web Services with JAX-RSRESTful Web Services with JAX-RS
RESTful Web Services with JAX-RSCarol McDonald
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVCIndicThreads
 
Spark IT 2011 - Developing RESTful Web services with JAX-RS
Spark IT 2011 - Developing RESTful Web services with JAX-RSSpark IT 2011 - Developing RESTful Web services with JAX-RS
Spark IT 2011 - Developing RESTful Web services with JAX-RSArun Gupta
 
Restful webservice
Restful webserviceRestful webservice
Restful webserviceDong Ngoc
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web servicesnbuddharaju
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to TornadoGavin Roy
 
RESTful application with JAX-RS and how to expose and test them
RESTful application with JAX-RS and how to expose and test themRESTful application with JAX-RS and how to expose and test them
RESTful application with JAX-RS and how to expose and test themKumaraswamy M
 
Expose your data as an api is with oracle rest data services -spoug Madrid
Expose your data as an api is with oracle rest data services -spoug MadridExpose your data as an api is with oracle rest data services -spoug Madrid
Expose your data as an api is with oracle rest data services -spoug MadridVinay Kumar
 
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonMulti Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonJoshua Long
 
03 form-data
03 form-data03 form-data
03 form-datasnopteck
 
Restful webservices
Restful webservicesRestful webservices
Restful webservicesKong King
 
Are you getting Sleepy. REST in SharePoint Apps
Are you getting Sleepy. REST in SharePoint AppsAre you getting Sleepy. REST in SharePoint Apps
Are you getting Sleepy. REST in SharePoint AppsLiam Cleary [MVP]
 
Android App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web ServicesAndroid App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web ServicesAnuchit Chalothorn
 

Similaire à Rest (20)

JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011
 
RESTful Web Services with JAX-RS
RESTful Web Services with JAX-RSRESTful Web Services with JAX-RS
RESTful Web Services with JAX-RS
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC
 
Doing REST Right
Doing REST RightDoing REST Right
Doing REST Right
 
Spark IT 2011 - Developing RESTful Web services with JAX-RS
Spark IT 2011 - Developing RESTful Web services with JAX-RSSpark IT 2011 - Developing RESTful Web services with JAX-RS
Spark IT 2011 - Developing RESTful Web services with JAX-RS
 
Restful webservice
Restful webserviceRestful webservice
Restful webservice
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web services
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to Tornado
 
RESTful application with JAX-RS and how to expose and test them
RESTful application with JAX-RS and how to expose and test themRESTful application with JAX-RS and how to expose and test them
RESTful application with JAX-RS and how to expose and test them
 
Expose your data as an api is with oracle rest data services -spoug Madrid
Expose your data as an api is with oracle rest data services -spoug MadridExpose your data as an api is with oracle rest data services -spoug Madrid
Expose your data as an api is with oracle rest data services -spoug Madrid
 
Ws rest
Ws restWs rest
Ws rest
 
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonMulti Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
 
03 form-data
03 form-data03 form-data
03 form-data
 
Web services tutorial
Web services tutorialWeb services tutorial
Web services tutorial
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
Restful webservices
Restful webservicesRestful webservices
Restful webservices
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 
Are you getting Sleepy. REST in SharePoint Apps
Are you getting Sleepy. REST in SharePoint AppsAre you getting Sleepy. REST in SharePoint Apps
Are you getting Sleepy. REST in SharePoint Apps
 
Android App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web ServicesAndroid App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web Services
 
Android and REST
Android and RESTAndroid and REST
Android and REST
 

Plus de Carol McDonald

Introduction to machine learning with GPUs
Introduction to machine learning with GPUsIntroduction to machine learning with GPUs
Introduction to machine learning with GPUsCarol McDonald
 
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...Carol McDonald
 
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DBAnalyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DBCarol McDonald
 
Analysis of Popular Uber Locations using Apache APIs: Spark Machine Learning...
Analysis of Popular Uber Locations using Apache APIs:  Spark Machine Learning...Analysis of Popular Uber Locations using Apache APIs:  Spark Machine Learning...
Analysis of Popular Uber Locations using Apache APIs: Spark Machine Learning...Carol McDonald
 
Predicting Flight Delays with Spark Machine Learning
Predicting Flight Delays with Spark Machine LearningPredicting Flight Delays with Spark Machine Learning
Predicting Flight Delays with Spark Machine LearningCarol McDonald
 
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DBStructured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DBCarol McDonald
 
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...Carol McDonald
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...Carol McDonald
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...Carol McDonald
 
How Big Data is Reducing Costs and Improving Outcomes in Health Care
How Big Data is Reducing Costs and Improving Outcomes in Health CareHow Big Data is Reducing Costs and Improving Outcomes in Health Care
How Big Data is Reducing Costs and Improving Outcomes in Health CareCarol McDonald
 
Demystifying AI, Machine Learning and Deep Learning
Demystifying AI, Machine Learning and Deep LearningDemystifying AI, Machine Learning and Deep Learning
Demystifying AI, Machine Learning and Deep LearningCarol McDonald
 
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...Carol McDonald
 
Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures Carol McDonald
 
Spark machine learning predicting customer churn
Spark machine learning predicting customer churnSpark machine learning predicting customer churn
Spark machine learning predicting customer churnCarol McDonald
 
Fast Cars, Big Data How Streaming can help Formula 1
Fast Cars, Big Data How Streaming can help Formula 1Fast Cars, Big Data How Streaming can help Formula 1
Fast Cars, Big Data How Streaming can help Formula 1Carol McDonald
 
Applying Machine Learning to Live Patient Data
Applying Machine Learning to  Live Patient DataApplying Machine Learning to  Live Patient Data
Applying Machine Learning to Live Patient DataCarol McDonald
 
Streaming Patterns Revolutionary Architectures with the Kafka API
Streaming Patterns Revolutionary Architectures with the Kafka APIStreaming Patterns Revolutionary Architectures with the Kafka API
Streaming Patterns Revolutionary Architectures with the Kafka APICarol McDonald
 
Apache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision TreesApache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision TreesCarol McDonald
 
Advanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming DataAdvanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming DataCarol McDonald
 

Plus de Carol McDonald (20)

Introduction to machine learning with GPUs
Introduction to machine learning with GPUsIntroduction to machine learning with GPUs
Introduction to machine learning with GPUs
 
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
 
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DBAnalyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
 
Analysis of Popular Uber Locations using Apache APIs: Spark Machine Learning...
Analysis of Popular Uber Locations using Apache APIs:  Spark Machine Learning...Analysis of Popular Uber Locations using Apache APIs:  Spark Machine Learning...
Analysis of Popular Uber Locations using Apache APIs: Spark Machine Learning...
 
Predicting Flight Delays with Spark Machine Learning
Predicting Flight Delays with Spark Machine LearningPredicting Flight Delays with Spark Machine Learning
Predicting Flight Delays with Spark Machine Learning
 
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DBStructured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
 
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
 
How Big Data is Reducing Costs and Improving Outcomes in Health Care
How Big Data is Reducing Costs and Improving Outcomes in Health CareHow Big Data is Reducing Costs and Improving Outcomes in Health Care
How Big Data is Reducing Costs and Improving Outcomes in Health Care
 
Demystifying AI, Machine Learning and Deep Learning
Demystifying AI, Machine Learning and Deep LearningDemystifying AI, Machine Learning and Deep Learning
Demystifying AI, Machine Learning and Deep Learning
 
Spark graphx
Spark graphxSpark graphx
Spark graphx
 
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
 
Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures
 
Spark machine learning predicting customer churn
Spark machine learning predicting customer churnSpark machine learning predicting customer churn
Spark machine learning predicting customer churn
 
Fast Cars, Big Data How Streaming can help Formula 1
Fast Cars, Big Data How Streaming can help Formula 1Fast Cars, Big Data How Streaming can help Formula 1
Fast Cars, Big Data How Streaming can help Formula 1
 
Applying Machine Learning to Live Patient Data
Applying Machine Learning to  Live Patient DataApplying Machine Learning to  Live Patient Data
Applying Machine Learning to Live Patient Data
 
Streaming Patterns Revolutionary Architectures with the Kafka API
Streaming Patterns Revolutionary Architectures with the Kafka APIStreaming Patterns Revolutionary Architectures with the Kafka API
Streaming Patterns Revolutionary Architectures with the Kafka API
 
Apache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision TreesApache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision Trees
 
Advanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming DataAdvanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming Data
 

Rest

  • 1. REST with JAX-RS, Security, Java EE 6 Carol McDonald
  • 2. Agenda • REST Primer • RESTful Design and API Elements • Building a Simple Service • Security • Q&A
  • 3. REpresentational State Transfer Get Response XML data = REST Web http://www.depot.com/parts Service REpresentational State Client Transfer Client State1 State2  The URL identifies the resource  Click on the url (resource) in page (hypermedia) html page is transferred to the browser REpresentational State transfer occurs
  • 4. REST Tenets • Resources (nouns) > Identified by a URI, For example:  http://www.parts-depot.com/parts • Methods (verbs) to manipulate the nouns > Small fixed set:  GET, PUT, POST, DELETE Read, Update, Create, Delete • Representation of the Resource > data and state transferred between client and server > XML, JSON... • Use verbs to exchange application state and representation
  • 5. method resource Request: GET http://localhost:8080/RestfulCustomer/webresources/model.customer/1 Status: 200 (OK) Time-Stamp: Fri, 14 Dec 2012 02:19:34 GMT Received: {"name":"Jumbo Eagle Corp","state":"FL","customerId":1, "addressline1":"111 E. Las Olivas Blvd","addressline2":"Suite 51", "city":"Fort Lauderdale","phone":"305-555-0188","fax":"305-555-0189", "email":"jumboeagle@example.com","creditLimit":100000 } representation
  • 6. Rest Uniform Interface: Every thing is a Resource Every resource has an id, URI is the id  http://company.com/customers/123456
  • 7. Every Resource has an Id URI is the id, Every resource has a URI http://company.com/customers/123456 Resource Collection name Primary key • URIs identify : > items, collections of items, virtual and physical objects, or computation results. http://company.com/customers/123456/orders/12 http://example.com/orders/2007/11 http://example.com/products?color=green
  • 8. Rest Standard Interface: Use Standard HTTP Methods • Example  GET /store/customers/123456
  • 9. Use Standard Methods: • /orders – GET - list all orders Order Customer – POST - submit a new order Mgmt Example  /orders/{order-id} > GET - get an order representation > PUT - update an order > DELETE - cancel an order  /orders/average-sale – GET - calculate average sale • /customers http://www.infoq.com/articles/rest- – GET - list all customers introduction – POST - create a new customer  /customers/{cust-id} > GET - get a customer representation > DELETE- remove a customer  /customers/{cust-id}/orders – GET - get the orders of a customer
  • 10. Use Standard HTTP Methods • HTTP Get, Head > Should not modify anything > Cache-able With Correct use of Last-Modified and ETag • Idempotency: > PUT, DELETE, GET, HEAD can be repeated and the results are the same
  • 11. Link things together • Hypermedia • As • The • Engine • Of • Application • State HATEOAS © Availity, LLC | All rights reserved.
  • 12. Link Things Together Representations contain links to other resources: <prop self="http://example.com/orders/101230"> <customer ref="http://example.com/customers/bar"> <product ref="http://example.com/products/21034"/> <amount value="1"/> </order> • Service provides links in response to the Client > Enables client to move the application from one state to the next by following a link
  • 14. Example © Availity, LLC | All rights reserved.
  • 15. Multiple Representations • Offer data in a variety of formats, for different needs > XML > JSON > (X)HTML • Support content negotiation > Accept header GET /foo Accept: application/json > URI-based GET /foo.json > Response header > Content-Type application/xml
  • 16. content negotiation Request: http://localhost:8080/RestfulCustomer/webresources/application.wadl Status: 200 (OK) Time-Stamp: Fri, 14 Dec 2012 03:11:50 GMT Received: <?xml version="1.0" encoding="UTF-8"?> <resources base="http://localhost:8080/RestfulCustomer/webresources/"> <resource path="model.customer"> <method id="findAll" name="GET"> <response> <representation mediaType="application/xml"/> <representation mediaType="application/json"/> </response> </method>
  • 17. Stateless Communications • HTTP protocol is stateless • Everything required to process a request contained in the request > No client session on the server > Eliminates many failure conditions • application state kept on Client • Service responsible for resource state
  • 18. Rest Common Patterns: Container, Item Server in control of URI • Container – a collection of items • List catalog items: GET /catalog/items • Add item to container: POST /catalog/items > with item in request > URI of item returned in HTTP response header > e.g. http://host/catalog/items/1 • Update item: PUT /catalog/items/1 > with updated item in request Good example: Atom Publishing Protocol
  • 19. Common Patterns: Map, Key, Value Client in control of URI • List key-value pairs: GET /map • Put new value to map: PUT /map/{key} > with entry in request > e.g. PUT /map/dir/contents.xml • Read value: GET /map/{key} • Update value: PUT /map/{key} > with updated value in request • Remove value: DELETE /map/{key} • Good example: Amazon S3
  • 20. Rest Key Benefits • Server side > Uniform Interface > Cacheable > Scalable > Easy failover • Client side > Easy to experiment in browser > Broad programming language support > Choice of data formats
  • 21. Agenda • REST Primer • RESTful Design and API Elements with JAX-RS • Building a Simple Service • Status • Q&A
  • 22. JAX-RS: Clear mapping to REST concepts • High level, Declarative > Uses @ annotation in POJOs • Jersey – reference implementation of JSR 311  Download it from http://jersey.dev.java.net  Comes with Glassfish, Java EE 6  Tools support in NetBeans
  • 23. Resources • Resource class > POJO, No required interfaces • ID provided by @Path annotation > Relative to deployment context > Annotate class or “sub-resource locator” method http://host/ctx/orders/12 @Path("orders/{id}") public class OrderResource { @Path("customer") http://host/ctx/orders/12/customer CustomerResource getCustomer(...) {...} }
  • 24. Request Mapping • Annotate resource class methods with standard method > @GET, @PUT, @POST, @DELETE, @HEAD • annotations on parameters specify mapping from request data • Return value mapped to http response @Path("orders/{order_id}") public class OrderResource { @GET Order getOrder(@PathParam("order_id") String id) { ... } }
  • 25.
  • 26. Multiple Representations Static and dynamic content negotiation • Annotate methods or classes > @Produces matches Accepts header > @Consumes matches Content-Type header @GET @Consumes("application/json") @Produces({"application/xml","application/json"}) String getOrder(@PathParam("order_id") String id) { ... }
  • 27. Multiple Representations: JAX-RS consuming @Path("/items/") @ConsumeMime(“application/xml”) public class ItemsResource { http://host/catalog/items/?start=0 @GET ItemsConverter get(@QueryParam("start") int start) { ... } http://host/catalog/items/123 @Path("{id}/") ItemResource getItemResource(@PathParam("id")Long id){ ... } }
  • 28. Multiple Representations @Post @ConsumeMime(“application/x-www-form-urlencoded”) @ProduceMime(“application/xml”) public JAXBClass updateEmployee( MultivalueMap<String, String> form) { ... converted to XML Converted to a map for accessing form's field
  • 29. Multiple Representations: producing a response @Path(“/items”) class Items { Use Response class to build “created”response @POST @ProduceMime(“application/xml”) Response create(Ent e) { // persist the new entry, create URI return Response.created( uriInfo.getAbsolutePath(). resolve(uri+"/")).build(); } }
  • 30. Uniform interface: HTTP request and response C: POST /items HTTP/1.1 C: Host: host.com C: Content-Type: application/xml C: Content-Length: 35 C: C: <item><name>dog</name></item> S: HTTP/1.1 201 Created S: Location: http://host.com/employees/1234 S: Content-Length: 0
  • 31. Link Things Together • UriInfo provides information about the request URI and the route to the resource • UriBuilder provides facilities to easily build URIs for resources @Context UriInfo info; OrderResource r = ... UriBuilder b = info.getBaseUriBuilder(); URI u = b.path(OrderResource.class).build(r.id);
  • 32. Agenda • REST Primer • RESTful Design and API Elements • Building a Simple Service • Deployment Options • Status
  • 34. URIs and Methods: Item Catalog Example  /items – GET - list all items – POST – add item to catalog  /items/{id} > GET - get an item representation > PUT - update an item > DELETE – remove an item http://www.infoq.com/articles/rest- introduction
  • 35. Methods @Path(“/items”) class ItemsResource { @GET public List<Item> findAll() { ... } @POST Response create(Item) { ... } @PUT @Path("{id}") public void editp(Item entity) {} @GET @Path("{id}") public Item find(@PathParam("id") Integer id) { ... } } Java method name is not significant The @HTTP method is the method
  • 36. RESTful Catalog  Javascript client, JAX-RS, JSON, JPA Registration Application JAX-RS class Entity Class JSON class Item DB ItemsResource javascript client
  • 37. Item Entity JAXB annotated @Entity @Table(name = "ITEM") @XmlRootElement public class Item implements Serializable { @Id private Integer id; ... }
  • 38. XML <item uri="http://localhost/Web/resources/items/1/"> <description> black cat is nice</description> <id>1</id> <imagethumburl>/images/anth.jpg</imagethumburl> <name>not Friendly Cat</name> <price>307.10</price> <productid>feline01</productid> </item>
  • 39. JSON { "@uri":"http://host/catalog/resources/items/1/", "name":"Friendly Cat", "description":"This black and white colored cat is super friendly.", "id":"1", "imageurl":"http://localhost:8080/CatalogService/images/anthony.jpg" }
  • 40. Resource Classes > Items Resource retrieves updates a collection of Item entities > /items – URI for a list of Items > /item/1 – URI for item 1 JAX-RS class Entity Class Item DB ItemsResource Dojo client
  • 41. Get Items responds to the URI http://host/catalog/items/ @Path("/items/") responds to HTTP GET public class ItemsResource { responds with JSON @GET @Produces("application/json") JAXB class public List<Item> get(){ CriteriaQuery cq = getEntityManager(). getCriteriaBuilder().createQuery(); cq.select(cq.from(Item)); return getEntityManager().createQuery (cq).getResultList(); } Performs JPA Query, returns list of entities
  • 42. JQuery Client var rootURL = "http://localhost:8080/catalog/resources/item"; // Retrieve item list function findAll() { $.ajax({ type: 'GET', url: rootURL, dataType: "json", success: renderList }); } function renderList(data) { var list =data; $('#itemList li').remove(); $.each(list, function(index, item) { $('#itemList').append('<li><a href="#" data-identity="' + item.id + '">'+item.name+'</a></li>'); }); }
  • 43. Backbone.js client © Availity, LLC | All rights reserved.
  • 44. MVC © Availity, LLC | All rights reserved.
  • 45. Backbone.sync maps CRUD requests to REST Save (new) → create → HTTP POST /url Fetch → read → GET /url/id Save → update → PUT /url/id Destroy → delete → DELETE /url/id © Availity, LLC | All rights reserved.
  • 46. backbone Client window.Item = Backbone.Model.extend({ urlRoot: "resources/items", defaults: { id: null, name: "", description: "", imageurl: null } }); window.ItemCollection = Backbone.Collection.extend({ model: Item, url: "resources/items" });
  • 47. Agenda • REST Primer • RESTful Design and API Elements • Building a Simple Service • Security • Q&A
  • 48. Securing your REST Web Service • Authentication for Identity Verification • Authorizaton • Encryption
  • 49. Authentication: Configure web.xml <login-config> <auth-method>BASIC</auth-method> <realm-name>admin</realm-name> </login-config>
  • 50. Authentication: Configure web.xml <login-config> <auth-method>BASIC</auth-method> <realm-name>admin</realm-name> </login-config> • Login-config: > defines how HTTP requests should be authenticated • Auth-method: > BASIC, DIGEST, or CLIENT_CERT. corresponds to Basic, Digest, and Client Certificate authentication, respectively. • Realm-name: realm > Name for database of users and groups that identify valid users of a web application
  • 51. Authentication: Configure web.xml <security-constraint> <web-resource-collection> <url-pattern>/secure/*</url-pattern> <http-method>POST</http-method> </web-resource-collection> ... • security constraint > defines access privileges to a collection of resources • url-pattern: > URL pattern you want to secure • Http-method: > Methods to be protected
  • 52. Authentication: Configure web.xml <security-constraint> ... <auth-constraint> <description>only let admin login </description> <role-name>admin</role-name> </auth-constraint> • auth-constraint: > names the roles authorized to access the URL patterns and HTTP methods declared by this security constraint
  • 53. Encryption: Configure web.xml <security-constraint> ... <user-data-constraint> <description>SSL</description> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint> • user-data-constraint: NONE, INTEGRAL, or CONFIDENTIAL > how the data will be transported between client and server
  • 54. Authentication: Configure web.xml <security-role> <role-name>admin</role-name> </security-role> • security-role: lists all of the security roles used in the application > For every <role-name> used in <auth- constraints> must define a corresponding <security-role> • http://java.sun.com/javaee/5/docs/tutorial/doc/bncas.html
  • 55. Authentication: map roles to realm <sun-web-app> <security-role-mapping> <role-name>admin</role-name> <principal-name>admin</principal-name> </security-role-mapping> </sun-web-app> LDAP • security-role-mapping: realm > Assigns security role to a group or user in Application Server realm • Realm: > database of users and groups that identify valid users of a web application (FILE, LDAP
  • 56. Authentication: map roles to realm file realm
  • 57. Authorization Annotations roles permitted to execute operation @Path("/customers") @RolesAllowed({"ADMIN", "CUSTOMER"}) public class CustomerResource { @GET @Path("{id}") @Produces("application/xml") public Customer getCustomer(@PathParam("id") int id) {...} @RolesAllowed("ADMIN") @POST @Consumes("application/xml") public void createCustomer(Customer cust) {...} @PermitAll @GET @Produces("application/xml") authenticated user any public Customer[] getCustomers() {} }
  • 58. JAX-RS Security Context public interface SecurityContext { Determine the identity of the user public Principal getUserPrincipal(); check whether user belongs to a certain role public boolean isUserInRole(String role); whether this request was made using a secure channel public boolean isSecure(); public String getAuthenticationScheme(); }
  • 59. JAX-RS Security Context @Path("/customers") check whether user public class CustomerService { belongs to a certain role @GET @Produces("application/xml") public Customer[] getCustomers(@Context SecurityContext sec) { if (sec.isSecure() && !sec.isUserInRole("ADMIN")){ logger.log(sec.getUserPrincipal() + " accessed customer database."); } ... } } Determine the identity of the user
  • 60. Java EE 6 • JAX-RS is part of Java EE 6 • Gradle dependencies are easy apply plugin: 'war' dependencies { testCompile 'org.glassfish.extras:glassfish-embedded-all:3.0.1' providedCompile 'org.glassfish.extras:glassfish-embedded- all:3.0.1’ }
  • 61. Java EE 6 security • Service/Façade • Declarative (@RolesAllowed) • Programmatic • Web Controller • New annotations for authentication & authorization • @ServletSecurity @HttpConstraint , @HttpMethodConstraint • @WebFilter @DeclareRoles @RunAsPresentation • Transport Layer • CONFIDENTIAL, INTEGRAL, NONE • ServletSecurity.TransportGuarantee @WebServlet(name="UnderwritingServlet", urlPatterns={"/UnderwritingServlet"}) @ServletSecurity(@HttpConstraint(transportGuarantee=ServletSecurity.Transport Guarantee.CONFIDENTIAL), )) © Availity, LLC | All rights reserved.
  • 62. CDI • Bean discovery and wiring public class ItemController { @Inject private CatalogService catalogService ; © Availity, LLC | All rights reserved.
  • 63. Bean Validation public class Address { @NotNull @Size(max=30, message="longer than {max} characters") private String street1; ... @NotNull @Valid private Country country; } public class Country { @NotNull @Size(max=30) private String name; ... } © Availity, LLC | All rights reserved.
  • 64. Servlet 3.0 • Ease of Development @WebServlet(urlPatterns=“/foo”, name=”MyServlet”, asyncSupported=true) • @WebFilter("/secured/*") • Asynchronous Servlet > Support Comet applications • Security enhancements © Availity, LLC | All rights reserved.
  • 65. Summary • REST architecture is gaining popularity > Simple, scalable and the infrastructure is already in place • JAX-RS (JSR-311) provides a high level declarative programming model > http://jersey.dev.java.net
  • 66. For More Information • Reference Implementation • http://jersey.java.net/ • Java EE 6 tutorial • http://docs.oracle.com/javaee/6/tutorial/doc/ • Backbone.js JAX-RS example • http://coenraets.org/blog/2011/12/backbone-js-wine-cellar-tutorial- part-1-getting-started/ • JAX-RS Comet example • http://www.oracle.com/technetwork/systems/articles/cometslideshow- 139170.html
  • 67. For More Information • RESTful Java with JAX-RS