SlideShare uma empresa Scribd logo
1 de 38
Baixar para ler offline
<Insert Picture Here>




Advanced Java API for
RESTful Web Services
Lee Chuk Munn
chuk-munn.lee@oracle.com
<Insert Picture Here>




                          Objective
Examine some “advance” features
                    in JAX-RS
Architectural Style
• Music styles – baroque, romantic, rap, jazz, etc
   – There is no Jazz (music) note
   – How you put the notes that makes the style
• Computing styles – client/server, object oriented, etc.
   – There is no client/server API
• “... a coordinated set of architectural constraints that
 restricts the roles/features of architectural elements
 and the allowed relationships among those elements
 within any architecture that conforms to that style” -
 Dr. Roy Fielding
What is REST?
• REpresentation State Transfer
   – Architectural Styles and the Design of Network-based
     Software Architecture – Roy Fielding PhD thesis
• Major components
  –   Nouns (resources) are identified by URIs
  –   A small subset of verbs to manipulate the nouns
  –   State of the data
  –   Representation is how you would like to view the state
• Use verbs to exchange application states and
  representation
• Hypermedia is the engine for application state
  transition
REST Example
• HTTP is one of the most RESTful protocol
• Example: the web browser
  – The URL is the noun (resource)
  – GET (verb) the page from the server
  – State of the page is transferred from the server to the browser
     • Page maybe static or dynamic
     • State of page now exists on the client
  – Page may be represented as HTML, RSS, JSON, etc.
  – Click on a link in page (hypermedia) the process is repeated
What is REST?
           Request
           GET /music/artists/magnum/recordings HTTP/1.1
           Host: media.example.com
           Accept: application/xml

   Verb    Response                 Noun
           HTTP/1.1 200 OK
           Date: Tue, 08 May 2007 16:41:58 GMT
           Server: Apache/1.3.6
           Content-Type: application/xml; charset=UTF-8

  State    <?xml version="1.0"?>
           <recordings xmlns="…">
transfer     <recording>…</recording>
             …                          Representation
           </recordings>
JAX-RS in One Slide
@Path(“/music”)
@Produces(“application/xml”)
public class Music {         www.mymusic.com/music
  @GET //Returns List<Genre>
  public Response getGenreList() {
    ...
  }

    @GET @Path(“{genre}”) //Returns List<Song>
    public Response getSongs(
         @PathParam(“genre”) String genreId) {
      ...
    }                    www.mymusic.com/music/jazz
}
Selected Topics
• Runtime resource resolution
• Integration with EJB and CDI
• Runtime content negotiation
• Conditional HTTP request
• Dealing with type erasure
• Pluggable exception handling
Terms
• Root resource
                                http://server/department/eng
  @Path(“department”)
  public class Department {
• Sub resource method
   – Handles the request
  @GET @Path(“{id}”)
  public Department get(
        @PathParam(“id”) String deptId) {
• Sub resource locator
   – Returns an object that will handle the request
  @Path(“{id}”)
  public Department get(
       @PathParam(“id”) String deptId) {
Runtime Resource Resolution
@Path(“department”)
public class Department {

  @Path(“{id}”)
  public Object get(
       @PathParam(“id”) String id) {
    //Determine department type and return resource
    return (new ...);
  }

public class Marketing extends Department {
  @GET @Path(“{type}”)
  public Response get(
       @PathParam(“type”) String deptType) { ... }
Runtime Resource Resolution
@Path(“department”)
public class Department {
  @Path(“{id}”)
  public Object get(
       @PathParam(“id”) String id) { ... }



    GET /department/marketing/tele
public class Marketing extends Department {
  @GET @Path(“{type}”)
  public Response get(
       @PathParam(“type”) String deptType) { ... }
Demo
More Resource Resolution
 • Sub resource locators determines what type of
   resource to return dynamically
    – Eg. Use JPA to query data and return that as a resource
    – Can be used with CDI or EJBs
    – All parameters must be annotated

@Path(“department”)
public class Department {
  @Path(“{id}”)
  public Object get(@PathParam(“id”) String id) {
     EntityManager em = ... //Get an instance
     Department dept = em.find(Department.class, id);
     return (dept);
  }
Resource Methods and Locators
• Easy to get confuse with sub-resource locator and
  sub-resource methods
• Both are annotated with @Path
• Sub-resource methods has resource method
  designators
  – Eg. @GET
• Sub-resource locator do not have method designators
Integration with EJB
 • Annotate @Path to convert into a root resource
    – Stateless session bean
    – Singleton bean


@Path("stateless-bean")
@Stateless
public class StatelessResource { ... }

@Path("singleton-bean")
@Singleton
public class SingletonResource { ... }
CDI One Pager
@Stateless public class ShoppingService {
  @Inject private Cart myCart;
  public void addToCart(Item someItem) {
     myCart.add(someItem);
  }
  …
}
public interface Cart {
  public void add(Item item);
}
@ConversationScoped
public class DefaultShoppingCart implements Cart {
  @PersistenceContext private EntityManager em;
  public void add(Item item) {
     …
  }
}
Using CDI with Root Resources
• Perfect world – use CDI to manage REST resources
   – CDI providing lifecycle management, dependency, etc
• Not very well specified
• See http://www.mentby.com/paul-sandoz/jax-rs-on-
 glassfish-31-ejb-injection.html
JAX-RS/CDI Component Models
• Root resources are managed in the request scope
   – Default
• CDI requires “normal” scoped beans to be proxyable
  – Annotated with @RequestScoped or @ApplicationScoped
  – Unproxyable beans
     • No non-private constructor with no argument
     • Final class
• Root resources needs to be annotated with CDI
 scoped to be managed by CDI
Using CDI with JAX-RS
• Request scoped, JAX-RS managed
  @Path(“customer/{id}”)
  public class Customer {
    public Customer(@PathParam(“id”) String id) {
• Application scoped, CDI managed, will fail
 @Path(“customer/{id}”) @ApplicationScoped
 public class Customer {
   @Inject
   public Customer(@PathParam(“id”) String id) {
• Application scoped, provide a no-args constructor
   – Use resource method to get id
 @Path(“customer/{id}”) @ApplicationScoped
 public class Customer {
   public Customer() { }
Demo
Representation
     Request
     GET /music/artists/magnum/recordings HTTP/1.1
     Host: media.example.com
     Accept: application/xml

                                        Format
     Response
     HTTP/1.1 200 OK
     Date: Tue, 08 May 2007 16:41:58 GMT
     Server: Apache/1.3.6
     Content-Type: application/xml; charset=UTF-8

     <?xml version="1.0"?>
     <recordings xmlns="…">
       <recording>…</recording>
       …
     </recordings>
Supported Media Types
• Out-of-the-box support for
   – */* - byte[], InputStream, DataSource
   – text/* - String
   – text/xml, application/xml, application/*+xml –
     JAXBElement
   – application/x-www-form-urlencoded –
     MultivalueMap
• Use @Produces or @Consumes to match with HTTP
 headers
  – Accept, Content-Type
Runtime Content Negotiation
• Static content/media type negotiation of
  representation supported with @Produces
• Runtime content negotiation of representation
  supports 4 dimensions
  – Media type, character set, language, encoding
• Each representation has a Variant which is a point
  in the 4 dimension space
List<Variant> variant = Variant
  .mediaType(MediaType.APPLICATION.JSON
     , MediaType.APPLICATION.XML)
  .languages(Locale.ENGLISH, Locale.CHINESE);

assert variant.size() == 4
Select Most Acceptable Variant
@GET public Response get(@Context Request r) {
   List<Variant> vs = ...
   Variant v = r.selectVariant(vs);
   if (v == null)
     return (Response.notAcceptable(vs).build());
   else {
     Object rep = selectRepresentation(v);
     return (Response.ok(rep, v));
   }
}
  • Selection will compare the list of variants with the
   correspond acceptable values in the client request
    – Accept, Accept-Langauge, Accept-Encoding, Accept-
      Charset
Conditional HTTP Request
• Save bandwidth and client processing
   – A GET can return a 304 (not modified) if representation has
     not changed since previous request
• Avoid the lost update problem
   – A PUT can return 412 (precondition failed) if the resource state
     has been modified since previous request
• A date and/or entity tag can be used
   – Last-Modified and Etag headers
   – HTTP dates have granularity of 1 second
   – Etags are better for use with PUT
Processng Etags
@GET
public Response get(@Context Request r) {
  EntityTag et = ... //Calculate etag
  Response.ResponseBuilder rb =
       r.evaluatePreconditions(et);
  if (rb != null) {
     // Return 304 (Not Modified)
     return rb.build();
  }
  String rep = ...
  return Response.ok(rep).tag(et).build();
}
Dealing with Type Erasure – 1
• Resources can return an entity

 @GET List<Customer> getCustomers() { ...

• Type information is lost when returning Response
 @GET Response getCustomers() {
   List<Customer> list = ...
   return (Response.ok(list).build());

• MessageBodyWriter support for List<Customer>
 will not work when type information is lost
  – Converts Java object to stream
Dealing with Type Erasure – 2
  • Use GenericEntity to preserve type information at
   runtime
@GET Response getCustomers() {
  List<Customer> list = ...
  GenericEntity<List<Customer>> ge =
      new GenericEntity<List<Customer>>(list){};
return (Response.ok(list).build());
Pluggable Exception Handling
• Propagation on unmapped exceptions to web
 container
  – A runtime exception thrown by the JAX-RS container or
    application is propagated as is
  – A checked exception is thrown by the application is
    propagated as the cause of a ServletException
  – Propagated exceptions can be mapped to error pages
• Runtime/checked exceptions can be “caught” and
 mapped to Response using ExceptionMapper
Exception Classes

Class A extends RuntimeException { … }

Class B extends A { … }

Class C extends B { … }
Exception Mapper
@Provider
public class AMapper
    implements ExceptionMapper<A> {
  public Response toResponse(A a) { … }
}

@Provider
public class BMapper
    implements ExceptionMapper<B> {
  public Response toResponse(B b) { … }
}
Throwing Exceptions

// throwing A maps to Response of AMapper
@GET public String a() throws A { ... }

// throwing B maps to Response of BMapper
@GET public String b() throws B { ... }

// throwing C maps to Response of BMapper
@GET public String c() throws C { ... }
ExceptionMapper
• ExceptionMapper “closest” to exception class is
  selected to map exception
• Can map Throwable
  @Provider public class CatchAll
       implements ExceptionMapper<Throwable> {
    public Response toResponse(Throwable t) {
       // Internal Server Error
       return Response.status(500).build();
    }
  }
• Inject @Provider to delegate
   – Map the cause of the exception
We encourage you to use the newly minted corporate tagline
“Software. Hardware. Complete.” at the end of all your presentations.
This message should replace any reference to our previous corporate
tagline “Oracle Is the Information Company.”
For More Information


        search.oracle.com




               or
           oracle.com
Alternate Title with Subhead
Arial Size 18 (Gray)

• First-level bullet
   – Second-level bullet
      • Third-level bullet
         – Fourth-level bullet
            • Fifth-level bullet

Mais conteúdo relacionado

Mais procurados

Mais procurados (19)

Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Servlets
ServletsServlets
Servlets
 
Jsp (java server page)
Jsp (java server page)Jsp (java server page)
Jsp (java server page)
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Jsp servlets
Jsp servletsJsp servlets
Jsp servlets
 
Java Servlet
Java Servlet Java Servlet
Java Servlet
 
Java Servlets & JSP
Java Servlets & JSPJava Servlets & JSP
Java Servlets & JSP
 
Java server pages
Java server pagesJava server pages
Java server pages
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jsp
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play framework
 
JSP
JSPJSP
JSP
 
Java.sql package
Java.sql packageJava.sql package
Java.sql package
 
RESTful web service with JBoss Fuse
RESTful web service with JBoss FuseRESTful web service with JBoss Fuse
RESTful web service with JBoss Fuse
 
JDBC
JDBCJDBC
JDBC
 
jsf2 Notes
jsf2 Notesjsf2 Notes
jsf2 Notes
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 

Semelhante a S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsCarol McDonald
 
RESTful Web services using JAX-RS
RESTful Web services using JAX-RSRESTful Web services using JAX-RS
RESTful Web services using JAX-RSArun Gupta
 
CDI, Seam & RESTEasy: You haven't seen REST yet!
CDI, Seam & RESTEasy: You haven't seen REST yet!CDI, Seam & RESTEasy: You haven't seen REST yet!
CDI, Seam & RESTEasy: You haven't seen REST yet!Dan Allen
 
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
 
JAX-RS Creating RESTFul services
JAX-RS Creating RESTFul servicesJAX-RS Creating RESTFul services
JAX-RS Creating RESTFul servicesLudovic Champenois
 
JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011Shreedhar Ganapathy
 
JSUG - RESTful Web Services by Florian Motlik
JSUG - RESTful Web Services by Florian MotlikJSUG - RESTful Web Services by Florian Motlik
JSUG - RESTful Web Services by Florian MotlikChristoph Pickl
 
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
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web servicesnbuddharaju
 
03 form-data
03 form-data03 form-data
03 form-datasnopteck
 
Building Restful Web Services with Java
Building Restful Web Services with JavaBuilding Restful Web Services with Java
Building Restful Web Services with JavaVassil Popovski
 
Javaone 2010
Javaone 2010Javaone 2010
Javaone 2010Hien Luu
 
Restful webservice
Restful webserviceRestful webservice
Restful webserviceDong Ngoc
 
Object Graph Mapping with Spring Data Neo4j 3 - Nicki Watt & Michael Hunger @...
Object Graph Mapping with Spring Data Neo4j 3 - Nicki Watt & Michael Hunger @...Object Graph Mapping with Spring Data Neo4j 3 - Nicki Watt & Michael Hunger @...
Object Graph Mapping with Spring Data Neo4j 3 - Nicki Watt & Michael Hunger @...Neo4j
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVCIndicThreads
 

Semelhante a S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010 (20)

Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
 
Rest
RestRest
Rest
 
RESTful Web services using JAX-RS
RESTful Web services using JAX-RSRESTful Web services using JAX-RS
RESTful Web services using JAX-RS
 
CDI, Seam & RESTEasy: You haven't seen REST yet!
CDI, Seam & RESTEasy: You haven't seen REST yet!CDI, Seam & RESTEasy: You haven't seen REST yet!
CDI, Seam & RESTEasy: You haven't seen REST yet!
 
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
 
JAX-RS Creating RESTFul services
JAX-RS Creating RESTFul servicesJAX-RS Creating RESTFul services
JAX-RS Creating RESTFul services
 
JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011
 
JSUG - RESTful Web Services by Florian Motlik
JSUG - RESTful Web Services by Florian MotlikJSUG - RESTful Web Services by Florian Motlik
JSUG - RESTful Web Services by Florian Motlik
 
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
 
Jersey
JerseyJersey
Jersey
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web services
 
Rest And Rails
Rest And RailsRest And Rails
Rest And Rails
 
03 form-data
03 form-data03 form-data
03 form-data
 
Building Restful Web Services with Java
Building Restful Web Services with JavaBuilding Restful Web Services with Java
Building Restful Web Services with Java
 
Javaone 2010
Javaone 2010Javaone 2010
Javaone 2010
 
Andrei shakirin rest_cxf
Andrei shakirin rest_cxfAndrei shakirin rest_cxf
Andrei shakirin rest_cxf
 
Restful webservice
Restful webserviceRestful webservice
Restful webservice
 
REST easy with API Platform
REST easy with API PlatformREST easy with API Platform
REST easy with API Platform
 
Object Graph Mapping with Spring Data Neo4j 3 - Nicki Watt & Michael Hunger @...
Object Graph Mapping with Spring Data Neo4j 3 - Nicki Watt & Michael Hunger @...Object Graph Mapping with Spring Data Neo4j 3 - Nicki Watt & Michael Hunger @...
Object Graph Mapping with Spring Data Neo4j 3 - Nicki Watt & Michael Hunger @...
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC
 

Mais de Arun Gupta

5 Skills To Force Multiply Technical Talents.pdf
5 Skills To Force Multiply Technical Talents.pdf5 Skills To Force Multiply Technical Talents.pdf
5 Skills To Force Multiply Technical Talents.pdfArun Gupta
 
Machine Learning using Kubernetes - AI Conclave 2019
Machine Learning using Kubernetes - AI Conclave 2019Machine Learning using Kubernetes - AI Conclave 2019
Machine Learning using Kubernetes - AI Conclave 2019Arun Gupta
 
Machine Learning using Kubeflow and Kubernetes
Machine Learning using Kubeflow and KubernetesMachine Learning using Kubeflow and Kubernetes
Machine Learning using Kubeflow and KubernetesArun Gupta
 
Secure and Fast microVM for Serverless Computing using Firecracker
Secure and Fast microVM for Serverless Computing using FirecrackerSecure and Fast microVM for Serverless Computing using Firecracker
Secure and Fast microVM for Serverless Computing using FirecrackerArun Gupta
 
Building Java in the Open - j.Day at OSCON 2019
Building Java in the Open - j.Day at OSCON 2019Building Java in the Open - j.Day at OSCON 2019
Building Java in the Open - j.Day at OSCON 2019Arun Gupta
 
Why Amazon Cares about Open Source
Why Amazon Cares about Open SourceWhy Amazon Cares about Open Source
Why Amazon Cares about Open SourceArun Gupta
 
Machine learning using Kubernetes
Machine learning using KubernetesMachine learning using Kubernetes
Machine learning using KubernetesArun Gupta
 
Building Cloud Native Applications
Building Cloud Native ApplicationsBuilding Cloud Native Applications
Building Cloud Native ApplicationsArun Gupta
 
Chaos Engineering with Kubernetes
Chaos Engineering with KubernetesChaos Engineering with Kubernetes
Chaos Engineering with KubernetesArun Gupta
 
How to be a mentor to bring more girls to STEAM
How to be a mentor to bring more girls to STEAMHow to be a mentor to bring more girls to STEAM
How to be a mentor to bring more girls to STEAMArun Gupta
 
Java in a World of Containers - DockerCon 2018
Java in a World of Containers - DockerCon 2018Java in a World of Containers - DockerCon 2018
Java in a World of Containers - DockerCon 2018Arun Gupta
 
The Serverless Tidal Wave - SwampUP 2018 Keynote
The Serverless Tidal Wave - SwampUP 2018 KeynoteThe Serverless Tidal Wave - SwampUP 2018 Keynote
The Serverless Tidal Wave - SwampUP 2018 KeynoteArun Gupta
 
Introduction to Amazon EKS - KubeCon 2018
Introduction to Amazon EKS - KubeCon 2018Introduction to Amazon EKS - KubeCon 2018
Introduction to Amazon EKS - KubeCon 2018Arun Gupta
 
Mastering Kubernetes on AWS - Tel Aviv Summit
Mastering Kubernetes on AWS - Tel Aviv SummitMastering Kubernetes on AWS - Tel Aviv Summit
Mastering Kubernetes on AWS - Tel Aviv SummitArun Gupta
 
Top 10 Technology Trends Changing Developer's Landscape
Top 10 Technology Trends Changing Developer's LandscapeTop 10 Technology Trends Changing Developer's Landscape
Top 10 Technology Trends Changing Developer's LandscapeArun Gupta
 
Container Landscape in 2017
Container Landscape in 2017Container Landscape in 2017
Container Landscape in 2017Arun Gupta
 
Java EE and NoSQL using JBoss EAP 7 and OpenShift
Java EE and NoSQL using JBoss EAP 7 and OpenShiftJava EE and NoSQL using JBoss EAP 7 and OpenShift
Java EE and NoSQL using JBoss EAP 7 and OpenShiftArun Gupta
 
Docker, Kubernetes, and Mesos recipes for Java developers
Docker, Kubernetes, and Mesos recipes for Java developersDocker, Kubernetes, and Mesos recipes for Java developers
Docker, Kubernetes, and Mesos recipes for Java developersArun Gupta
 
Thanks Managers!
Thanks Managers!Thanks Managers!
Thanks Managers!Arun Gupta
 
Migrate your traditional VM-based Clusters to Containers
Migrate your traditional VM-based Clusters to ContainersMigrate your traditional VM-based Clusters to Containers
Migrate your traditional VM-based Clusters to ContainersArun Gupta
 

Mais de Arun Gupta (20)

5 Skills To Force Multiply Technical Talents.pdf
5 Skills To Force Multiply Technical Talents.pdf5 Skills To Force Multiply Technical Talents.pdf
5 Skills To Force Multiply Technical Talents.pdf
 
Machine Learning using Kubernetes - AI Conclave 2019
Machine Learning using Kubernetes - AI Conclave 2019Machine Learning using Kubernetes - AI Conclave 2019
Machine Learning using Kubernetes - AI Conclave 2019
 
Machine Learning using Kubeflow and Kubernetes
Machine Learning using Kubeflow and KubernetesMachine Learning using Kubeflow and Kubernetes
Machine Learning using Kubeflow and Kubernetes
 
Secure and Fast microVM for Serverless Computing using Firecracker
Secure and Fast microVM for Serverless Computing using FirecrackerSecure and Fast microVM for Serverless Computing using Firecracker
Secure and Fast microVM for Serverless Computing using Firecracker
 
Building Java in the Open - j.Day at OSCON 2019
Building Java in the Open - j.Day at OSCON 2019Building Java in the Open - j.Day at OSCON 2019
Building Java in the Open - j.Day at OSCON 2019
 
Why Amazon Cares about Open Source
Why Amazon Cares about Open SourceWhy Amazon Cares about Open Source
Why Amazon Cares about Open Source
 
Machine learning using Kubernetes
Machine learning using KubernetesMachine learning using Kubernetes
Machine learning using Kubernetes
 
Building Cloud Native Applications
Building Cloud Native ApplicationsBuilding Cloud Native Applications
Building Cloud Native Applications
 
Chaos Engineering with Kubernetes
Chaos Engineering with KubernetesChaos Engineering with Kubernetes
Chaos Engineering with Kubernetes
 
How to be a mentor to bring more girls to STEAM
How to be a mentor to bring more girls to STEAMHow to be a mentor to bring more girls to STEAM
How to be a mentor to bring more girls to STEAM
 
Java in a World of Containers - DockerCon 2018
Java in a World of Containers - DockerCon 2018Java in a World of Containers - DockerCon 2018
Java in a World of Containers - DockerCon 2018
 
The Serverless Tidal Wave - SwampUP 2018 Keynote
The Serverless Tidal Wave - SwampUP 2018 KeynoteThe Serverless Tidal Wave - SwampUP 2018 Keynote
The Serverless Tidal Wave - SwampUP 2018 Keynote
 
Introduction to Amazon EKS - KubeCon 2018
Introduction to Amazon EKS - KubeCon 2018Introduction to Amazon EKS - KubeCon 2018
Introduction to Amazon EKS - KubeCon 2018
 
Mastering Kubernetes on AWS - Tel Aviv Summit
Mastering Kubernetes on AWS - Tel Aviv SummitMastering Kubernetes on AWS - Tel Aviv Summit
Mastering Kubernetes on AWS - Tel Aviv Summit
 
Top 10 Technology Trends Changing Developer's Landscape
Top 10 Technology Trends Changing Developer's LandscapeTop 10 Technology Trends Changing Developer's Landscape
Top 10 Technology Trends Changing Developer's Landscape
 
Container Landscape in 2017
Container Landscape in 2017Container Landscape in 2017
Container Landscape in 2017
 
Java EE and NoSQL using JBoss EAP 7 and OpenShift
Java EE and NoSQL using JBoss EAP 7 and OpenShiftJava EE and NoSQL using JBoss EAP 7 and OpenShift
Java EE and NoSQL using JBoss EAP 7 and OpenShift
 
Docker, Kubernetes, and Mesos recipes for Java developers
Docker, Kubernetes, and Mesos recipes for Java developersDocker, Kubernetes, and Mesos recipes for Java developers
Docker, Kubernetes, and Mesos recipes for Java developers
 
Thanks Managers!
Thanks Managers!Thanks Managers!
Thanks Managers!
 
Migrate your traditional VM-based Clusters to Containers
Migrate your traditional VM-based Clusters to ContainersMigrate your traditional VM-based Clusters to Containers
Migrate your traditional VM-based Clusters to Containers
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 

Último (20)

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 

S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

  • 1.
  • 2. <Insert Picture Here> Advanced Java API for RESTful Web Services Lee Chuk Munn chuk-munn.lee@oracle.com
  • 3. <Insert Picture Here> Objective Examine some “advance” features in JAX-RS
  • 4. Architectural Style • Music styles – baroque, romantic, rap, jazz, etc – There is no Jazz (music) note – How you put the notes that makes the style • Computing styles – client/server, object oriented, etc. – There is no client/server API • “... a coordinated set of architectural constraints that restricts the roles/features of architectural elements and the allowed relationships among those elements within any architecture that conforms to that style” - Dr. Roy Fielding
  • 5. What is REST? • REpresentation State Transfer – Architectural Styles and the Design of Network-based Software Architecture – Roy Fielding PhD thesis • Major components – Nouns (resources) are identified by URIs – A small subset of verbs to manipulate the nouns – State of the data – Representation is how you would like to view the state • Use verbs to exchange application states and representation • Hypermedia is the engine for application state transition
  • 6. REST Example • HTTP is one of the most RESTful protocol • Example: the web browser – The URL is the noun (resource) – GET (verb) the page from the server – State of the page is transferred from the server to the browser • Page maybe static or dynamic • State of page now exists on the client – Page may be represented as HTML, RSS, JSON, etc. – Click on a link in page (hypermedia) the process is repeated
  • 7. What is REST? Request GET /music/artists/magnum/recordings HTTP/1.1 Host: media.example.com Accept: application/xml Verb Response Noun HTTP/1.1 200 OK Date: Tue, 08 May 2007 16:41:58 GMT Server: Apache/1.3.6 Content-Type: application/xml; charset=UTF-8 State <?xml version="1.0"?> <recordings xmlns="…"> transfer <recording>…</recording> … Representation </recordings>
  • 8. JAX-RS in One Slide @Path(“/music”) @Produces(“application/xml”) public class Music { www.mymusic.com/music @GET //Returns List<Genre> public Response getGenreList() { ... } @GET @Path(“{genre}”) //Returns List<Song> public Response getSongs( @PathParam(“genre”) String genreId) { ... } www.mymusic.com/music/jazz }
  • 9. Selected Topics • Runtime resource resolution • Integration with EJB and CDI • Runtime content negotiation • Conditional HTTP request • Dealing with type erasure • Pluggable exception handling
  • 10. Terms • Root resource http://server/department/eng @Path(“department”) public class Department { • Sub resource method – Handles the request @GET @Path(“{id}”) public Department get( @PathParam(“id”) String deptId) { • Sub resource locator – Returns an object that will handle the request @Path(“{id}”) public Department get( @PathParam(“id”) String deptId) {
  • 11. Runtime Resource Resolution @Path(“department”) public class Department { @Path(“{id}”) public Object get( @PathParam(“id”) String id) { //Determine department type and return resource return (new ...); } public class Marketing extends Department { @GET @Path(“{type}”) public Response get( @PathParam(“type”) String deptType) { ... }
  • 12. Runtime Resource Resolution @Path(“department”) public class Department { @Path(“{id}”) public Object get( @PathParam(“id”) String id) { ... } GET /department/marketing/tele public class Marketing extends Department { @GET @Path(“{type}”) public Response get( @PathParam(“type”) String deptType) { ... }
  • 13. Demo
  • 14. More Resource Resolution • Sub resource locators determines what type of resource to return dynamically – Eg. Use JPA to query data and return that as a resource – Can be used with CDI or EJBs – All parameters must be annotated @Path(“department”) public class Department { @Path(“{id}”) public Object get(@PathParam(“id”) String id) { EntityManager em = ... //Get an instance Department dept = em.find(Department.class, id); return (dept); }
  • 15. Resource Methods and Locators • Easy to get confuse with sub-resource locator and sub-resource methods • Both are annotated with @Path • Sub-resource methods has resource method designators – Eg. @GET • Sub-resource locator do not have method designators
  • 16. Integration with EJB • Annotate @Path to convert into a root resource – Stateless session bean – Singleton bean @Path("stateless-bean") @Stateless public class StatelessResource { ... } @Path("singleton-bean") @Singleton public class SingletonResource { ... }
  • 17. CDI One Pager @Stateless public class ShoppingService { @Inject private Cart myCart; public void addToCart(Item someItem) { myCart.add(someItem); } … } public interface Cart { public void add(Item item); } @ConversationScoped public class DefaultShoppingCart implements Cart { @PersistenceContext private EntityManager em; public void add(Item item) { … } }
  • 18. Using CDI with Root Resources • Perfect world – use CDI to manage REST resources – CDI providing lifecycle management, dependency, etc • Not very well specified • See http://www.mentby.com/paul-sandoz/jax-rs-on- glassfish-31-ejb-injection.html
  • 19. JAX-RS/CDI Component Models • Root resources are managed in the request scope – Default • CDI requires “normal” scoped beans to be proxyable – Annotated with @RequestScoped or @ApplicationScoped – Unproxyable beans • No non-private constructor with no argument • Final class • Root resources needs to be annotated with CDI scoped to be managed by CDI
  • 20. Using CDI with JAX-RS • Request scoped, JAX-RS managed @Path(“customer/{id}”) public class Customer { public Customer(@PathParam(“id”) String id) { • Application scoped, CDI managed, will fail @Path(“customer/{id}”) @ApplicationScoped public class Customer { @Inject public Customer(@PathParam(“id”) String id) { • Application scoped, provide a no-args constructor – Use resource method to get id @Path(“customer/{id}”) @ApplicationScoped public class Customer { public Customer() { }
  • 21. Demo
  • 22. Representation Request GET /music/artists/magnum/recordings HTTP/1.1 Host: media.example.com Accept: application/xml Format Response HTTP/1.1 200 OK Date: Tue, 08 May 2007 16:41:58 GMT Server: Apache/1.3.6 Content-Type: application/xml; charset=UTF-8 <?xml version="1.0"?> <recordings xmlns="…"> <recording>…</recording> … </recordings>
  • 23. Supported Media Types • Out-of-the-box support for – */* - byte[], InputStream, DataSource – text/* - String – text/xml, application/xml, application/*+xml – JAXBElement – application/x-www-form-urlencoded – MultivalueMap • Use @Produces or @Consumes to match with HTTP headers – Accept, Content-Type
  • 24. Runtime Content Negotiation • Static content/media type negotiation of representation supported with @Produces • Runtime content negotiation of representation supports 4 dimensions – Media type, character set, language, encoding • Each representation has a Variant which is a point in the 4 dimension space List<Variant> variant = Variant .mediaType(MediaType.APPLICATION.JSON , MediaType.APPLICATION.XML) .languages(Locale.ENGLISH, Locale.CHINESE); assert variant.size() == 4
  • 25. Select Most Acceptable Variant @GET public Response get(@Context Request r) { List<Variant> vs = ... Variant v = r.selectVariant(vs); if (v == null) return (Response.notAcceptable(vs).build()); else { Object rep = selectRepresentation(v); return (Response.ok(rep, v)); } } • Selection will compare the list of variants with the correspond acceptable values in the client request – Accept, Accept-Langauge, Accept-Encoding, Accept- Charset
  • 26. Conditional HTTP Request • Save bandwidth and client processing – A GET can return a 304 (not modified) if representation has not changed since previous request • Avoid the lost update problem – A PUT can return 412 (precondition failed) if the resource state has been modified since previous request • A date and/or entity tag can be used – Last-Modified and Etag headers – HTTP dates have granularity of 1 second – Etags are better for use with PUT
  • 27. Processng Etags @GET public Response get(@Context Request r) { EntityTag et = ... //Calculate etag Response.ResponseBuilder rb = r.evaluatePreconditions(et); if (rb != null) { // Return 304 (Not Modified) return rb.build(); } String rep = ... return Response.ok(rep).tag(et).build(); }
  • 28. Dealing with Type Erasure – 1 • Resources can return an entity @GET List<Customer> getCustomers() { ... • Type information is lost when returning Response @GET Response getCustomers() { List<Customer> list = ... return (Response.ok(list).build()); • MessageBodyWriter support for List<Customer> will not work when type information is lost – Converts Java object to stream
  • 29. Dealing with Type Erasure – 2 • Use GenericEntity to preserve type information at runtime @GET Response getCustomers() { List<Customer> list = ... GenericEntity<List<Customer>> ge = new GenericEntity<List<Customer>>(list){}; return (Response.ok(list).build());
  • 30.
  • 31. Pluggable Exception Handling • Propagation on unmapped exceptions to web container – A runtime exception thrown by the JAX-RS container or application is propagated as is – A checked exception is thrown by the application is propagated as the cause of a ServletException – Propagated exceptions can be mapped to error pages • Runtime/checked exceptions can be “caught” and mapped to Response using ExceptionMapper
  • 32. Exception Classes Class A extends RuntimeException { … } Class B extends A { … } Class C extends B { … }
  • 33. Exception Mapper @Provider public class AMapper implements ExceptionMapper<A> { public Response toResponse(A a) { … } } @Provider public class BMapper implements ExceptionMapper<B> { public Response toResponse(B b) { … } }
  • 34. Throwing Exceptions // throwing A maps to Response of AMapper @GET public String a() throws A { ... } // throwing B maps to Response of BMapper @GET public String b() throws B { ... } // throwing C maps to Response of BMapper @GET public String c() throws C { ... }
  • 35. ExceptionMapper • ExceptionMapper “closest” to exception class is selected to map exception • Can map Throwable @Provider public class CatchAll implements ExceptionMapper<Throwable> { public Response toResponse(Throwable t) { // Internal Server Error return Response.status(500).build(); } } • Inject @Provider to delegate – Map the cause of the exception
  • 36. We encourage you to use the newly minted corporate tagline “Software. Hardware. Complete.” at the end of all your presentations. This message should replace any reference to our previous corporate tagline “Oracle Is the Information Company.”
  • 37. For More Information search.oracle.com or oracle.com
  • 38. Alternate Title with Subhead Arial Size 18 (Gray) • First-level bullet – Second-level bullet • Third-level bullet – Fourth-level bullet • Fifth-level bullet