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




Developing RESTful Web services with JAX-RS
Shreedhar Ganapathy, Arun Gupta, Java EE &
GlassFish Guys
The following/preceding 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
What is REST
• REST stands for Representational State Transfer.


• Relies on a stateless, client-server, cacheable communications
 protocol

• In most cases, the HTTP protocol is used to make calls between
 two or more network endpoints

• Lightweight alternative to mechanisms like CORBA, RPC and
 Web Services (SOAP, WSDL, etc. )

• REST uses HTTP for all four CRUD (Create / Read / Update /
 Delete) operations




                                                                   3
REST is an Architectural Style


  Style of software architecture for
designing distributed and networked
hypermedia systems such as World
              Wide Web



                                       4
RESTful Web Services



Application of REST architectural style
 to services that utilize Web standards
(URIs, HTTP, HTML, XML, Atom, RDF
 etc.) that are Platform and Language
               independent


                                          5
Java API for RESTful Web Services
(JAX-RS)


 Standard annotation-driven API that
aims to help developers build RESTful
        Web services in Java



                                        6
How does REST compare with SOAP?
SOAP Request                                  REST Query
The following query is sent as an HTTP POST   The following URL is sent to server
                                              with a GET request
Result response is usually an XML document
embedded in an envelope
                                              The response is raw result data that
                                              can be directly consumed without
<?xml version="1.0"?>
                                              opening an envelope
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soa
p-envelope"                                   http://www.example.com/custo
soap:encodingStyle="http://www.w3.org/200     merdb/CustomerAddress/4545
1/12/soap-encoding">
 <soap:body
pb="http://www.example.com/customerdb">
  <pb:GetCustomerAddress>
<pb:CustID>4545</pb:CustID>
  </pb:GetCustomerAddress>
 </soap:Body>
</soap:Envelope>




                                                                                     7
RESTful Application Cycle

            Resources are identified by URIs
                             ↓
 Clients communicate with resources via requests using a
                 standard set of methods
                             ↓
Requests and responses contain resource representations in
            formats identified by media types
                             ↓
   Responses contain URIs that link to further resources




                                                             8
Principles of REST

• Give everything an ID
• Standard set of methods
• Link things together
• Multiple representations
• Stateless communications




                             9
Give Everything an ID

• ID is a URI

 http://example.com/widgets/foo

 http://example.com/customers/bar

 http://example.com/customers/bar/orders/2

 http://example.com/orders/101230/customer




                                             10
Resources are identified by URIs

• Resource == Java class
 • POJO
 • No required interfaces
• ID provided by @Path annotation
 • Value is relative URI, base URI is provided by deployment
   context or parent resource
 • Embedded parameters for non-fixed parts of the URI
 • Annotate class or “sub-resource locator” method




                                                               11
Resources are identified by URIs

@Path("orders/{order_id}")
public class OrderResource {

  @GET
  @Path("customer")
  CustomerResource
getCustomer(@PathParam(“order_id”)int id) {...}
}




                                                  12
Standard Set of Methods


    Method                    Purpose

   GET       Read, possibly cached

   POST      Update or create without a known ID

   PUT       Update or create with a known ID

   DELETE    Remove




                                                   13
Standard Set of Methods

• Annotate resource class methods with standard method
   • @GET, @PUT, @POST, @DELETE, @HEAD
   • @HttpMethod meta-annotation allows extensions, e.g. WebDAV
• JAX-RS routes request to appropriate resource class and
  method
• Flexible method signatures, annotations on parameters
  specify mapping from request
• Return value mapped to response




                                                                  14
Standard Set of Methods
@Path("properties/{name}")
public class SystemProperty {

    @GET
    Property get(@PathParam("name") String name)
      {...}

    @PUT
    Property set(@PathParam("name") String name,
      String value) {...}

}



                                                   15
Multiple Representations
• Offer data in a variety of formats
  • XML (Type safety advantage)
  • JSON (easy to parse with JavaScript clients)
  • (X)HTML (Ideal for clients like browsers for human readable
    documents)
• Maximize reach
• Support content negotiation
  • Accept header
    GET /foo
    Accept: application/json
  • URI-based
    GET /foo.json



                                                                  16
Resource Representations

• Representation format identified by media
 type. E.g.:
 • XML - application/properties+xml
 • JSON - application/properties+json
 • (X)HTML+microformats - application/xhtml+xml
• JAX-RS automates content negotiation
 • GET /foo
   Accept: application/properties+json




                                                  17
Multiple Representations

• Static - Annotate methods or classes with static capabilities
   • @Produces, @Consumes
• Dynamic - Use Variant, VariantListBuilder and
 Request.selectVariant for dynamic capabilities




                                                                  18
Content Negotiation: Accept Header

Accept: application/xml
Accept: application/json;q=1.0, text/plain;q=0.5, application/xml;q=0.5,

@GET
@Produces({"application/xml","application/json"})
Order getOrder(@PathParam("order_id") String id) {
  ...
}

@GET
@Produces("text/plain")
String getOrder2(@PathParam("order_id") String id) {
  ...
}



                                                                           19
Content Negotiation: URL-based
@Path("/orders")
public class OrderResource {
    @Path("{orderId}.xml")
    @Produces(“application/xml”)
    @GET
    public Order getOrderInXML(@PathParam("orderId") String
orderId) {
      . . .
    }

    @Path("{orderId}.json")
    @Produces(“application/json”)
    @GET
    public Order getOrderInJSON(@PathParam("orderId") String
orderId) {
       . . .
    }
}



                                                               20
JAX-RS 1.1
Code Sample

import   javax.inject.Inject;
import   javax.enterprise.context.RequestScoped;

@RequestScoped
public class ActorResource {
    @Inject DatabaseBean db;

    public Actor getActor(int id) {
        return db.findActorById(id);
    }
}




                                                   21
Content Negotiation
import   javax.ws.rs.GET;
import   javax.ws.rs.Path;
import   javax.ws.rs.Produces;
import   javax.ws.rs.PathParam;
import   javax.inject.Inject;
import   javax.enterprise.context.RequestScoped;

@Path("/actor/{id}")
@RequestScoped
public class ActorResource {
    @Inject DatbaseBean db;

    @GET
    @Produces("application/json")
    public Actor getActor(@PathParam("id") int id) {
         return db.findActorById(id);
    }
}                 http://blogs.sun.com/arungupta/entry/totd_124_using_cdi_jpa


                                                                                22
Link Things Together


<order self="http://example.com/orders/101230">
  <customer ref="http://example.com/customers/bar">
  <product ref="http://example.com/products/21034"/>
  <amount value="1"/>
</order>




                                                   23
Responses Contain Links

HTTP/1.1 201 Created
Date: Wed, 03 Jun 2009 16:41:58 GMT
Server: Apache/1.3.6
Location: http://example.com/properties/foo
Content-Type: application/order+xml
Content-Length: 184

<property self="http://example.com/properties/foo">
  <parent ref="http://example.com/properties/bar"/>
  <name>Foo</name>
  <value>1</value>
</order>




                                                      24
Responses Contain Links

• UriInfo provides information about deployment context,
  the request URI and the route to the resource
• UriBuilder provides facilities to easily construct URIs for
  resources




                                                                25
Responses Contain Links

@Context UriInfo i;

SystemProperty p = ...
UriBuilder b = i.getBaseUriBuilder();
URI u = b.path(SystemProperties.class)
   .path(p.getName()).build();

List<URI> ancestors = i.getMatchedURIs();
URI parent = ancestors.get(1);




                                            26
Stateless Communications


• Long lived identifiers
• Avoid sessions
• Everything required to process a request
 contained in the request




                                             27
JAX-RS 1.1
    More Code Samples
• Processing POSTed HTML Form
@POST
@Consumes("application/x-www-form-urlencoded")
public void post(@FormParam("name") String name) {
     // Store the message
}

• Sub-Resources
@Singleton
@Path("/printers")
public class PrintersResource {

    @GET @Path("/list")
    @Produces({"application/json", "application/xml"})
    public WebResourceList getListOfPrinters() { ... }

    @GET @Path("/ids/{printerid}")
    @Produces({"application/json", "application/xml"})
    public Printer getPrinter(@PathParam("printerid") String printerId) { ...
}



                                                                            28
JAX-RS 1.1
        Integration with Java EE 6 – Servlets 3.0

    • No or Portable “web.xml”
<web-app>                                                 @ApplicationPath(“resources”)
  <servlet>
    <servlet-name>Jersey Web Application</servlet-name>   public class MyApplication
    <servlet-class>                                          extends
                                                             javax.ws.rs.core.Application {
com.sun.jersey.spi.container.servlet.ServletContainer
    </servlet-class>                                      }
    <init-param>
      <param-name>javax.ws.rs.Application</param-name>
      <param-value>com.foo.MyApplication</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey Web Application</servlet-name>
    <url-pattern>/resources/*</url-pattern>
  </servlet-mapping>
</web-app>




                                                                                         29
JAX-RS Summary


• Java API for building RESTful Web Services
• POJO based
• Annotation-driven
• Server-side API
• HTTP-centric




                                           30
JAX-RS 1.1
    Integration with Java EE 6 – EJB 3.1

• Use stateless or singleton EJBs in the
    WAR as resource and provider classes
@Path(“stateless”)
@Stateless                                  @Singleton
public class MyStatelessRootResource {      public class MyStatelessResource {
    @Context UriInfo ui;                            @Context UriInfo ui;


    @GET                                        …
    public String get() { return “GET”; }   }

    @EJB MyStatelessResource subResource;


    @Path(“sub-resource”)
    public MyStatelessResource sub() {
      return subResource;
    }
}


                                                                            31
JAX-RS 1.1
 Jersey Client-side API

• Consume HTTP-based RESTful Services
• Easy-to-use
 • Better than HttpURLConnection!
• Reuses JAX-RS API
 • Resources and URI are first-class citizens
• Not part of JAX-RS yet
 • com.sun.jersey.api.client




                                                32
JAX-RS 1.1
   Jersey Client API – Code Sample

Client client = Client.create();

WebResource resource = client.resource(“...”);

//curl http://example.com/base
String s = resource.get(String.class);

//curl -HAccept:text/plain http://example.com/base
String s = resource.
        accept(“text/plain”).
        get(String.class);

http://blogs.sun.com/enterprisetechtips/entry/consuming_restful_web_services_w
ith

                                                                                 33
JAX-RS 1.1
Jersey Client API – NetBeans Code Generation




                                               34
JAX-RS 1.1
 WADL Representation of Resources
• Machine processable description of
  HTTP-based Applications
• Generated OOTB for the application
    <application xmlns="http://research.sun.com/wadl/2006/10">
      <doc xmlns:jersey="http://jersey.dev.java.net/"
           jersey:generatedBy="Jersey: 1.1.4.1 11/24/2009 01:37
    AM"/>
      <resources base="http://localhost:8080/HelloWADL/resources/">

        <resource path="generic">
          <method id="getText" name="GET">
            <response>
              <representation mediaType="text/plain"/>
            </response>
          </method>
          <method id="putText" name="PUT">
            <request>
              <representation mediaType="text/plain"/>
            </request>
          </method>
        </resource>
      </resources>
    </application>




                                                                      35
Java SE Deployment

• RuntimeDelegate is used to create instances of a
 desired endpoint class
• Application supplies configuration information

  • List of resource classes and providers as subclass of
    Application
• Implementations can support any Java type
   • Jersey supports Grizzly (see below), LW HTTP server and JAX-WS
     Provider




                                                                      36
Example Java SE Deployment

Application app = ...
RuntimeDelegate rd = RuntimeDelegate.getInstance();
Adapter a = rd.createEndpoint(app, Adapter.class);

SelectorThread st = GrizzlyServerFactory.create(
    “http://127.0.0.1:8084/”, a);




                                                      37
Servlet
• JAX-RS application packaged in WAR like a servlet
• For JAX-RS aware containers
   • web.xml can point to Application subclass
• For non-JAX-RS aware containers
   • web.xml points to implementation-specific Servlet; and
   • an init-param identifies the Application subclass
• Resource classes and providers can access Servlet
 request, context, config and response via injection




                                                              38
JAX-RS status
• JAX-RS 1.0: 18th October 2008
• JAX-RS 1.1: 23rd November 2009
   • Aligned with Java EE 6, but not in the Web
     profile!
• JAX-RS 2.0: JSR 339 Filed
• Implementations
   • Apache CXF, Apache Wink, eXo, Jersey,
     RESTEasy, Restlet, Triaxrs


                                          39      39
GET /Samples

• Many samples are provided with the release
  • Atom, JAXB, JSON, Scala, Spring, WADL
  • Using GlassFish (+embedded) and Grizzly
• Download the 1.1.0 samples
  • Samples are maven-based
  • Works with NetBeans 6.x + maven plugin
  • Individual sample zip files are also available
     • e.g. Sparklines, Mandel




                                                     40
GET /Features

• Client API
• JSON with JAXB
• Spring and Guice integration
• MIME multipart API
• Atom with Abdera API
• WADL
• Grizzly and Simple servers




                                 41
JAX-RS 2.0
    http://jcp.org/en/jsr/detail?id=339

                                                         NEW
●
    Client API
    ●
         Low level using Builder pattern, Higher-level
●
    Hypermedia
●
    MVC Pattern
    ●
         Resource controllers, Pluggable viewing technology
●
    Bean Validation
    ●
         Form or Query parameter validation
●
    Closer integration with @Inject, etc.
●
    Server-side asynchronous request processing
●
    Server-side content negotiation

                                                               42
References


• oracle.com/javaee
• glassfish.org
• oracle.com/goto/glassfish
• blogs.sun.com/theaquarium
• youtube.com/GlassFishVideos
• Follow @glassfish




                                43
<Insert Picture Here>




Developing RESTful Web services with JAX-RS
 Shreedhar Ganapathy, Arun Gupta, Java EE &
 GlassFish Guys

 blogs.sun.com/arungupta, @arungupta

Mais conteúdo relacionado

Mais procurados

Front End Development for Backend Developers - GIDS 2019
Front End Development for Backend Developers - GIDS 2019Front End Development for Backend Developers - GIDS 2019
Front End Development for Backend Developers - GIDS 2019Matt Raible
 
Choosing a Java Web Framework
Choosing a Java Web FrameworkChoosing a Java Web Framework
Choosing a Java Web FrameworkWill Iverson
 
Bootiful Development with Spring Boot and React - UberConf 2018
Bootiful Development with Spring Boot and React - UberConf 2018Bootiful Development with Spring Boot and React - UberConf 2018
Bootiful Development with Spring Boot and React - UberConf 2018Matt Raible
 
Seven Simple Reasons to Use AppFuse
Seven Simple Reasons to Use AppFuseSeven Simple Reasons to Use AppFuse
Seven Simple Reasons to Use AppFuseMatt Raible
 
Mobile Development with Ionic, React Native, and JHipster - ACGNJ Java Users ...
Mobile Development with Ionic, React Native, and JHipster - ACGNJ Java Users ...Mobile Development with Ionic, React Native, and JHipster - ACGNJ Java Users ...
Mobile Development with Ionic, React Native, and JHipster - ACGNJ Java Users ...Matt Raible
 
Comparing JVM Web Frameworks - Rich Web Experience 2010
Comparing JVM Web Frameworks - Rich Web Experience 2010Comparing JVM Web Frameworks - Rich Web Experience 2010
Comparing JVM Web Frameworks - Rich Web Experience 2010Matt Raible
 
Java REST API Framework Comparison - PWX 2021
Java REST API Framework Comparison - PWX 2021Java REST API Framework Comparison - PWX 2021
Java REST API Framework Comparison - PWX 2021Matt Raible
 
Spring Boot APIs and Angular Apps: Get Hip with JHipster! KCDC 2019
Spring Boot APIs and Angular Apps: Get Hip with JHipster! KCDC 2019Spring Boot APIs and Angular Apps: Get Hip with JHipster! KCDC 2019
Spring Boot APIs and Angular Apps: Get Hip with JHipster! KCDC 2019Matt Raible
 
Mobile Development with Ionic, React Native, and JHipster - AllTheTalks 2020
Mobile Development with Ionic, React Native, and JHipster - AllTheTalks 2020Mobile Development with Ionic, React Native, and JHipster - AllTheTalks 2020
Mobile Development with Ionic, React Native, and JHipster - AllTheTalks 2020Matt Raible
 
How to Win at UI Development in the World of Microservices - THAT Conference ...
How to Win at UI Development in the World of Microservices - THAT Conference ...How to Win at UI Development in the World of Microservices - THAT Conference ...
How to Win at UI Development in the World of Microservices - THAT Conference ...Matt Raible
 
Java REST API Framework Comparison - UberConf 2021
Java REST API Framework Comparison - UberConf 2021Java REST API Framework Comparison - UberConf 2021
Java REST API Framework Comparison - UberConf 2021Matt Raible
 
Java Web Application Security - UberConf 2011
Java Web Application Security - UberConf 2011Java Web Application Security - UberConf 2011
Java Web Application Security - UberConf 2011Matt Raible
 
Front End Development for Back End Java Developers - NYJavaSIG 2019
Front End Development for Back End Java Developers - NYJavaSIG 2019Front End Development for Back End Java Developers - NYJavaSIG 2019
Front End Development for Back End Java Developers - NYJavaSIG 2019Matt Raible
 
What's New in Spring 3.1
What's New in Spring 3.1What's New in Spring 3.1
What's New in Spring 3.1Matt Raible
 
Case Study: Migrating Hyperic from EJB to Spring from JBoss to Apache Tomcat
Case Study: Migrating Hyperic from EJB to Spring from JBoss to Apache TomcatCase Study: Migrating Hyperic from EJB to Spring from JBoss to Apache Tomcat
Case Study: Migrating Hyperic from EJB to Spring from JBoss to Apache TomcatVMware Hyperic
 
Front End Development for Back End Java Developers - Jfokus 2020
Front End Development for Back End Java Developers - Jfokus 2020Front End Development for Back End Java Developers - Jfokus 2020
Front End Development for Back End Java Developers - Jfokus 2020Matt Raible
 
Apache Roller, Acegi Security and Single Sign-on
Apache Roller, Acegi Security and Single Sign-onApache Roller, Acegi Security and Single Sign-on
Apache Roller, Acegi Security and Single Sign-onMatt Raible
 
JavaOne India 2011 - Running your Java EE 6 Apps in the Cloud
JavaOne India 2011 - Running your Java EE 6 Apps in the CloudJavaOne India 2011 - Running your Java EE 6 Apps in the Cloud
JavaOne India 2011 - Running your Java EE 6 Apps in the CloudArun Gupta
 
Web App Security for Java Developers - UberConf 2021
Web App Security for Java Developers - UberConf 2021Web App Security for Java Developers - UberConf 2021
Web App Security for Java Developers - UberConf 2021Matt Raible
 
Java REST API Comparison: Micronaut, Quarkus, and Spring Boot - jconf.dev 2020
Java REST API Comparison: Micronaut, Quarkus, and Spring Boot - jconf.dev 2020Java REST API Comparison: Micronaut, Quarkus, and Spring Boot - jconf.dev 2020
Java REST API Comparison: Micronaut, Quarkus, and Spring Boot - jconf.dev 2020Matt Raible
 

Mais procurados (20)

Front End Development for Backend Developers - GIDS 2019
Front End Development for Backend Developers - GIDS 2019Front End Development for Backend Developers - GIDS 2019
Front End Development for Backend Developers - GIDS 2019
 
Choosing a Java Web Framework
Choosing a Java Web FrameworkChoosing a Java Web Framework
Choosing a Java Web Framework
 
Bootiful Development with Spring Boot and React - UberConf 2018
Bootiful Development with Spring Boot and React - UberConf 2018Bootiful Development with Spring Boot and React - UberConf 2018
Bootiful Development with Spring Boot and React - UberConf 2018
 
Seven Simple Reasons to Use AppFuse
Seven Simple Reasons to Use AppFuseSeven Simple Reasons to Use AppFuse
Seven Simple Reasons to Use AppFuse
 
Mobile Development with Ionic, React Native, and JHipster - ACGNJ Java Users ...
Mobile Development with Ionic, React Native, and JHipster - ACGNJ Java Users ...Mobile Development with Ionic, React Native, and JHipster - ACGNJ Java Users ...
Mobile Development with Ionic, React Native, and JHipster - ACGNJ Java Users ...
 
Comparing JVM Web Frameworks - Rich Web Experience 2010
Comparing JVM Web Frameworks - Rich Web Experience 2010Comparing JVM Web Frameworks - Rich Web Experience 2010
Comparing JVM Web Frameworks - Rich Web Experience 2010
 
Java REST API Framework Comparison - PWX 2021
Java REST API Framework Comparison - PWX 2021Java REST API Framework Comparison - PWX 2021
Java REST API Framework Comparison - PWX 2021
 
Spring Boot APIs and Angular Apps: Get Hip with JHipster! KCDC 2019
Spring Boot APIs and Angular Apps: Get Hip with JHipster! KCDC 2019Spring Boot APIs and Angular Apps: Get Hip with JHipster! KCDC 2019
Spring Boot APIs and Angular Apps: Get Hip with JHipster! KCDC 2019
 
Mobile Development with Ionic, React Native, and JHipster - AllTheTalks 2020
Mobile Development with Ionic, React Native, and JHipster - AllTheTalks 2020Mobile Development with Ionic, React Native, and JHipster - AllTheTalks 2020
Mobile Development with Ionic, React Native, and JHipster - AllTheTalks 2020
 
How to Win at UI Development in the World of Microservices - THAT Conference ...
How to Win at UI Development in the World of Microservices - THAT Conference ...How to Win at UI Development in the World of Microservices - THAT Conference ...
How to Win at UI Development in the World of Microservices - THAT Conference ...
 
Java REST API Framework Comparison - UberConf 2021
Java REST API Framework Comparison - UberConf 2021Java REST API Framework Comparison - UberConf 2021
Java REST API Framework Comparison - UberConf 2021
 
Java Web Application Security - UberConf 2011
Java Web Application Security - UberConf 2011Java Web Application Security - UberConf 2011
Java Web Application Security - UberConf 2011
 
Front End Development for Back End Java Developers - NYJavaSIG 2019
Front End Development for Back End Java Developers - NYJavaSIG 2019Front End Development for Back End Java Developers - NYJavaSIG 2019
Front End Development for Back End Java Developers - NYJavaSIG 2019
 
What's New in Spring 3.1
What's New in Spring 3.1What's New in Spring 3.1
What's New in Spring 3.1
 
Case Study: Migrating Hyperic from EJB to Spring from JBoss to Apache Tomcat
Case Study: Migrating Hyperic from EJB to Spring from JBoss to Apache TomcatCase Study: Migrating Hyperic from EJB to Spring from JBoss to Apache Tomcat
Case Study: Migrating Hyperic from EJB to Spring from JBoss to Apache Tomcat
 
Front End Development for Back End Java Developers - Jfokus 2020
Front End Development for Back End Java Developers - Jfokus 2020Front End Development for Back End Java Developers - Jfokus 2020
Front End Development for Back End Java Developers - Jfokus 2020
 
Apache Roller, Acegi Security and Single Sign-on
Apache Roller, Acegi Security and Single Sign-onApache Roller, Acegi Security and Single Sign-on
Apache Roller, Acegi Security and Single Sign-on
 
JavaOne India 2011 - Running your Java EE 6 Apps in the Cloud
JavaOne India 2011 - Running your Java EE 6 Apps in the CloudJavaOne India 2011 - Running your Java EE 6 Apps in the Cloud
JavaOne India 2011 - Running your Java EE 6 Apps in the Cloud
 
Web App Security for Java Developers - UberConf 2021
Web App Security for Java Developers - UberConf 2021Web App Security for Java Developers - UberConf 2021
Web App Security for Java Developers - UberConf 2021
 
Java REST API Comparison: Micronaut, Quarkus, and Spring Boot - jconf.dev 2020
Java REST API Comparison: Micronaut, Quarkus, and Spring Boot - jconf.dev 2020Java REST API Comparison: Micronaut, Quarkus, and Spring Boot - jconf.dev 2020
Java REST API Comparison: Micronaut, Quarkus, and Spring Boot - jconf.dev 2020
 

Destaque

Java EE 6 Clustering with Glassfish 3.1
Java EE 6 Clustering with Glassfish 3.1 Java EE 6 Clustering with Glassfish 3.1
Java EE 6 Clustering with Glassfish 3.1 Shreedhar Ganapathy
 
Glassfish Overview Fontys 20090520
Glassfish Overview Fontys 20090520Glassfish Overview Fontys 20090520
Glassfish Overview Fontys 20090520Eugene Bogaart
 
Coherence sig-nfr-web-tier-scaling-using-coherence-web
Coherence sig-nfr-web-tier-scaling-using-coherence-webCoherence sig-nfr-web-tier-scaling-using-coherence-web
Coherence sig-nfr-web-tier-scaling-using-coherence-webC2B2 Consulting
 
HTTP Session Replication with Oracle Coherence, GlassFish, WebLogic
HTTP Session Replication with Oracle Coherence, GlassFish, WebLogicHTTP Session Replication with Oracle Coherence, GlassFish, WebLogic
HTTP Session Replication with Oracle Coherence, GlassFish, WebLogicOracle
 
An Engineer's Intro to Oracle Coherence
An Engineer's Intro to Oracle CoherenceAn Engineer's Intro to Oracle Coherence
An Engineer's Intro to Oracle CoherenceOracle
 
Oracle Coherence: in-memory datagrid
Oracle Coherence: in-memory datagridOracle Coherence: in-memory datagrid
Oracle Coherence: in-memory datagridEmiliano Pecis
 

Destaque (7)

GlassFish v2 Clustering
GlassFish v2 ClusteringGlassFish v2 Clustering
GlassFish v2 Clustering
 
Java EE 6 Clustering with Glassfish 3.1
Java EE 6 Clustering with Glassfish 3.1 Java EE 6 Clustering with Glassfish 3.1
Java EE 6 Clustering with Glassfish 3.1
 
Glassfish Overview Fontys 20090520
Glassfish Overview Fontys 20090520Glassfish Overview Fontys 20090520
Glassfish Overview Fontys 20090520
 
Coherence sig-nfr-web-tier-scaling-using-coherence-web
Coherence sig-nfr-web-tier-scaling-using-coherence-webCoherence sig-nfr-web-tier-scaling-using-coherence-web
Coherence sig-nfr-web-tier-scaling-using-coherence-web
 
HTTP Session Replication with Oracle Coherence, GlassFish, WebLogic
HTTP Session Replication with Oracle Coherence, GlassFish, WebLogicHTTP Session Replication with Oracle Coherence, GlassFish, WebLogic
HTTP Session Replication with Oracle Coherence, GlassFish, WebLogic
 
An Engineer's Intro to Oracle Coherence
An Engineer's Intro to Oracle CoherenceAn Engineer's Intro to Oracle Coherence
An Engineer's Intro to Oracle Coherence
 
Oracle Coherence: in-memory datagrid
Oracle Coherence: in-memory datagridOracle Coherence: in-memory datagrid
Oracle Coherence: in-memory datagrid
 

Semelhante a JAX-RS JavaOne Hyderabad, India 2011

RESTful Web services using JAX-RS
RESTful Web services using JAX-RSRESTful Web services using JAX-RS
RESTful Web services using JAX-RSArun Gupta
 
JAX-RS Creating RESTFul services
JAX-RS Creating RESTFul servicesJAX-RS Creating RESTFul services
JAX-RS Creating RESTFul servicesLudovic Champenois
 
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
 
Resting on your laurels will get you powned
Resting on your laurels will get you pownedResting on your laurels will get you powned
Resting on your laurels will get you pownedDinis Cruz
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiTiago Knoch
 
Ppt on web development and this has all details
Ppt on web development and this has all detailsPpt on web development and this has all details
Ppt on web development and this has all detailsgogijoshiajmer
 
Consuming RESTful Web services in PHP
Consuming RESTful Web services in PHPConsuming RESTful Web services in PHP
Consuming RESTful Web services in PHPZoran Jeremic
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHPZoran Jeremic
 
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
 
JAX-RS 2.0 and OData
JAX-RS 2.0 and ODataJAX-RS 2.0 and OData
JAX-RS 2.0 and ODataAnil Allewar
 
Java colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rsJava colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rsSagara Gunathunga
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP TutorialLorna Mitchell
 
Network Device Database Management with REST using Jersey
Network Device Database Management with REST using JerseyNetwork Device Database Management with REST using Jersey
Network Device Database Management with REST using JerseyPayal Jain
 
Android App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web ServicesAndroid App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web ServicesAnuchit Chalothorn
 
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
 

Semelhante a JAX-RS JavaOne Hyderabad, India 2011 (20)

RESTful Web services using JAX-RS
RESTful Web services using JAX-RSRESTful Web services using JAX-RS
RESTful Web services using JAX-RS
 
JAX-RS Creating RESTFul services
JAX-RS Creating RESTFul servicesJAX-RS Creating RESTFul services
JAX-RS Creating RESTFul services
 
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
 
Resting on your laurels will get you powned
Resting on your laurels will get you pownedResting on your laurels will get you powned
Resting on your laurels will get you powned
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
 
Ppt on web development and this has all details
Ppt on web development and this has all detailsPpt on web development and this has all details
Ppt on web development and this has all details
 
Consuming RESTful Web services in PHP
Consuming RESTful Web services in PHPConsuming RESTful Web services in PHP
Consuming RESTful Web services in PHP
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHP
 
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
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web services
 
JAX-RS 2.0 and OData
JAX-RS 2.0 and ODataJAX-RS 2.0 and OData
JAX-RS 2.0 and OData
 
Java colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rsJava colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rs
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
 
Network Device Database Management with REST using Jersey
Network Device Database Management with REST using JerseyNetwork Device Database Management with REST using Jersey
Network Device Database Management with REST using Jersey
 
Rest web services
Rest web servicesRest web services
Rest web services
 
Web services tutorial
Web services tutorialWeb services tutorial
Web services tutorial
 
Android App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web ServicesAndroid App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web Services
 
RESTing with JAX-RS
RESTing with JAX-RSRESTing with JAX-RS
RESTing with 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!
 

Último

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
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
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
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
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 

Último (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
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...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
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
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 

JAX-RS JavaOne Hyderabad, India 2011

  • 1. <Insert Picture Here> Developing RESTful Web services with JAX-RS Shreedhar Ganapathy, Arun Gupta, Java EE & GlassFish Guys
  • 2. The following/preceding 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
  • 3. What is REST • REST stands for Representational State Transfer. • Relies on a stateless, client-server, cacheable communications protocol • In most cases, the HTTP protocol is used to make calls between two or more network endpoints • Lightweight alternative to mechanisms like CORBA, RPC and Web Services (SOAP, WSDL, etc. ) • REST uses HTTP for all four CRUD (Create / Read / Update / Delete) operations 3
  • 4. REST is an Architectural Style Style of software architecture for designing distributed and networked hypermedia systems such as World Wide Web 4
  • 5. RESTful Web Services Application of REST architectural style to services that utilize Web standards (URIs, HTTP, HTML, XML, Atom, RDF etc.) that are Platform and Language independent 5
  • 6. Java API for RESTful Web Services (JAX-RS) Standard annotation-driven API that aims to help developers build RESTful Web services in Java 6
  • 7. How does REST compare with SOAP? SOAP Request REST Query The following query is sent as an HTTP POST The following URL is sent to server with a GET request Result response is usually an XML document embedded in an envelope The response is raw result data that can be directly consumed without <?xml version="1.0"?> opening an envelope <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soa p-envelope" http://www.example.com/custo soap:encodingStyle="http://www.w3.org/200 merdb/CustomerAddress/4545 1/12/soap-encoding"> <soap:body pb="http://www.example.com/customerdb"> <pb:GetCustomerAddress> <pb:CustID>4545</pb:CustID> </pb:GetCustomerAddress> </soap:Body> </soap:Envelope> 7
  • 8. RESTful Application Cycle Resources are identified by URIs ↓ Clients communicate with resources via requests using a standard set of methods ↓ Requests and responses contain resource representations in formats identified by media types ↓ Responses contain URIs that link to further resources 8
  • 9. Principles of REST • Give everything an ID • Standard set of methods • Link things together • Multiple representations • Stateless communications 9
  • 10. Give Everything an ID • ID is a URI http://example.com/widgets/foo http://example.com/customers/bar http://example.com/customers/bar/orders/2 http://example.com/orders/101230/customer 10
  • 11. Resources are identified by URIs • Resource == Java class • POJO • No required interfaces • ID provided by @Path annotation • Value is relative URI, base URI is provided by deployment context or parent resource • Embedded parameters for non-fixed parts of the URI • Annotate class or “sub-resource locator” method 11
  • 12. Resources are identified by URIs @Path("orders/{order_id}") public class OrderResource { @GET @Path("customer") CustomerResource getCustomer(@PathParam(“order_id”)int id) {...} } 12
  • 13. Standard Set of Methods Method Purpose GET Read, possibly cached POST Update or create without a known ID PUT Update or create with a known ID DELETE Remove 13
  • 14. Standard Set of Methods • Annotate resource class methods with standard method • @GET, @PUT, @POST, @DELETE, @HEAD • @HttpMethod meta-annotation allows extensions, e.g. WebDAV • JAX-RS routes request to appropriate resource class and method • Flexible method signatures, annotations on parameters specify mapping from request • Return value mapped to response 14
  • 15. Standard Set of Methods @Path("properties/{name}") public class SystemProperty { @GET Property get(@PathParam("name") String name) {...} @PUT Property set(@PathParam("name") String name, String value) {...} } 15
  • 16. Multiple Representations • Offer data in a variety of formats • XML (Type safety advantage) • JSON (easy to parse with JavaScript clients) • (X)HTML (Ideal for clients like browsers for human readable documents) • Maximize reach • Support content negotiation • Accept header GET /foo Accept: application/json • URI-based GET /foo.json 16
  • 17. Resource Representations • Representation format identified by media type. E.g.: • XML - application/properties+xml • JSON - application/properties+json • (X)HTML+microformats - application/xhtml+xml • JAX-RS automates content negotiation • GET /foo Accept: application/properties+json 17
  • 18. Multiple Representations • Static - Annotate methods or classes with static capabilities • @Produces, @Consumes • Dynamic - Use Variant, VariantListBuilder and Request.selectVariant for dynamic capabilities 18
  • 19. Content Negotiation: Accept Header Accept: application/xml Accept: application/json;q=1.0, text/plain;q=0.5, application/xml;q=0.5, @GET @Produces({"application/xml","application/json"}) Order getOrder(@PathParam("order_id") String id) { ... } @GET @Produces("text/plain") String getOrder2(@PathParam("order_id") String id) { ... } 19
  • 20. Content Negotiation: URL-based @Path("/orders") public class OrderResource { @Path("{orderId}.xml") @Produces(“application/xml”) @GET public Order getOrderInXML(@PathParam("orderId") String orderId) { . . . } @Path("{orderId}.json") @Produces(“application/json”) @GET public Order getOrderInJSON(@PathParam("orderId") String orderId) { . . . } } 20
  • 21. JAX-RS 1.1 Code Sample import javax.inject.Inject; import javax.enterprise.context.RequestScoped; @RequestScoped public class ActorResource { @Inject DatabaseBean db; public Actor getActor(int id) { return db.findActorById(id); } } 21
  • 22. Content Negotiation import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.PathParam; import javax.inject.Inject; import javax.enterprise.context.RequestScoped; @Path("/actor/{id}") @RequestScoped public class ActorResource { @Inject DatbaseBean db; @GET @Produces("application/json") public Actor getActor(@PathParam("id") int id) { return db.findActorById(id); } } http://blogs.sun.com/arungupta/entry/totd_124_using_cdi_jpa 22
  • 23. Link Things Together <order self="http://example.com/orders/101230"> <customer ref="http://example.com/customers/bar"> <product ref="http://example.com/products/21034"/> <amount value="1"/> </order> 23
  • 24. Responses Contain Links HTTP/1.1 201 Created Date: Wed, 03 Jun 2009 16:41:58 GMT Server: Apache/1.3.6 Location: http://example.com/properties/foo Content-Type: application/order+xml Content-Length: 184 <property self="http://example.com/properties/foo"> <parent ref="http://example.com/properties/bar"/> <name>Foo</name> <value>1</value> </order> 24
  • 25. Responses Contain Links • UriInfo provides information about deployment context, the request URI and the route to the resource • UriBuilder provides facilities to easily construct URIs for resources 25
  • 26. Responses Contain Links @Context UriInfo i; SystemProperty p = ... UriBuilder b = i.getBaseUriBuilder(); URI u = b.path(SystemProperties.class) .path(p.getName()).build(); List<URI> ancestors = i.getMatchedURIs(); URI parent = ancestors.get(1); 26
  • 27. Stateless Communications • Long lived identifiers • Avoid sessions • Everything required to process a request contained in the request 27
  • 28. JAX-RS 1.1 More Code Samples • Processing POSTed HTML Form @POST @Consumes("application/x-www-form-urlencoded") public void post(@FormParam("name") String name) { // Store the message } • Sub-Resources @Singleton @Path("/printers") public class PrintersResource { @GET @Path("/list") @Produces({"application/json", "application/xml"}) public WebResourceList getListOfPrinters() { ... } @GET @Path("/ids/{printerid}") @Produces({"application/json", "application/xml"}) public Printer getPrinter(@PathParam("printerid") String printerId) { ... } 28
  • 29. JAX-RS 1.1 Integration with Java EE 6 – Servlets 3.0 • No or Portable “web.xml” <web-app> @ApplicationPath(“resources”) <servlet> <servlet-name>Jersey Web Application</servlet-name> public class MyApplication <servlet-class> extends javax.ws.rs.core.Application { com.sun.jersey.spi.container.servlet.ServletContainer </servlet-class> } <init-param> <param-name>javax.ws.rs.Application</param-name> <param-value>com.foo.MyApplication</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Jersey Web Application</servlet-name> <url-pattern>/resources/*</url-pattern> </servlet-mapping> </web-app> 29
  • 30. JAX-RS Summary • Java API for building RESTful Web Services • POJO based • Annotation-driven • Server-side API • HTTP-centric 30
  • 31. JAX-RS 1.1 Integration with Java EE 6 – EJB 3.1 • Use stateless or singleton EJBs in the WAR as resource and provider classes @Path(“stateless”) @Stateless @Singleton public class MyStatelessRootResource { public class MyStatelessResource { @Context UriInfo ui; @Context UriInfo ui; @GET … public String get() { return “GET”; } } @EJB MyStatelessResource subResource; @Path(“sub-resource”) public MyStatelessResource sub() { return subResource; } } 31
  • 32. JAX-RS 1.1 Jersey Client-side API • Consume HTTP-based RESTful Services • Easy-to-use • Better than HttpURLConnection! • Reuses JAX-RS API • Resources and URI are first-class citizens • Not part of JAX-RS yet • com.sun.jersey.api.client 32
  • 33. JAX-RS 1.1 Jersey Client API – Code Sample Client client = Client.create(); WebResource resource = client.resource(“...”); //curl http://example.com/base String s = resource.get(String.class); //curl -HAccept:text/plain http://example.com/base String s = resource. accept(“text/plain”). get(String.class); http://blogs.sun.com/enterprisetechtips/entry/consuming_restful_web_services_w ith 33
  • 34. JAX-RS 1.1 Jersey Client API – NetBeans Code Generation 34
  • 35. JAX-RS 1.1 WADL Representation of Resources • Machine processable description of HTTP-based Applications • Generated OOTB for the application <application xmlns="http://research.sun.com/wadl/2006/10"> <doc xmlns:jersey="http://jersey.dev.java.net/" jersey:generatedBy="Jersey: 1.1.4.1 11/24/2009 01:37 AM"/> <resources base="http://localhost:8080/HelloWADL/resources/"> <resource path="generic"> <method id="getText" name="GET"> <response> <representation mediaType="text/plain"/> </response> </method> <method id="putText" name="PUT"> <request> <representation mediaType="text/plain"/> </request> </method> </resource> </resources> </application> 35
  • 36. Java SE Deployment • RuntimeDelegate is used to create instances of a desired endpoint class • Application supplies configuration information • List of resource classes and providers as subclass of Application • Implementations can support any Java type • Jersey supports Grizzly (see below), LW HTTP server and JAX-WS Provider 36
  • 37. Example Java SE Deployment Application app = ... RuntimeDelegate rd = RuntimeDelegate.getInstance(); Adapter a = rd.createEndpoint(app, Adapter.class); SelectorThread st = GrizzlyServerFactory.create( “http://127.0.0.1:8084/”, a); 37
  • 38. Servlet • JAX-RS application packaged in WAR like a servlet • For JAX-RS aware containers • web.xml can point to Application subclass • For non-JAX-RS aware containers • web.xml points to implementation-specific Servlet; and • an init-param identifies the Application subclass • Resource classes and providers can access Servlet request, context, config and response via injection 38
  • 39. JAX-RS status • JAX-RS 1.0: 18th October 2008 • JAX-RS 1.1: 23rd November 2009 • Aligned with Java EE 6, but not in the Web profile! • JAX-RS 2.0: JSR 339 Filed • Implementations • Apache CXF, Apache Wink, eXo, Jersey, RESTEasy, Restlet, Triaxrs 39 39
  • 40. GET /Samples • Many samples are provided with the release • Atom, JAXB, JSON, Scala, Spring, WADL • Using GlassFish (+embedded) and Grizzly • Download the 1.1.0 samples • Samples are maven-based • Works with NetBeans 6.x + maven plugin • Individual sample zip files are also available • e.g. Sparklines, Mandel 40
  • 41. GET /Features • Client API • JSON with JAXB • Spring and Guice integration • MIME multipart API • Atom with Abdera API • WADL • Grizzly and Simple servers 41
  • 42. JAX-RS 2.0 http://jcp.org/en/jsr/detail?id=339 NEW ● Client API ● Low level using Builder pattern, Higher-level ● Hypermedia ● MVC Pattern ● Resource controllers, Pluggable viewing technology ● Bean Validation ● Form or Query parameter validation ● Closer integration with @Inject, etc. ● Server-side asynchronous request processing ● Server-side content negotiation 42
  • 43. References • oracle.com/javaee • glassfish.org • oracle.com/goto/glassfish • blogs.sun.com/theaquarium • youtube.com/GlassFishVideos • Follow @glassfish 43
  • 44. <Insert Picture Here> Developing RESTful Web services with JAX-RS Shreedhar Ganapathy, Arun Gupta, Java EE & GlassFish Guys blogs.sun.com/arungupta, @arungupta