Your SlideShare is downloading. ×
0
<Insert Picture Here>Developing RESTful Web services with JAX-RSArun Gupta, Java EE & GlassFish Guyblogs.oracle.com/arungu...
The following/preceding is intended to outline ourgeneral product direction. It is intended forinformation purposes only, ...
REST is an Architectural Style   Style of software architecture fordistributed hypermedia systems such          as World W...
RESTful Web ServicesApplication of REST architectural style to services that utilize Web standards(URIs, HTTP, HTML, XML, ...
Java API for RESTful Web Services(JAX-RS) Standard annotation-driven API thataims to help developers build RESTful        ...
RESTful Application Cycle            Resources are identified by URIs                             ↓ Clients communicate wi...
Principles of REST• Give everything an ID• Standard set of methods• Link things together• Multiple representations• Statel...
Give Everything an ID• ID is a URI http://example.com/widgets/foo http://example.com/customers/bar http://example.com/cust...
Resources are identified by URIs• Resource == Java class • POJO • No required interfaces• ID provided by @Path annotation ...
Resources are identified by URIs@Path("orders/{order_id}")public class OrderResource {    @GET    @Path("customer")    Cus...
Standard Set of MethodsMethod    Purpose                               AnnotationGET       Read, possibly cached          ...
Standard Set of Methods• Annotate resource class methods with standard method   • @GET, @PUT, @POST, @DELETE, @HEAD   • @H...
Standard Set of Methods@Path("properties/{name}")public class SystemProperty {    @GET    Property get(@PathParam("name") ...
Binding Request to ResourceAnnotation     Sample@PathParam     Binds the value from URI, e.g.               @PathParam(“id...
Multiple Representations• Offer data in a variety of formats  • XML  • JSON  • (X)HTML• Maximize reach• Support content ne...
Resource Representations• Representation format identified by media type. E.g.: • XML - application/properties+xml • JSON ...
Multiple Representations• Static - Annotate methods or classes with static capabilities   • @Produces, @Consumes• Dynamic ...
Content Negotiation: Accept HeaderAccept: application/xmlAccept: application/json;q=1.0, text/xml;q=0.5, application/xml;q...
Content Negotiation: URL-based@Path("/orders")public class OrderResource {    @Path("{orderId}.xml")    @Produces(“applica...
JAX-RS 1.1Code Sampleimport javax.inject.Inject;import javax.enterprise.context.RequestScoped;@RequestScopedpublic class A...
Content Negotiationimport   javax.ws.rs.GET;import   javax.ws.rs.Path;import   javax.ws.rs.Produces;import   javax.ws.rs.P...
Link Things Together<order self="http://example.com/orders/101230">  <customer ref="http://example.com/customers/bar">  <p...
Responses Contain LinksHTTP/1.1 201 CreatedDate: Wed, 03 Jun 2009 16:41:58 GMTServer: Apache/1.3.6Location: http://example...
Responses Contain Links• UriInfo provides information about deployment context,  the request URI and the route to the reso...
Responses Contain Links@Context UriInfo i;SystemProperty p = ...UriBuilder b = i.getBaseUriBuilder();URI u = b.path(System...
Stateless Communications• Long lived identifiers• Avoid sessions• Everything required to process a request contained in th...
JAX-RS 1.1    More Code Samples• Processing POSTed HTMLForm@POST@Consumes("application/x-www-form-urlencoded")public void ...
JAX-RS 1.1        Integration with Java EE 6 – Servlets 3.0    • No or Portable “web.xml”<web-app>                        ...
Mapping Application Exceptions    • Map checked or runtime exception to Responsepublic class OrderNotFoundException extend...
Mapping Application Exceptions@Providerpublic class OrderNotFoundExceptionMapper implementsExceptionMapper<OrderNotFoundEx...
JAX-RS Summary• Java API for building RESTful Web Services• POJO based• Annotation-driven• Server-side API• HTTP-centric  ...
JAX-RS 1.1    Integration with Java EE 6 – EJB 3.1• Use stateless or singleton EJBs in the    WAR as resource and provider...
JAX-RS 1.1 Jersey Client-side API• Consume HTTP-based RESTful Services• Easy-to-use • Better than HttpURLConnection!• Reus...
JAX-RS 1.1   Jersey Client API – Code SampleClient client = Client.create();WebResource resource = client.resource(“...”);...
JAX-RS 1.1Jersey Client API – NetBeans Code Generation                                               35
JAX-RS 1.1  WADL Representation of Resources• Machine processable description of  HTTP-based Applications• Generated OOTB ...
Java SE Deployment• RuntimeDelegate is used to create instances of a desired endpoint class• Application supplies configur...
Example Java SE DeploymentApplication app = ...RuntimeDelegate rd = RuntimeDelegate.getInstance();Adapter a = rd.createEnd...
Servlet• JAX-RS application packaged in WAR like a servlet• For JAX-RS aware containers   • web.xml can point to Applicati...
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 ...
GET /Samples• Many samples are provided with the release  • Atom, JAXB, JSON, Scala, Spring, WADL  • Using GlassFish (+emb...
JAX-RS 2.0 (JSR 339)    http://jcp.org/en/jsr/detail?id=339    http://jax-rs-spec.java.net●    Client API    ●         Low...
References• oracle.com/javaee• glassfish.org• oracle.com/goto/glassfish• blogs.oracle.com/theaquarium• youtube.com/GlassFi...
<Insert Picture Here>Developing RESTful Web services with JAX-RSArun Gupta, Java EE & GlassFish Guyblogs.oracle.com/arungu...
Upcoming SlideShare
Loading in...5
×

RESTful Web services using JAX-RS

22,204

Published on

RESTful Web services using JAX-RS at Java Day, Istanbul, May 2012

Published in: Technology
1 Comment
19 Likes
Statistics
Notes
  • Hi Arun,
    I am working with Jersy to RESTFUL JSON output.
    is it possible to send custom object as a @Pathparam using get method and i need json as output using RESTFUL.

    I mean instead of sending all the parameters URI like ----> custom/1/aaa/addr shall we custom/pojo

    Client Side:

    class Pojo{
    int id=1;
    String name='aaa';
    String addr='addr';
    //setter & getters

    }

    Main class:

    public static void main(String... a)
    {
    Pojo pojo = new Pojo();

    System.out.println(service.path('rest').path('custom/pojo').accept(MediaType.APPLICATION_JSON).get(String.class));
    }


    server side:

    @Path('/custom')
    class Custom
    {
    @GET
    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    @Path('{pojo}')
    public Pojo getJsonOutput(@PathParam('pojo') Pojo p) {
    if(1==p.getId() && 'aaa'.equals(p.getName()) && 'addr'.equals(p.getAddr())


    return new Pojo();

    else

    return null;
    }
    }


    class Pojo{
    int id=1;
    String name='aaa';
    String addr='addr';
    String firstName='aaa';
    String lastName='bbb';
    String firstAddr='ccc';
    String lastAddr='ddd';
    String mobnumber='123457896';

    //Setters & Getters

    }
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total Views
22,204
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
462
Comments
1
Likes
19
Embeds 0
No embeds

No notes for slide

Transcript of "RESTful Web services using JAX-RS"

  1. 1. <Insert Picture Here>Developing RESTful Web services with JAX-RSArun Gupta, Java EE & GlassFish Guyblogs.oracle.com/arungupta, @arungupta
  2. 2. The following/preceding is intended to outline ourgeneral product direction. It is intended forinformation purposes only, and may not beincorporated into any contract. It is not acommitment to deliver any material, code, orfunctionality, and should not be relied upon inmaking purchasing decisions.The development, release, and timing of anyfeatures or functionality described for Oracle’sproducts remains at the sole discretion of Oracle. 2
  3. 3. REST is an Architectural Style Style of software architecture fordistributed hypermedia systems such as World Wide Web 3
  4. 4. RESTful Web ServicesApplication of REST architectural style to services that utilize Web standards(URIs, HTTP, HTML, XML, Atom, RDF etc.) 4
  5. 5. Java API for RESTful Web Services(JAX-RS) Standard annotation-driven API thataims to help developers build RESTful Web services in Java 5
  6. 6. 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 6
  7. 7. Principles of REST• Give everything an ID• Standard set of methods• Link things together• Multiple representations• Stateless communications 7
  8. 8. 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 8
  9. 9. 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 9
  10. 10. Resources are identified by URIs@Path("orders/{order_id}")public class OrderResource { @GET @Path("customer") Customer getCustomer(@PathParam(“order_id”)int id { … }} 10
  11. 11. Standard Set of MethodsMethod Purpose AnnotationGET Read, possibly cached @GETPOST Update or create without a known ID @POSTPUT Update or create with a known ID @PUTDELETE Remove @DELETEHEAD GET with no response @HEADOPTIONS Supported methods @OPTIONS 11
  12. 12. 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 12
  13. 13. 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) {...}} 13
  14. 14. Binding Request to ResourceAnnotation Sample@PathParam Binds the value from URI, e.g. @PathParam(“id”)@QueryParam Binds the value of query name/value, e.g. @QueryParam(“name”)@CookieParam Binds the value of a cookie, e.g. @CookieParam(“JSESSIONID”)@HeaderParam Binds the value of a HTTP header , e.g. @HeaderParam("Accept")@FormParam Binds the value of an HTML form, e.g. @FormParam(“name”)@MatrixParam Binds the value of a matrix parameter, e.g. @MatrixParam(“name”) 14
  15. 15. Multiple Representations• Offer data in a variety of formats • XML • JSON • (X)HTML• Maximize reach• Support content negotiation • Accept header GET /foo Accept: application/json • URI-based GET /foo.json 15
  16. 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 16
  17. 17. Multiple Representations• Static - Annotate methods or classes with static capabilities • @Produces, @Consumes• Dynamic - Use Variant, VariantListBuilder and Request.selectVariant for dynamic capabilities 17
  18. 18. Content Negotiation: Accept HeaderAccept: application/xmlAccept: application/json;q=1.0, text/xml;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) { ...} 18
  19. 19. Content Negotiation: URL-based@Path("/orders")public class OrderResource { @Path("{orderId}.xml") @Produces(“application/xml”) @GET public Order getOrderInXML(@PathParam("orderId") StringorderId) { . . . } @Path("{orderId}.json") @Produces(“application/json”) @GET public Order getOrderInJSON(@PathParam("orderId") StringorderId) { . . . }} 19
  20. 20. JAX-RS 1.1Code Sampleimport javax.inject.Inject;import javax.enterprise.context.RequestScoped;@RequestScopedpublic class ActorResource { @Inject DatbaseBean db; public Actor getActor(int id) { return db.findActorById(id); }} 20
  21. 21. Content Negotiationimport 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}")@RequestScopedpublic class ActorResource { @Inject DatbaseBean db; @GET @Produces("application/json") public Actor getActor(@PathParam("id") int id) { return db.findActorById(id); }} http://blogs.oracle.com/arungupta/entry/totd_124_using_cdi_jpa 21
  22. 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> 22
  23. 23. Responses Contain LinksHTTP/1.1 201 CreatedDate: Wed, 03 Jun 2009 16:41:58 GMTServer: Apache/1.3.6Location: http://example.com/properties/fooContent-Type: application/order+xmlContent-Length: 184<property self="http://example.com/properties/foo"> <parent ref="http://example.com/properties/bar"/> <name>Foo</name> <value>1</value></order> 23
  24. 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 24
  25. 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); 25
  26. 26. Stateless Communications• Long lived identifiers• Avoid sessions• Everything required to process a request contained in the request 26
  27. 27. JAX-RS 1.1 More Code Samples• Processing POSTed HTMLForm@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) { ...} 27
  28. 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> 28
  29. 29. Mapping Application Exceptions • Map checked or runtime exception to Responsepublic class OrderNotFoundException extends RuntimeException { public OrderNotFoundException(int id) super(id + " order not found"); }} @Path("{id}") public Order getOrder(@PathParam("id")int id) { Order order = null; . . . return order; if (order == null) throw new OrderNotFoundException(id); } 29
  30. 30. Mapping Application Exceptions@Providerpublic class OrderNotFoundExceptionMapper implementsExceptionMapper<OrderNotFoundException> { @Override public Response toResponse(OrderNotFoundException exception){ return Response .status(Response.Status.PRECONDITION_FAILED) .entity("Response not found") .build(); }} 30
  31. 31. JAX-RS Summary• Java API for building RESTful Web Services• POJO based• Annotation-driven• Server-side API• HTTP-centric 31
  32. 32. 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 @Singletonpublic 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; }} 32
  33. 33. 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 33
  34. 34. JAX-RS 1.1 Jersey Client API – Code SampleClient client = Client.create();WebResource resource = client.resource(“...”);//curl http://example.com/baseString s = resource.get(String.class);//curl -HAccept:text/plain http://example.com/baseString s = resource. accept(“text/plain”). get(String.class);http://blogs.oracle.com/enterprisetechtips/entry/consuming_restful_web_services_with 34
  35. 35. JAX-RS 1.1Jersey Client API – NetBeans Code Generation 35
  36. 36. 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:37AM"/> <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> 36
  37. 37. 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 37
  38. 38. Example Java SE DeploymentApplication app = ...RuntimeDelegate rd = RuntimeDelegate.getInstance();Adapter a = rd.createEndpoint(app, Adapter.class);SelectorThread st = GrizzlyServerFactory.create( “http://127.0.0.1:8084/”, a); 38
  39. 39. 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 39
  40. 40. 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: Future<?> • 2.0 M3 Available• Implementations • Apache CXF, Apache Wink, eXo, Jersey, RESTEasy, Restlet, Triaxrs 40 40
  41. 41. 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 41
  42. 42. JAX-RS 2.0 (JSR 339) http://jcp.org/en/jsr/detail?id=339 http://jax-rs-spec.java.net● 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. 43. References• oracle.com/javaee• glassfish.org• oracle.com/goto/glassfish• blogs.oracle.com/theaquarium• youtube.com/GlassFishVideos• Follow @glassfish 43
  44. 44. <Insert Picture Here>Developing RESTful Web services with JAX-RSArun Gupta, Java EE & GlassFish Guyblogs.oracle.com/arungupta, @arungupta
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×