SlideShare a Scribd company logo
JAX-RS 2.0: RESTful Java on Steroids
Arun Gupta, Java EE & GlassFish Guy
http://blogs.oracle.com/arungupta, @arungupta
 1   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
The following is intended to outline our general product direction. It is
                    intended for information purposes only, and may not be incorporated into
                    any contract. It is not a commitment to deliver any material, code, or
                    functionality, and should not be relied upon in making purchasing
                    decisions. The development, release, and timing of any features or
                    functionality described for Oracle s products remains at the sole discretion
                    of Oracle.




2   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Part I: How we got here ?




3   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
How We Got Here?

    •  Shortest intro to JAX-RS 1.0
    •  Requested features for JAX-RS 2.0
    •  JSR 339: JAX-RS 2.0




4   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
JAX-RS Origins

    •  JAX-RS 1.0 is Java API for RESTful WS
    •  RESTFul Principles:
       –  Assign everything an ID
       –  Link things together
       –  Use common set of methods
       –  Allow multiple representations
       –  Stateless communications



5   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
JAX-RS 1.0 Goals

    •  POJO-Based API
    •  HTTP Centric
    •  Format Independence
    •  Container Independence
    •  Inclusion in Java EE




6   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Example: JAX-RS API
                                                                                     Resources


@Path("/atm/{cardId}")	                                    URI Parameter
public class AtmService {	                                   Injection
	
    @GET @Path("/balance")	
    @Produces("text/plain")	
    public String balance(@PathParam("cardId") String card,	
                           @QueryParam("pin") String pin) {	
        return Double.toString(getBalance(card, pin));	
    }	
	
    …	
	
 HTTP Method                                                                  Built-in
   Binding                                                                  Serialization



 7   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Example: JAX-RS API (contd.)
                …	                                                         Custom Serialization
	
            @POST @Path("/withdrawal")	
            @Consumes("text/plain") 	
            @Produces("application/json")	
            public Money withdraw(@PathParam("card") String card,	
                                  @QueryParam("pin") String pin, 	
                                  String amount){	
                return getMoney(card, pin, amount);	
            }	
}	




8   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Requested Features

                                                                           Filters/Handlers
                                       Client API

                                                                                              Hypermedia
                            Async                                          JSR 330

                                                                                               Validation
                                    Improved
                                     Conneg                                    MVC

9   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
JSR 339 Expert Group

     •  EG Formed in March 2011
     •  Oracle Leads: Marek Potociar / Santiago Pericas-G.
     •  Expert Group:
         –  Jan Algermissen, Florent Benoit, Sergey Beryozkin (Talend),
            Adam Bien, Bill Burke (RedHat), Clinton Combs, Bill De Hora,
            Markus Karg, Sastry Malladi (Ebay), Julian Reschke, Guilherme
            Silveira, Dionysios Synodinos
     •  Early Draft 2 published on Feb 9, 2012!


10   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Part II: Where We Are Going




11   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
New in JAX-RS 2.0
                                                                                              ✔
                                                                            ✔   Filters/Handlers
                                        Client API
                                                                                                                 ✔
                                                                                                   Hypermedia
                                                                      ✔                   ✔
                             Async                                              JSR 330
                                                                                                                 ✔
                                                                                                    Validation
                                     Improved
                                                                            ✔
                                                                                              ✗
                                      Conneg                                        MVC

12   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
New in JAX-RS 2.0
                                                                            ✔     Interceptors
                                        Client API                                  /Handlers

                                                                                                 Hypermedia
                             Async                                              JSR 330

                                                                                                  Validation
                                     Improved
                                      Conneg

13   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Motivation

     •  HTTP client libraries too low level
     •  Sharing features with JAX-RS server API
        •  E.g., MBRs and MBWs

     •  Supported by some JAX-RS 1.0 implementations
        •  Need for a standard




14   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Client API

                                                                                                  Resource Target
Client Factory                                                      Client
                                                                                                  “atm”



                                                                    Configuration                 Resource Target
                                                                   Configuration
                                                                  Configuration                   “{cardId}”


                                                                                      Resource Target           Resource Target
Invocation                                                          Request Builder
                                                                                      “balance”                 “withdrawal”



                              Response

  15   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Example: Client API

// Get instance of Client	
Client client = ClientFactory.newClient();	
	
Can also inject @URI for the target ß	
	
// Get account balance	
String bal = client.target("http://.../atm/balance")	
    .pathParam("card", "111122223333")	
    .queryParam("pin", "9876") 	
    .request("text/plain").get(String.class);	
	

16   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Example: Client API (contd.)

// Withdraw some money	
Money mon = client.target("http://.../atm/withdraw")	
    .pathParam("card", "111122223333")	
    .queryParam("pin", "9876")	
    .request("application/json")	
    .post(text("50.0"), Money.class);	




17   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Example: Generic Interface (Command pattern,
     Batch processing)
Invocation inv1 = 	
    client.target("http://.../atm/balance")…	
    .request(“text/plain”).buildGet();	
	
Invocation inv2 = 	
    client.target("http://.../atm/withdraw")…	
    .request("application/json")	
    .buildPost(text("50.0"));	
	



18   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Example: Generic Interface (contd.)
	
Collection<Invocation> invs = 	
  Arrays.asList(inv1, inv2);	
	
Collection<Response> ress = 	
  Collections.transform(invs, 	
    new F<Invocation, Response>() {	
      public Response apply(Invocation inv) {	
         return inv.invoke(); 	
      }	
    });	


19   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Example: Configuration
// Get client and register MyProvider1	
Client client = ClientFactory.newClient();	
client.configuration().register(MyProvider1.class);	
	
// Create atm and register MyProvider2	
// Inherits MyProvider1 from client	
Target atm = client.target("http://.../atm");	
atm.configuration().register(MyProvider2.class);	
	
// Create balance and register MyProvider3	
// Inherits MyProvider1, MyProvider2 from atm	
Target balance = atm.path("balance");    // new instance	
balance.configuration().register(MyProvider3.class);	
	
	
20   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
New in JAX-RS 2.0
                                                                                                 ✔
                                                                            ✔     Interceptors
                                        Client API                                  /Handlers

                                                                                                 Hypermedia
                             Async                                              JSR 330

                                                                                                     Validation
                                     Improved
                                      Conneg

21   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Motivation

     •  Customize JAX-RS implementations via well-defined
        extension points
     •  Use Cases: Logging, Compression, Security, Etc.
     •  Shared by client and server APIs
     •  Supported by most JAX-RS 1.0 implementations
           •  All using slightly different types or semantics




22   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Filters

     •  Non-wrapping extension points
        •  Pre: Interface RequestFilter	
        •  Post: Interface ResponseFilter	

     •  Part of a filter chain
     •  Do not call the next filter directly
     •  Each filter decides to proceed or break chain
        •  By returning FilterAction.NEXT or FilterAction.STOP	



23   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Filter Example: LoggingFilter
@Provider	
class LoggingFilter 	
    implements RequestFilter, ResponseFilter {	
	
    @Override	
    public FilterAction preFilter(FilterContext ctx) 	
       throws IOException {	
         logRequest(ctx.getRequest());	
         return FilterAction.NEXT;	
    }	
	
    …	
	
    24   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Filter Example: LoggingFilter (contd.)

	
          @Override	
           public FilterAction postFilter(FilterContext ctx) 	
             throws IOException {	
               logResponse(ctx.getResponse());	
               return FilterAction.NEXT;	
           } 	
	
    }	



     25   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Interceptors

     •  Wrapping extension points
        •  ReadFrom: Interface ReaderInterceptor	
        •  WriteTo: Interface WriterInterceptor	

     •  Part of a interceptor chain
     •  Call the next handler directly
     •  Each handler decides to proceed or break chain
        •  By calling ctx.proceed()	



26   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Handler Example: GzipInterceptor
@Provider	
class GzipInterceptor implements ReaderInterceptor,
WriterInterceptor {	
	
     @Override	
     public Object aroundreadFrom(ReadInterceptorContext ctx) 	
         throws IOException {	
         if (gzipEncoded(ctx)) {	
             InputStream old = ctx.getInputStream();	
             ctx.setInputStream(new GZIPInputStream(old));	
         }	
         return ctx.proceed();	
     } 	
… }	
	 27   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Order of execution

          Request                                             WriteTo       Request            ReadFrom
           Filter                                             Handler        Filter             Handler




       ReadFrom                                            Response         WriteTo            Response
        Handler                                              Filter         Handler              Filter

                                        Client                                        Server




28   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Binding

     •  Associating filters and handlers with resource methods
     •  Same mechanism for filters and handlers

                                                                            Name Binding     Global Binding


                                                                            @NameBinding/
                                     Static                                                    DEFAULT
                                                                             @Qualifier?

                                                                            DynamicBinding   DynamicBinding
                                Dynamic
                                                                               interface        Interface


29   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Binding Example: LoggingFilter
     @NameBinding 	 	// or @Qualifier ?	
     @Target({ElementType.TYPE, ElementType.METHOD})	
     @Retention(value = RetentionPolicy.RUNTIME)	
     public @interface Logged {	
     }	
     	
     @Provider	
     @Logged	
     public class LoggingFilter implements RequestFilter, 	
         ResponseFilter 	
     { … }	
     	



30   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Binding Example: LoggingFilter
     @Path("/")	
     public class MyResourceClass {	
     	
         @Logged	
         @GET	
         @Produces("text/plain")	
         @Path("{name}")	
         public String hello(@PathParam("name") String name) {	
             return "Hello " + name;	
         }	
     }	
     	


31   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
New in JAX-RS 2.0
                                                                                              ✔
                                                                            ✔   Filters/Handlers
                                        Client API

                                                                                                   Hypermedia
                                                                                          ✔
                             Async                                              JSR 330
                                                                                                                 ✔
                                                                                                    Validation
                                     Improved
                                      Conneg

32   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Motivation

     •  Services must validate data
     •  Bean Validation already provides the mechanism
        •  Integration into JAX-RS

     •  Support for constraint annotations in:
        •  Fields and properties
        •  Parameters (including request entity)
        •  Methods (response entities)
        •  Resource classes


33   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Example: Constraint Annotations
   @Path("/")	
   class MyResourceClass {	
   	
         @POST	
         @Consumes(MediaType.APPLICATION_FORM_URLENCODED)	
Built-in public void registerUser(	
               @NotNull @FormParam("firstName") String fn,	
Custom
               @NotNull @FormParam("lastName") String ln,	
               @Email @FormParam("email") String em) {	
               ... } 	
   }	
      	


 34   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Example: User defined Constraints
     @Target({ METHOD, FIELD, PARAMETER })	
     @Retention(RUNTIME)	
     @Constraint(validatedBy = EmailValidator.class)	
     public @interface Email { ... }	
     	
     class EmailValidator 	
       implements ConstraintValidator<Email, String> {	
         public void initialize(Email email) {	
             … }	
         public boolean isValid(String value,     	
             ConstraintValidatorContext context) {	
             // Check 'value' is e-mail address 	
             … } }	

35   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Example: Request Entity Validation
@CheckUser1	
class User { ... }	
	
@Path("/")	
class MyResourceClass {	
    @POST	
    @Consumes("application/xml")	
    public void registerUser1(@Valid User u) { … } 	
	
    @POST	
    @Consumes("application/json")	
    public void registerUser12(@CheckUser2 @Valid User u)
{ … } 	
}	
 36   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
New in JAX-RS 2.0
                                                                                               ✔
                                                                            ✔   Filters/Handlers
                                        Client API

                                                                                                   Hypermedia
                                                                      ✔                   ✔
                             Async                                              JSR 330
                                                                                                                 ✔
                                                                                                    Validation
                                     Improved
                                      Conneg

37   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Motivation

     •  Let “borrowed” threads run free!
        •  Container environment

     •  Suspend and resume connections
        •  Suspend while waiting for an event
        •  Resume when event arrives

     •  Leverage Servlet 3.X async support (if available)
     •  Client API support
        •  Future<RESPONSE>, InvocationCallback<RESPONSE>


38   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Example: Suspend and Resume
 @Path("/async/longRunning")	
 public class MyResource {    	
   @Context private ExecutionContext ctx;	
 	
   @GET @Produces("text/plain")	
   public void longRunningOp() {	
     Executors.newSingleThreadExecutor().submit(	
       new Runnable() {	
           public void run() { 	
               Thread.sleep(10000);     // Sleep 10 secs	
               ctx.resume("Hello async world!"); 	
           } });	
     ctx.suspend(); 	 	// Suspend connection and return	
   } … }   	
39   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Example: @Suspend Annotation
     @Path("/async/longRunning")	
     public class MyResource {    	
       @Context private ExecutionContext ctx;	
     	
       @GET @Produces("text/plain") @Suspend	
       public void longRunning() {	
         Executors.newSingleThreadExecutor().submit(	
           new Runnable() {	
               public void run() { 	
                   Thread.sleep(10000);     // Sleep 10 secs	
                   ctx.resume("Hello async world!"); 	
               } });	
         // ctx.suspend(); Suspend connection and return	
       } … }   	
40   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Example: Client API Async Support
 // Build target URI	
 Target target = client.target("http://.../atm/balance")…	
     	
 // Start async call and register callback	
 Future<?> handle = target.request().async().get(	
     new InvocationCallback<String>() {	
         public void complete(String balance) { … }	
         public void failed(InvocationException e) { … }	
       });	
   	
 // After waiting for a while …	
 If (!handle.isDone()) handle.cancel(true);	
 	

41   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
New in JAX-RS 2.0
                                                                                              ✔
                                                                            ✔   Filters/Handlers
                                        Client API
                                                                                                                 ✔
                                                                                                   Hypermedia
                                                                       ✔                  ✔
                             Async                                              JSR 330
                                                                                                                 ✔
                                                                                                    Validation
                                     Improved
                                      Conneg

42   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Motivation

     •  REST principles
        •  Identifiers and Links
        •  HATEOAS (Hypermedia As The Engine Of App State)

     •  Link types:
        •  Structural Links
        •  Transitional Links




43   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Example: Structural vs. Transitional Links
     Link: <http://.../orders/1/ship>; rel=ship,	
            <http://.../orders/1/cancel>; rel=cancel	   Transitional
     ...	
     <order id="1">	
       <customer>http://.../customers/11</customer>	
       <address>http://.../customers/11/address/1</customer>	
       <items>	
          <item>	                                         Structural

            <product>http://.../products/111</products>	
            <quantity>2</quantity>	
       </item>	
       ... </order>    	


44   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Current Proposal
     Transitional Links Only
     •  Link and LinkBuilder classes
        •  RFC 5988: Web Linking

     •  Support for Link in ResponseBuilder	
     •  Create Target from Link in Client API




45   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Example: Using Transitional Links
// Server API	
Response res = Response.ok(order)	
      .link("http://.../orders/1/ship", "ship")	
      .build();	
      	
// Client API	
Response order = client.target(…)	
      .request("application/xml").get();	
	
if (order.getLink(“ship”) != null) {          	
      Response shippedOrder = client	
          .target(order.getLink("ship"))	
          .request("application/xml").post(null);	
    … }	
  	
 46   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
New in JAX-RS 2.0
                                                                                              ✔
                                                                            ✔   Filters/Handlers
                                        Client API
                                                                                                                 ✔
                                                                                                   Hypermedia
                                                                       ✔                  ✔
                             Async                                              JSR 330
                                                                                                                 ✔
                                                                                                    Validation
                                                                            ✔
                                     Improved
                                      Conneg

47   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Improved Conneg

        GET http://.../widgets2	
        Accept: text/*; q=1	
        …	
        	
        Path("widgets2")	
        public class WidgetsResource2 {	
           @GET	
           @Produces("text/plain", 	
                     "text/html")	
           public Widgets getWidget() {...}	
        }	

48   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Improved Conneg (contd.)

        GET http://.../widgets2	
        Accept: text/*; q=1	
        …	
        	
        Path("widgets2")	
        public class WidgetsResource2 {	
           @GET	
           @Produces("text/plain;qs=0.5",	
                     "text/html;qs=0.75")	
           public Widgets getWidget() {...}	
        }	

49   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Other Topics Under Consideration

     •  Better integration with JSR 330
        •  Support @Inject and qualifiers

     •  High-level client API?




50   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
More Information

     •  JSR: http://jcp.org/en/jsr/detail?id=339
     •  Java.net: http://java.net/projects/jax-rs-spec
     •  User Alias: users@jax-rs-spec.java.net
        •  All EG discussions forwarded to this list




51   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Q&A


52   Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

More Related Content

PDF
The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012
PDF
Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012
PDF
Running your Java EE 6 applications in the Cloud
PDF
GlassFish & Java EE Business Update @ CEJUG
PDF
GlassFish REST Administration Backend at JavaOne India 2012
PDF
Websocket 1.0
PDF
GlassFish REST Administration Backend
PDF
Java EE 7: Developing for the Cloud at Geecon, JEEConf, Johannesburg
The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012
Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012
Running your Java EE 6 applications in the Cloud
GlassFish & Java EE Business Update @ CEJUG
GlassFish REST Administration Backend at JavaOne India 2012
Websocket 1.0
GlassFish REST Administration Backend
Java EE 7: Developing for the Cloud at Geecon, JEEConf, Johannesburg

What's hot (20)

PDF
JAX-RS 2.0: RESTful Web services on steroids at Geecon 2012
PDF
PaaSing a Java EE 6 Application at Geecon 2012
PDF
5050 dev nation
PDF
The State of Java under Oracle at JCertif 2011
PDF
Java EE 7: Developing for the Cloud at Java Day, Istanbul, May 2012
PDF
OSGi & Java EE in GlassFish @ Silicon Valley Code Camp 2010
PDF
Powering the Next Generation Services with Java Platform - Spark IT 2010
PDF
Java EE 7 and HTML5: Developing for the Cloud
PDF
The Java EE 7 Platform: Productivity++ & Embracing HTML5
PDF
Running your Java EE 6 applications in the Cloud @ Silicon Valley Code Camp 2010
PDF
Getting Started with Rails on GlassFish (Hands-on Lab) - Spark IT 2010
PDF
GIDS 2012: PaaSing a Java EE Application
PDF
TDC 2011: The Java EE 7 Platform: Developing for the Cloud
PDF
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...
PDF
GIDS 2012: Java Message Service 2.0
PDF
Java EE 6 and GlassFish v3: Paving the path for future
PDF
OSGi-enabled Java EE Applications using GlassFish at JCertif 2011
PDF
JAX-RS 2.0: What’s New in JSR 339 ?
PDF
Running your Java EE applications in the Cloud
PDF
The Java EE 7 Platform: Productivity &amp; HTML5 at San Francisco JUG
JAX-RS 2.0: RESTful Web services on steroids at Geecon 2012
PaaSing a Java EE 6 Application at Geecon 2012
5050 dev nation
The State of Java under Oracle at JCertif 2011
Java EE 7: Developing for the Cloud at Java Day, Istanbul, May 2012
OSGi & Java EE in GlassFish @ Silicon Valley Code Camp 2010
Powering the Next Generation Services with Java Platform - Spark IT 2010
Java EE 7 and HTML5: Developing for the Cloud
The Java EE 7 Platform: Productivity++ & Embracing HTML5
Running your Java EE 6 applications in the Cloud @ Silicon Valley Code Camp 2010
Getting Started with Rails on GlassFish (Hands-on Lab) - Spark IT 2010
GIDS 2012: PaaSing a Java EE Application
TDC 2011: The Java EE 7 Platform: Developing for the Cloud
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...
GIDS 2012: Java Message Service 2.0
Java EE 6 and GlassFish v3: Paving the path for future
OSGi-enabled Java EE Applications using GlassFish at JCertif 2011
JAX-RS 2.0: What’s New in JSR 339 ?
Running your Java EE applications in the Cloud
The Java EE 7 Platform: Productivity &amp; HTML5 at San Francisco JUG
Ad

Similar to Java Summit Chennai: JAX-RS 2.0 (20)

PPTX
JAX-RS 2.0: RESTful Java on Steroids, by Aron Gupta
PPTX
JAX-RS 2.0: RESTful Web services on steroids
PDF
Hadoop Summit San Diego Feb2013
PDF
JAX-RS 2.0: RESTful Web Services
PPTX
apiGrove
PDF
Implementing Web Commerce In A Complex Environment
PDF
Expendables E-AppStore
PDF
Using Istio to Secure & Monitor Your Services
PDF
2009 Q2 WSO2 Technical Update
PPTX
Coherence RoadMap 2018
PPT
Have You Seen Java EE Lately?
PDF
JAX-RS 2.0: New and Noteworthy in RESTful Web services API at JAX London
PDF
21st Century SOA
PDF
Streaming Solutions for Real time problems
PDF
Application Services On The Web Sales Forcecom
PDF
2. FOMS _ FeedHenry_ Mícheál Ó Foghlú
PDF
Java EE, What's Next? by Anil Gaur
PDF
MySQL day Dublin - OCI & Application Development
PDF
21st Century Service Oriented Architecture
PPTX
How to Use Stormpath in angular js
JAX-RS 2.0: RESTful Java on Steroids, by Aron Gupta
JAX-RS 2.0: RESTful Web services on steroids
Hadoop Summit San Diego Feb2013
JAX-RS 2.0: RESTful Web Services
apiGrove
Implementing Web Commerce In A Complex Environment
Expendables E-AppStore
Using Istio to Secure & Monitor Your Services
2009 Q2 WSO2 Technical Update
Coherence RoadMap 2018
Have You Seen Java EE Lately?
JAX-RS 2.0: New and Noteworthy in RESTful Web services API at JAX London
21st Century SOA
Streaming Solutions for Real time problems
Application Services On The Web Sales Forcecom
2. FOMS _ FeedHenry_ Mícheál Ó Foghlú
Java EE, What's Next? by Anil Gaur
MySQL day Dublin - OCI & Application Development
21st Century Service Oriented Architecture
How to Use Stormpath in angular js
Ad

More from Arun Gupta (20)

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

Recently uploaded (20)

PDF
WOOl fibre morphology and structure.pdf for textiles
PDF
Encapsulation theory and applications.pdf
PDF
Hybrid model detection and classification of lung cancer
PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
Web App vs Mobile App What Should You Build First.pdf
PDF
project resource management chapter-09.pdf
PDF
Zenith AI: Advanced Artificial Intelligence
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
A novel scalable deep ensemble learning framework for big data classification...
PDF
Approach and Philosophy of On baking technology
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PPTX
A Presentation on Touch Screen Technology
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
OMC Textile Division Presentation 2021.pptx
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
WOOl fibre morphology and structure.pdf for textiles
Encapsulation theory and applications.pdf
Hybrid model detection and classification of lung cancer
DP Operators-handbook-extract for the Mautical Institute
Web App vs Mobile App What Should You Build First.pdf
project resource management chapter-09.pdf
Zenith AI: Advanced Artificial Intelligence
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
A novel scalable deep ensemble learning framework for big data classification...
Approach and Philosophy of On baking technology
Group 1 Presentation -Planning and Decision Making .pptx
A Presentation on Touch Screen Technology
Univ-Connecticut-ChatGPT-Presentaion.pdf
Encapsulation_ Review paper, used for researhc scholars
OMC Textile Division Presentation 2021.pptx
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...

Java Summit Chennai: JAX-RS 2.0

  • 1. JAX-RS 2.0: RESTful Java on Steroids Arun Gupta, Java EE & GlassFish Guy http://blogs.oracle.com/arungupta, @arungupta 1 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 2. The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle s products remains at the sole discretion of Oracle. 2 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 3. Part I: How we got here ? 3 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 4. How We Got Here? •  Shortest intro to JAX-RS 1.0 •  Requested features for JAX-RS 2.0 •  JSR 339: JAX-RS 2.0 4 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 5. JAX-RS Origins •  JAX-RS 1.0 is Java API for RESTful WS •  RESTFul Principles: –  Assign everything an ID –  Link things together –  Use common set of methods –  Allow multiple representations –  Stateless communications 5 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 6. JAX-RS 1.0 Goals •  POJO-Based API •  HTTP Centric •  Format Independence •  Container Independence •  Inclusion in Java EE 6 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 7. Example: JAX-RS API Resources @Path("/atm/{cardId}") URI Parameter public class AtmService { Injection @GET @Path("/balance") @Produces("text/plain") public String balance(@PathParam("cardId") String card, @QueryParam("pin") String pin) { return Double.toString(getBalance(card, pin)); } … HTTP Method Built-in Binding Serialization 7 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 8. Example: JAX-RS API (contd.) … Custom Serialization @POST @Path("/withdrawal") @Consumes("text/plain") @Produces("application/json") public Money withdraw(@PathParam("card") String card, @QueryParam("pin") String pin, String amount){ return getMoney(card, pin, amount); } } 8 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 9. Requested Features Filters/Handlers Client API Hypermedia Async JSR 330 Validation Improved Conneg MVC 9 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 10. JSR 339 Expert Group •  EG Formed in March 2011 •  Oracle Leads: Marek Potociar / Santiago Pericas-G. •  Expert Group: –  Jan Algermissen, Florent Benoit, Sergey Beryozkin (Talend), Adam Bien, Bill Burke (RedHat), Clinton Combs, Bill De Hora, Markus Karg, Sastry Malladi (Ebay), Julian Reschke, Guilherme Silveira, Dionysios Synodinos •  Early Draft 2 published on Feb 9, 2012! 10 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 11. Part II: Where We Are Going 11 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 12. New in JAX-RS 2.0 ✔ ✔ Filters/Handlers Client API ✔ Hypermedia ✔ ✔ Async JSR 330 ✔ Validation Improved ✔ ✗ Conneg MVC 12 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 13. New in JAX-RS 2.0 ✔ Interceptors Client API /Handlers Hypermedia Async JSR 330 Validation Improved Conneg 13 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 14. Motivation •  HTTP client libraries too low level •  Sharing features with JAX-RS server API •  E.g., MBRs and MBWs •  Supported by some JAX-RS 1.0 implementations •  Need for a standard 14 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 15. Client API Resource Target Client Factory Client “atm” Configuration Resource Target Configuration Configuration “{cardId}” Resource Target Resource Target Invocation Request Builder “balance” “withdrawal” Response 15 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 16. Example: Client API // Get instance of Client Client client = ClientFactory.newClient(); Can also inject @URI for the target ß // Get account balance String bal = client.target("http://.../atm/balance") .pathParam("card", "111122223333") .queryParam("pin", "9876") .request("text/plain").get(String.class); 16 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 17. Example: Client API (contd.) // Withdraw some money Money mon = client.target("http://.../atm/withdraw") .pathParam("card", "111122223333") .queryParam("pin", "9876") .request("application/json") .post(text("50.0"), Money.class); 17 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 18. Example: Generic Interface (Command pattern, Batch processing) Invocation inv1 = client.target("http://.../atm/balance")… .request(“text/plain”).buildGet(); Invocation inv2 = client.target("http://.../atm/withdraw")… .request("application/json") .buildPost(text("50.0")); 18 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 19. Example: Generic Interface (contd.) Collection<Invocation> invs = Arrays.asList(inv1, inv2); Collection<Response> ress = Collections.transform(invs, new F<Invocation, Response>() { public Response apply(Invocation inv) { return inv.invoke(); } }); 19 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 20. Example: Configuration // Get client and register MyProvider1 Client client = ClientFactory.newClient(); client.configuration().register(MyProvider1.class); // Create atm and register MyProvider2 // Inherits MyProvider1 from client Target atm = client.target("http://.../atm"); atm.configuration().register(MyProvider2.class); // Create balance and register MyProvider3 // Inherits MyProvider1, MyProvider2 from atm Target balance = atm.path("balance"); // new instance balance.configuration().register(MyProvider3.class); 20 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 21. New in JAX-RS 2.0 ✔ ✔ Interceptors Client API /Handlers Hypermedia Async JSR 330 Validation Improved Conneg 21 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 22. Motivation •  Customize JAX-RS implementations via well-defined extension points •  Use Cases: Logging, Compression, Security, Etc. •  Shared by client and server APIs •  Supported by most JAX-RS 1.0 implementations •  All using slightly different types or semantics 22 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 23. Filters •  Non-wrapping extension points •  Pre: Interface RequestFilter •  Post: Interface ResponseFilter •  Part of a filter chain •  Do not call the next filter directly •  Each filter decides to proceed or break chain •  By returning FilterAction.NEXT or FilterAction.STOP 23 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 24. Filter Example: LoggingFilter @Provider class LoggingFilter implements RequestFilter, ResponseFilter { @Override public FilterAction preFilter(FilterContext ctx) throws IOException { logRequest(ctx.getRequest()); return FilterAction.NEXT; } … 24 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 25. Filter Example: LoggingFilter (contd.) @Override public FilterAction postFilter(FilterContext ctx) throws IOException { logResponse(ctx.getResponse()); return FilterAction.NEXT; } } 25 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 26. Interceptors •  Wrapping extension points •  ReadFrom: Interface ReaderInterceptor •  WriteTo: Interface WriterInterceptor •  Part of a interceptor chain •  Call the next handler directly •  Each handler decides to proceed or break chain •  By calling ctx.proceed() 26 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 27. Handler Example: GzipInterceptor @Provider class GzipInterceptor implements ReaderInterceptor, WriterInterceptor { @Override public Object aroundreadFrom(ReadInterceptorContext ctx) throws IOException { if (gzipEncoded(ctx)) { InputStream old = ctx.getInputStream(); ctx.setInputStream(new GZIPInputStream(old)); } return ctx.proceed(); } … } 27 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 28. Order of execution Request WriteTo Request ReadFrom Filter Handler Filter Handler ReadFrom Response WriteTo Response Handler Filter Handler Filter Client Server 28 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 29. Binding •  Associating filters and handlers with resource methods •  Same mechanism for filters and handlers Name Binding Global Binding @NameBinding/ Static DEFAULT @Qualifier? DynamicBinding DynamicBinding Dynamic interface Interface 29 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 30. Binding Example: LoggingFilter @NameBinding // or @Qualifier ? @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(value = RetentionPolicy.RUNTIME) public @interface Logged { } @Provider @Logged public class LoggingFilter implements RequestFilter, ResponseFilter { … } 30 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 31. Binding Example: LoggingFilter @Path("/") public class MyResourceClass { @Logged @GET @Produces("text/plain") @Path("{name}") public String hello(@PathParam("name") String name) { return "Hello " + name; } } 31 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 32. New in JAX-RS 2.0 ✔ ✔ Filters/Handlers Client API Hypermedia ✔ Async JSR 330 ✔ Validation Improved Conneg 32 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 33. Motivation •  Services must validate data •  Bean Validation already provides the mechanism •  Integration into JAX-RS •  Support for constraint annotations in: •  Fields and properties •  Parameters (including request entity) •  Methods (response entities) •  Resource classes 33 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 34. Example: Constraint Annotations @Path("/") class MyResourceClass { @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) Built-in public void registerUser( @NotNull @FormParam("firstName") String fn, Custom @NotNull @FormParam("lastName") String ln, @Email @FormParam("email") String em) { ... } } 34 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 35. Example: User defined Constraints @Target({ METHOD, FIELD, PARAMETER }) @Retention(RUNTIME) @Constraint(validatedBy = EmailValidator.class) public @interface Email { ... } class EmailValidator implements ConstraintValidator<Email, String> { public void initialize(Email email) { … } public boolean isValid(String value, ConstraintValidatorContext context) { // Check 'value' is e-mail address … } } 35 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 36. Example: Request Entity Validation @CheckUser1 class User { ... } @Path("/") class MyResourceClass { @POST @Consumes("application/xml") public void registerUser1(@Valid User u) { … } @POST @Consumes("application/json") public void registerUser12(@CheckUser2 @Valid User u) { … } } 36 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 37. New in JAX-RS 2.0 ✔ ✔ Filters/Handlers Client API Hypermedia ✔ ✔ Async JSR 330 ✔ Validation Improved Conneg 37 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 38. Motivation •  Let “borrowed” threads run free! •  Container environment •  Suspend and resume connections •  Suspend while waiting for an event •  Resume when event arrives •  Leverage Servlet 3.X async support (if available) •  Client API support •  Future<RESPONSE>, InvocationCallback<RESPONSE> 38 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 39. Example: Suspend and Resume @Path("/async/longRunning") public class MyResource { @Context private ExecutionContext ctx; @GET @Produces("text/plain") public void longRunningOp() { Executors.newSingleThreadExecutor().submit( new Runnable() { public void run() { Thread.sleep(10000); // Sleep 10 secs ctx.resume("Hello async world!"); } }); ctx.suspend(); // Suspend connection and return } … } 39 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 40. Example: @Suspend Annotation @Path("/async/longRunning") public class MyResource { @Context private ExecutionContext ctx; @GET @Produces("text/plain") @Suspend public void longRunning() { Executors.newSingleThreadExecutor().submit( new Runnable() { public void run() { Thread.sleep(10000); // Sleep 10 secs ctx.resume("Hello async world!"); } }); // ctx.suspend(); Suspend connection and return } … } 40 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 41. Example: Client API Async Support // Build target URI Target target = client.target("http://.../atm/balance")… // Start async call and register callback Future<?> handle = target.request().async().get( new InvocationCallback<String>() { public void complete(String balance) { … } public void failed(InvocationException e) { … } }); // After waiting for a while … If (!handle.isDone()) handle.cancel(true); 41 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 42. New in JAX-RS 2.0 ✔ ✔ Filters/Handlers Client API ✔ Hypermedia ✔ ✔ Async JSR 330 ✔ Validation Improved Conneg 42 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 43. Motivation •  REST principles •  Identifiers and Links •  HATEOAS (Hypermedia As The Engine Of App State) •  Link types: •  Structural Links •  Transitional Links 43 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 44. Example: Structural vs. Transitional Links Link: <http://.../orders/1/ship>; rel=ship, <http://.../orders/1/cancel>; rel=cancel Transitional ... <order id="1"> <customer>http://.../customers/11</customer> <address>http://.../customers/11/address/1</customer> <items> <item> Structural <product>http://.../products/111</products> <quantity>2</quantity> </item> ... </order> 44 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 45. Current Proposal Transitional Links Only •  Link and LinkBuilder classes •  RFC 5988: Web Linking •  Support for Link in ResponseBuilder •  Create Target from Link in Client API 45 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 46. Example: Using Transitional Links // Server API Response res = Response.ok(order) .link("http://.../orders/1/ship", "ship") .build(); // Client API Response order = client.target(…) .request("application/xml").get(); if (order.getLink(“ship”) != null) { Response shippedOrder = client .target(order.getLink("ship")) .request("application/xml").post(null); … } 46 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 47. New in JAX-RS 2.0 ✔ ✔ Filters/Handlers Client API ✔ Hypermedia ✔ ✔ Async JSR 330 ✔ Validation ✔ Improved Conneg 47 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 48. Improved Conneg GET http://.../widgets2 Accept: text/*; q=1 … Path("widgets2") public class WidgetsResource2 { @GET @Produces("text/plain", "text/html") public Widgets getWidget() {...} } 48 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 49. Improved Conneg (contd.) GET http://.../widgets2 Accept: text/*; q=1 … Path("widgets2") public class WidgetsResource2 { @GET @Produces("text/plain;qs=0.5", "text/html;qs=0.75") public Widgets getWidget() {...} } 49 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 50. Other Topics Under Consideration •  Better integration with JSR 330 •  Support @Inject and qualifiers •  High-level client API? 50 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 51. More Information •  JSR: http://jcp.org/en/jsr/detail?id=339 •  Java.net: http://java.net/projects/jax-rs-spec •  User Alias: users@jax-rs-spec.java.net •  All EG discussions forwarded to this list 51 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
  • 52. Q&A 52 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.