JAX RS Developing RESTful Applications
JERRY KURIAN. OVER 20 YEARS EXPERIENCE. TECHNOLOGY INNOVATOR & ENTREPRENEUR Started coding with an Intel 486 machine more than 25 years back and enjoying it ever since. Developed using VB, Pascal, C++, Java Enterprise and OSS, Scala, Node JS and the saga continues. Started using Spring, hibernate before it became hip. Started using Scala when it was in its infancy. After spending 8 years working in various software companies like Huawei Tech, Quidnunc across UK, US, China and India, the entrepreneurship bug bit in 2006 (before it was hip!!). Built one of the pioneers in SMS social network called CellZapp, I developed the product on my own and sold it to marquee customers like ESPN and Hungama Digital. Recently launched a product in field informatics www.isense-tech.co.in. Successfully launched across 3 pilot customers and on track to sign up more. A family man with two kids, I am a passionate weekend cricketer and an involved dad. I urge my two sons to follow their dreams, which they do by staying out of the conventional schooling system and exploring their passion at a democratic free school called BeMe. Check it out at http://beme.org.in
REFERENCES  RESTful Java with JAX-RS 2.0, 2nd Edition  https://www.safaribooksonline.com/library/view/restful- java-with/9781449361433/
WHY REST?  Web is one of the most successful “app” out there  The web has grown exponentially and shows no sign of stopping  All apps need to learn and adopt from the underlying architectural principles of the web to be able to grow similarly  The set of these architectural principles is called REpresentational State Transfer (REST)
REST PRINCIPLE  Addressable resources  The key abstraction of information and data in REST is a resource, and each resource must be addressable via a URI (Uniform Resource Identifier).  A uniform, constrained interface  Use a small set of well-defined methods to manipulate your resources.  Representation-oriented  You interact with services using representations of that service. For example, browsers need HTML, JavaScript needs JSON.  Communicate statelessly  Stateless applications are easier to scale.  Hypermedia As The Engine Of Application State (HATEOAS  Let your data formats drive state transitions in your applications.
ADDRESSABILITY  Addressability is the idea that every object and resource in your system is reachable through a unique identifier.  For an SOA, the means to discover a service or resource is a big problem and addressability through an identifier is an ideal solution  In the REST world, addressability is managed through the use of URIs  scheme://host:port/path?queryString#fragment
UNIFORM INTERFACE VIA HTTP  REST isn’t protocol specific  But REST over HTTP is the most common way in which REST applications are developed  There have been other specifications that have enabled distributed application development over web  WS-* and SOAP have been most popular. It also used HTTP but more as a transport later to bypass the firewalls  REST uses HTTP as a very rich application protocol that provides multitude of interesting and useful capabilities for application developers
HTTP http://www.cs.brandeis.edu/~rshaull/cs146a/project2/proxy-diagram.png
HTTP - METHODS http://www.bogotobogo.com/python/images/python_http_web_services/HttpRequest.png Browsers are one of the most well known users of HTTP protocol. But they generally restrict themselves to GET and POST methods
HTTP - METHODS  GET  GET is a read-only operation. It is used to query the server for specific information. It is both an idempotent and safe operation  PUT  PUT requests that the server store the message body sent with the request under the location provided in the HTTP message. It is usually modelled as an insert or update. It is also idempotent.  DELETE  DELETE is used to remove resources. It is idempotent as well.  POST  POST is the only non-idempotent and unsafe operation of HTTP. Each POST method is allowed to modify the service in a unique way.  HEAD  HEAD is exactly like GET except that instead of returning a response body, it returns only a response code and any headers associated with the request.  OPTIONS  OPTIONS is used to request information about the communication options of the resource you are interested in. Idempotent means that no matter how many times you apply the operation, the result is always the same
REPRESENTATION ORIENTATION  With a GET operation, you receive a representation of the current state of a resource.  A PUT or POST passes a representation of the resource to the server so that the underlying resource’s state can change  In a RESTful system, the complexity of the client- server interaction is within the representations being passed back and forth. These representations could be XML, JSON, YAML, or really any format you can come up with.
HATEOAS  The final principle of REST is the idea of using Hypermedia As The Engine Of Application State (HATEOAS).  Hypermedia and Hyperlinks compose complex sets of information from disparate sources. <order id="111"> <customer>http://customers.myintranet.com/customers/32133</customer> <order-entries> <order-entry> <quantity>5</quantity> <product>http://products.myintranet.com/products/111</product>
DEVELOPING A RESTFUL JAVA APP  For a Java programmer, the ideal scenario is to ensure they stick to Java as much as possible  As with frameworks and specs like Hibernate and JPA, which bridges the Relational database world with Java world, we need a way to do REST programming using mainly Java constructs  The steps to developing RESTful application are as follows
STEPS TO DEVELOPING RESTFUL APPS Define object model Model the URIs Define representation format Assign HTTP methods
DEFINE OBJECT MODEL  Developing enterprise applications often start with defining its object model  The object model defined for an application can be used to define the various resources in our RESTful application too  Consider a typical Order entry system.  Each order in the system represents a single transaction or purchase and is associated with a particular customer. Orders are made up of one or more line items. Line items represent the type and number of each product purchased.
OBJECT MODEL  Based on the system description the object model could be
MODEL THE URIS  Java addresses a class or an entity via its package and class name  This format is well known within a JVM for a class to access another class  How do you make a Java class representing a resource be known and accessible over the web?  The answer lies in providing a URI for the java based resources
URIS  In our object model, we will be interacting with Orders, Customers, and Products  We can make these resources addressable as follows  /orders  /orders/{id}  /products  /products/{id}  /customers  /customers/{id}
DEFINE REPRESENTATIONAL DATA FORMAT  Within JVM, two objects talk to each other through the state of the object or by serializing/de-serializing object over the wire  How can the state of a Java object be made known to a client over the web?  The representation of the state of a resource is one of the most important things to do in a RESTful application  XML and JSON are two of the most popular way to represent the resource states
XML BASED REPRESENTATION Read or update operation
XML BASED REPRESENTATION Create Operation
ASSIGNING HTTP METHODS  The URIs defined earlier are a means to access as well as perform operations on the resources  A client typically would want to perform CRUD operations on the resources  To obtain all the products, you would typically define GET method on the URI  GET /products HTTP/1.1  To limit the number of products returned, we can pass the limiting parameters as query parameters  GET /products?startIndex=0&size=5 HTTP/1.1
HTTP METHODS  To obtain an individual product, the GET operation would be defined as  /products/{id}  GET /products/233 HTTP/1.1  To create a new product, use the PUT operation  PUT /products/664 HTTP/1.1  Drawback of using PUT is that the client is expected to generate the ID of the new resource  POST can also be used to create a new resource
HTTP METHODS  Updating a resource can be achieved via a PUT method  To delete a resource, use the DELETE method  DELETE /orders/233  Cancellation of a resource is also update of a state and can be achieved through DELETE with specific query parameter  DELETE /orders/233?cancel=true
OPERATIONS ON RESOURCES  We might need to perform operations on resources that do not strictly result in update of resource states  Eg of an operation would be purging of a resources, which ultimately updates states of multiple resources  We can model operations as sub-resources and trigger a POST operation  POST /orders/purge HTTP/1.1  The sub-resource URI can be further extended to add interfaces as desired
DEVELOP A SAMPLE RESTFUL APPLICATION
FIRST APPLICATION  Create the model class  Define service  Define Path and parameters  Create the Application class  Deploy  Test Using Browser
HTTP METHODS AND URI MATCHING
JAX RS ANNOTATIONS FOR HTTP METHODS  As seen in the examples, the JAX-RS API defines support for various HTTP methods through annotations  The annotations supported are  @javax.ws.rs.GET  @javax.ws.rs.PUT  @javax.ws.rs.POST  @javax.ws.rs.HEAD  @javax.ws.rs.DELETE
BINDING URIS  The resources need to be addressed in a way that is accessible over the web  The path to the resource is annotated using  @javax.ws.rs.Path  For a Java class to be eligible to receive any HTTP requests, the class must be annotated with at least the @Path("/") expression  The value of the @Path annotation is an expression that denotes a relative URI to the context root of your JAX-RS application
BINDING OPERATIONS  @Path can also be applied to the java operations  The URI matching pattern is a concatenation of the class’s @Path expression and that of the method’s  The URI pattern for getUnpaidOrders() would be the relative URI /orders/unpaid
@PATH EXPRESSIONS  @Path annotations support complex expressions  /customers/200 will match the path for method getCustomer. While /customers/foo-bar will match following
REGULAR EXPRESSIONS  The .+ is a regular expression that will match any stream of characters after /customers  The getAddress() method has a more specific expression. Will map any characters after/customers that ends with /address. The GET /customers/foo/bar/address request would route to the getAddress() method
SUBRESOURCE LOCATORS  JAX-RS also allows you to dynamically dispatch requests yourself through subresource locators  Subresource locators are Java methods annotated with @Path, without HTTP method annotation  This returns a JAX-RS annotated service which dispatches the remaining request  Dispatches URI pattern /customers/{database}- db/{customerId}
JAX-RS INJECTION
ACQUIRING DATA  Every service requires a way to acquire data being sent by the client and respond appropriately  As seen earlier, the Jax RS services are normal classes with operations being implemented using the methods  There is a need to ensure that data passed by the client is receive by the appropriate methods  Jax RS provides various annotations that bind to input data and makes it available to methods
@PATHPARAM  @PathParam allows you to inject the value of named URI path parameters that were defined in @Path expressions
MATRIX PARAMS  There are times when you would want to pass an input attribute via the path of the URI instead of using the query params.  Such params passed via the pat are called Matrix Params  Example. GET /cars/mercedes/e55;color=black/2006  In the example, the attribute color is passed as a matrix parameter
MATRIX PARAM USING @PATH AND PATHSEGMENT
USING @MATRIXPARAM  JAX-RS specification allows you to inject matrix parameter values directly through the @javax.ws.rs.MatrixParam annotation
USING THE QUERY STRING - @QUERYPARAM  Generally attributes to a web resources are passed using the Query String of the HTTP protocol  The @javax.ws.rs.QueryParam annotation allows you to inject individual URI query parameters into your Java parameter  GET /customers?start=0&size=10
INJECTING VIA FORM ELEMENT - @FORMPARAM  The @javax.ws.rs.FormParam annotation is used to access application/x-www-form-url encoded request bodies
@HEADERPARAM  The @javax.ws.rs.HeaderParam annotation is used to inject HTTP request header values.  You could access the HTTP Referer header using the @HeaderParam annotation
RAW HEADERS  In case you need access to all the headers passed in by the request, then it can be accessed via HttpHeaders object set via @Context
@COOKIEPARAMS  HTTP is stateless, but many applications might require a state to be maintained  Maintaining states is accomplished via tools like  Sessions  Cookies  If a client app stores info in a cookie then it is also responsible to send the data via request headers  @CookieParams annotation allows service to access data
AUTOMATIC TYPE CONVERSION  Although, data sent via HTTP is usually represented as String, the java method can receive the data in specific type  JAX-RS converts String into desired type as long as the type conversion matches following criteria 1. The desired type is a primitive value 2. The desired type is a Java class with a constructor that takes a single String as input 3. The desired type is a java class that has a static method named valueOf() that takes a single String argument and returns an instance of the class 4. It is a java.util.List<T>, java.util.Set<T>, or java.util.SortedSet<T>, where T is a type that satisfies criteria 2 or 3
COLLECTION OF PARAMETERS  The client can pass a parameter multiple times, in case there are multiple values to the parameter  GET /customers?orderBy=last&orderBy=first  JAX-RS provider represents these two parameters as a java.util.List and injects this list with one @QueryParam annotation
DEFAULT VALUE  Many times the client may not have value for a specific param and may not pass it  This makes the value null. The null value may cause problems to the service  A default value can be set in such cases
ENCODED VALUES  By default, JAX-RS decodes the input values before converting them into Java types  If you wish to make use of the raw encoded values, then it is possible via @Encoded annotation
JAX-RS CLIENT API
WRITING RESTFUL CLIENTS  One of the major challenges in working with a REST application is writing a client app  Most of the annotations defined earlier are for creating a RESTful service  For writing clients, there are two options  Develop client app using java.net.URL or Apache HTTP Client  Use JAX-RS API Client API, which makes working with Jax RS much simpler
USING JERSEY FOR DEVELOPING CLIENT  The Jersey based implementation can be used for writing JAX-RS 2 clients  Add the following dependency in pom.xml to make use of the library <dependencies> <dependency> <groupId>org.glassfish.jersey.core</groupId> <artifactId>jersey-client</artifactId> <version>2.23.2</version> </dependency> </dependencies>
CREATING A CLIENT  API provides a class called javax.ws.rs.client.Client which represents a JAX-RS client  Create a new Client object using ClientBuilder  Client client = ClientBuilder.newClient();  Create the invocation target  WebTarget target = client.target("http://localhost:8080/SecondApp/services/c ustomers/eg;color=black/2000");  Send a GET request  Response response = target.request().get();  Analyze the response  response.readEntity(String.class)  Close the resources  response.close()  client.close()
WEBTARGET  The WebTarget interface represents a specific URI you want to invoke on.  Some of the important methods it provides are
WEBTARGET  Request invoker can be obtained from the Webtarget via its request methods  Invocation.Builder allows setting up of different types of headers
JAX-RS CONTENT HANDLING
NEED FOR CONTENT TRANSFORMATION  Aim of a Java developer is to deal with Java object as much as possible  RESTful services often represent data in the form of XML or JSON  There is a need to seamlessly convert from the raw XML or JSON format to Java object format so that the developers can handle it easily
BUILT-IN CONTENT MARSHALLING  StreamingOutput is a simple callback interface that you implement when you want to do raw streaming of response bodies
READING DATA  For reading request message bodies, you can use a raw InputStream or Reader for inputting any media type
RECEIVING OR RETURNING FILES  Instances of java.io.File can also be used for input and output of any media type.
JAXB  JAXB is a specification defined to map Java classes to XML  JAX-RS has built in support for JAXB
JAXB JAX-RS HANDLERS  JAX-RS spec is required to marshall and un- marshall JAXB objects
CUSTOM MARSHALLING  In case where there is no direct support for marshalling and unmarshalling of JAXB objects, JAX-RS supports creating custom marshallers  The interface to be implemented are  MessageBodyWriter  MessageBodyReader
IMPLEMENTING A MESSAGEBODYREADER  An implementation needs to be annotated with @Provider and @Consumes
PASSING OBJECTS FROM CLIENT  JAX-RS client implementation environment may not have in-built support for JAXB transformation  In such cases it is required that the MessageBodyReader and MessageBodyWriter is implemented  To make the class usable, it needs to be registered with the WebTarget  WebTarget target = client.target("http://localhost:8080/SecondApp/services/ customers").register(CustomerReader.class).register (CustomerWriter.class)
SERVER RESPONSES AND EXCEPTIONS
SUCCESSFUL RESPONSES  Successful HTTP response code numbers range from 200 to 399  If a service returns null or empty body, then the response code will be 204, “No Content”
ERROR RESPONSE  Standard HTTP error response code numbers range from 400 to 599  If the client provides a URI that is not found then the response code will be 404, “Not Found,”  If a client requests text/html response for a resource URI that is not returning anything then the status code will be 406, “Not Acceptable,  If the client invokes an HTTP method on a valid URI to which no JAX-RS resource method is bound, the JAX-RS runtime will send an error code of 405, “Method Not Allowed.”  Example, issuing PUT request to a resource that supports only POST
COMPLEX RESPONSE  For the cases where you need to control the response, your JAX-RS resource methods can return instances of javax.ws.rs.core.Response  A ResponseBuilder can be used to construct a Response
EXCEPTION HANDLING  Errors can be reported to a client either by creating and returning the appropriate Response object or by throwing an exception  JAX-RS provides the javax.ws.rs.WebApplicationException. This can be thrown by application code and automatically processed by JAX-RS  A Response object can be set in the exception object which will be returned by JAX-RS service to the client  If there is no Response object set then the server returns 500, “Internal Server Error,”
SECURING YOUR SERVICES
SECURING APPLICATIONS  Authentication  Authentication is about validating the identity of a client that is trying to access your services.  Authorization  Authorization is about deciding whether or not a certain user is allowed to access and invoke on a specific URI  Encryption  Sensitive data should be protected with cryptographic services like SSL
BASIC AUTHENTICATION  Basic Authentication is the simplest protocol available for performing authentication over HTTP  It involves sending a Base 64–encoded username and password within a request header to the server  If invoking a secure resource  GET /customers/333 HTTP/1.1  Pass Base 64 encoded username and password in header username:password  This has to be passed in every request  Prone to hostile interception
AUTHORIZATION  While authentication is about establishing and verifying user identity, authorization is about permissions.  Authorization requires users to have one or more roles  Roles need to be assigned permissions to perform operations
AUTHORIZATION USING JAX-RS  Authentication and Authorization in JAX-RS can be enabled either using web.xml or via Annotations  JAX-RS defines following annotations  @RolesAllowed – Lists the roles that are allowed access  @DenyAll – Denies access to all roles  @PermitAll – Allows all roles
ENABLING AUTHORIZATION  For the server to check for authorization, you need to register certain interceptors  The interceptors are specific to the implementation  Jboss Resteasy expects you to register a @Provider that is a PreProcessInterceptor  The Pre-Processor should be registered with the Application
HATEOAS
THE WEB PARADIGM  The Internet is commonly referred to as “the Web” because information is connected together through a series of hyperlinks embedded within HTML documents  The architectural principle that describes linking and form submission is called HATEOAS  HATEOAS stands for Hypermedia As The Engine Of Application State
IMPLEMENTING HATEOAS  Most XML-based RESTful applications use syntax from the Atom Syndication Format as a means to implement HATEOAS
ATOM LINKS  Atom links have some key attributes  rel  It is the logical, simple name used to reference the link  href  This is the URL you can traverse in order to get new information or change the state of your application.  type  This is the exchanged media type of the resource the URL points to  hreflang  Represents the language the data format is translated into.
HATEOAS AND JAX-RS  HATEOAS is to be defined by the application, so JAX-RS restricts itself to some helper methods to construct the links
BUILD FROM PATH  Given a path, the builder can help create a URI  This would result in a URI  http://example.com/customers/333?param=value
BUILD FROM RESOURCE  Given a REST resource, you can build a URI
SCALING JAX-RS APPLICATIONS
CACHING  Caching is one of the most powerful technique to improve performance  Any service that provides static unchanging data is an obvious candidate for caching  Browser knows when to cache using the response header called Expires
JAX-RS AND CACHING  JAX-RS services can specify expires header using Response
CACHECONTROL  JAX-RS also provides a CacheControl class to control the cache settings
CONCURRENCY  In a highly concurrent RESTful application, care should be taken that the a resource is not getting updated with invalid data  This can happen if a client has obtained a resource with a particular state and before making the update, some other client updates the data  This problem can be overcome using conditional PUT or POST
CONDITIONAL UPDATE  A client receives a GET response with its Etag and Last-Modified headers set  When performing conditional PUT or POST, the request should have If-Match or If-Unmodified- Since header
CONDITIONAL UPDATE WITH JAX-RS  To do conditional updates with JAX-RS, you use the Request.evaluatePreconditions() method
CONTENT NEGOTIATION
CONNEG  Clients set an Accept request header that is a comma-delimited list of preferred formats.  The client is asking the server for /stuff formatted in either XML or JSON. It can also specify wildcards  If the server is unable to provide the desired format, it will respond with a status code of 406, “Not Acceptable.”
JAX-RS AND CONNEG  JAX-RS does method dispatching based on the ACCEPT header values  JAX-RS can pick one of these methods based on what is in the Accept header
JAXB FOR CONNEG  You can implement one Java method that can service both formats  The method would return representation as per the ACCEPT header
INTEGRATIONS
EJB  Java EE requires that EJB containers support integration with JAX-RS  When manually registering your resources via your Application class, you must register the bean class of the EJB via the Application.getClasses() method.
EXAMPLE  Create an app with following features  Create a Product (Only allowed for Admin)  Place an Order.  Order Can include multiple Products  View Pending Order (Only allowed for Admin)  List All Customers  Also return the list of orders as HATEOAS

JAX-RS. Developing RESTful APIs with Java

  • 1.
  • 2.
    JERRY KURIAN. OVER20 YEARS EXPERIENCE. TECHNOLOGY INNOVATOR & ENTREPRENEUR Started coding with an Intel 486 machine more than 25 years back and enjoying it ever since. Developed using VB, Pascal, C++, Java Enterprise and OSS, Scala, Node JS and the saga continues. Started using Spring, hibernate before it became hip. Started using Scala when it was in its infancy. After spending 8 years working in various software companies like Huawei Tech, Quidnunc across UK, US, China and India, the entrepreneurship bug bit in 2006 (before it was hip!!). Built one of the pioneers in SMS social network called CellZapp, I developed the product on my own and sold it to marquee customers like ESPN and Hungama Digital. Recently launched a product in field informatics www.isense-tech.co.in. Successfully launched across 3 pilot customers and on track to sign up more. A family man with two kids, I am a passionate weekend cricketer and an involved dad. I urge my two sons to follow their dreams, which they do by staying out of the conventional schooling system and exploring their passion at a democratic free school called BeMe. Check it out at http://beme.org.in
  • 3.
    REFERENCES  RESTful Javawith JAX-RS 2.0, 2nd Edition  https://www.safaribooksonline.com/library/view/restful- java-with/9781449361433/
  • 4.
    WHY REST?  Webis one of the most successful “app” out there  The web has grown exponentially and shows no sign of stopping  All apps need to learn and adopt from the underlying architectural principles of the web to be able to grow similarly  The set of these architectural principles is called REpresentational State Transfer (REST)
  • 5.
    REST PRINCIPLE  Addressableresources  The key abstraction of information and data in REST is a resource, and each resource must be addressable via a URI (Uniform Resource Identifier).  A uniform, constrained interface  Use a small set of well-defined methods to manipulate your resources.  Representation-oriented  You interact with services using representations of that service. For example, browsers need HTML, JavaScript needs JSON.  Communicate statelessly  Stateless applications are easier to scale.  Hypermedia As The Engine Of Application State (HATEOAS  Let your data formats drive state transitions in your applications.
  • 6.
    ADDRESSABILITY  Addressability isthe idea that every object and resource in your system is reachable through a unique identifier.  For an SOA, the means to discover a service or resource is a big problem and addressability through an identifier is an ideal solution  In the REST world, addressability is managed through the use of URIs  scheme://host:port/path?queryString#fragment
  • 7.
    UNIFORM INTERFACE VIAHTTP  REST isn’t protocol specific  But REST over HTTP is the most common way in which REST applications are developed  There have been other specifications that have enabled distributed application development over web  WS-* and SOAP have been most popular. It also used HTTP but more as a transport later to bypass the firewalls  REST uses HTTP as a very rich application protocol that provides multitude of interesting and useful capabilities for application developers
  • 8.
  • 9.
    HTTP - METHODS http://www.bogotobogo.com/python/images/python_http_web_services/HttpRequest.png Browsersare one of the most well known users of HTTP protocol. But they generally restrict themselves to GET and POST methods
  • 10.
    HTTP - METHODS GET  GET is a read-only operation. It is used to query the server for specific information. It is both an idempotent and safe operation  PUT  PUT requests that the server store the message body sent with the request under the location provided in the HTTP message. It is usually modelled as an insert or update. It is also idempotent.  DELETE  DELETE is used to remove resources. It is idempotent as well.  POST  POST is the only non-idempotent and unsafe operation of HTTP. Each POST method is allowed to modify the service in a unique way.  HEAD  HEAD is exactly like GET except that instead of returning a response body, it returns only a response code and any headers associated with the request.  OPTIONS  OPTIONS is used to request information about the communication options of the resource you are interested in. Idempotent means that no matter how many times you apply the operation, the result is always the same
  • 11.
    REPRESENTATION ORIENTATION  Witha GET operation, you receive a representation of the current state of a resource.  A PUT or POST passes a representation of the resource to the server so that the underlying resource’s state can change  In a RESTful system, the complexity of the client- server interaction is within the representations being passed back and forth. These representations could be XML, JSON, YAML, or really any format you can come up with.
  • 12.
    HATEOAS  The finalprinciple of REST is the idea of using Hypermedia As The Engine Of Application State (HATEOAS).  Hypermedia and Hyperlinks compose complex sets of information from disparate sources. <order id="111"> <customer>http://customers.myintranet.com/customers/32133</customer> <order-entries> <order-entry> <quantity>5</quantity> <product>http://products.myintranet.com/products/111</product>
  • 13.
    DEVELOPING A RESTFULJAVA APP  For a Java programmer, the ideal scenario is to ensure they stick to Java as much as possible  As with frameworks and specs like Hibernate and JPA, which bridges the Relational database world with Java world, we need a way to do REST programming using mainly Java constructs  The steps to developing RESTful application are as follows
  • 14.
    STEPS TO DEVELOPINGRESTFUL APPS Define object model Model the URIs Define representation format Assign HTTP methods
  • 15.
    DEFINE OBJECT MODEL Developing enterprise applications often start with defining its object model  The object model defined for an application can be used to define the various resources in our RESTful application too  Consider a typical Order entry system.  Each order in the system represents a single transaction or purchase and is associated with a particular customer. Orders are made up of one or more line items. Line items represent the type and number of each product purchased.
  • 16.
    OBJECT MODEL  Basedon the system description the object model could be
  • 17.
    MODEL THE URIS Java addresses a class or an entity via its package and class name  This format is well known within a JVM for a class to access another class  How do you make a Java class representing a resource be known and accessible over the web?  The answer lies in providing a URI for the java based resources
  • 18.
    URIS  In ourobject model, we will be interacting with Orders, Customers, and Products  We can make these resources addressable as follows  /orders  /orders/{id}  /products  /products/{id}  /customers  /customers/{id}
  • 19.
    DEFINE REPRESENTATIONAL DATAFORMAT  Within JVM, two objects talk to each other through the state of the object or by serializing/de-serializing object over the wire  How can the state of a Java object be made known to a client over the web?  The representation of the state of a resource is one of the most important things to do in a RESTful application  XML and JSON are two of the most popular way to represent the resource states
  • 20.
    XML BASED REPRESENTATION Reador update operation
  • 21.
  • 22.
    ASSIGNING HTTP METHODS The URIs defined earlier are a means to access as well as perform operations on the resources  A client typically would want to perform CRUD operations on the resources  To obtain all the products, you would typically define GET method on the URI  GET /products HTTP/1.1  To limit the number of products returned, we can pass the limiting parameters as query parameters  GET /products?startIndex=0&size=5 HTTP/1.1
  • 23.
    HTTP METHODS  Toobtain an individual product, the GET operation would be defined as  /products/{id}  GET /products/233 HTTP/1.1  To create a new product, use the PUT operation  PUT /products/664 HTTP/1.1  Drawback of using PUT is that the client is expected to generate the ID of the new resource  POST can also be used to create a new resource
  • 24.
    HTTP METHODS  Updatinga resource can be achieved via a PUT method  To delete a resource, use the DELETE method  DELETE /orders/233  Cancellation of a resource is also update of a state and can be achieved through DELETE with specific query parameter  DELETE /orders/233?cancel=true
  • 25.
    OPERATIONS ON RESOURCES We might need to perform operations on resources that do not strictly result in update of resource states  Eg of an operation would be purging of a resources, which ultimately updates states of multiple resources  We can model operations as sub-resources and trigger a POST operation  POST /orders/purge HTTP/1.1  The sub-resource URI can be further extended to add interfaces as desired
  • 26.
    DEVELOP A SAMPLERESTFUL APPLICATION
  • 27.
    FIRST APPLICATION  Createthe model class  Define service  Define Path and parameters  Create the Application class  Deploy  Test Using Browser
  • 28.
    HTTP METHODS ANDURI MATCHING
  • 29.
    JAX RS ANNOTATIONSFOR HTTP METHODS  As seen in the examples, the JAX-RS API defines support for various HTTP methods through annotations  The annotations supported are  @javax.ws.rs.GET  @javax.ws.rs.PUT  @javax.ws.rs.POST  @javax.ws.rs.HEAD  @javax.ws.rs.DELETE
  • 30.
    BINDING URIS  Theresources need to be addressed in a way that is accessible over the web  The path to the resource is annotated using  @javax.ws.rs.Path  For a Java class to be eligible to receive any HTTP requests, the class must be annotated with at least the @Path("/") expression  The value of the @Path annotation is an expression that denotes a relative URI to the context root of your JAX-RS application
  • 31.
    BINDING OPERATIONS  @Pathcan also be applied to the java operations  The URI matching pattern is a concatenation of the class’s @Path expression and that of the method’s  The URI pattern for getUnpaidOrders() would be the relative URI /orders/unpaid
  • 32.
    @PATH EXPRESSIONS  @Pathannotations support complex expressions  /customers/200 will match the path for method getCustomer. While /customers/foo-bar will match following
  • 33.
    REGULAR EXPRESSIONS  The.+ is a regular expression that will match any stream of characters after /customers  The getAddress() method has a more specific expression. Will map any characters after/customers that ends with /address. The GET /customers/foo/bar/address request would route to the getAddress() method
  • 34.
    SUBRESOURCE LOCATORS  JAX-RSalso allows you to dynamically dispatch requests yourself through subresource locators  Subresource locators are Java methods annotated with @Path, without HTTP method annotation  This returns a JAX-RS annotated service which dispatches the remaining request  Dispatches URI pattern /customers/{database}- db/{customerId}
  • 35.
  • 36.
    ACQUIRING DATA  Everyservice requires a way to acquire data being sent by the client and respond appropriately  As seen earlier, the Jax RS services are normal classes with operations being implemented using the methods  There is a need to ensure that data passed by the client is receive by the appropriate methods  Jax RS provides various annotations that bind to input data and makes it available to methods
  • 37.
    @PATHPARAM  @PathParam allowsyou to inject the value of named URI path parameters that were defined in @Path expressions
  • 38.
    MATRIX PARAMS  Thereare times when you would want to pass an input attribute via the path of the URI instead of using the query params.  Such params passed via the pat are called Matrix Params  Example. GET /cars/mercedes/e55;color=black/2006  In the example, the attribute color is passed as a matrix parameter
  • 39.
    MATRIX PARAM USING@PATH AND PATHSEGMENT
  • 40.
    USING @MATRIXPARAM  JAX-RSspecification allows you to inject matrix parameter values directly through the @javax.ws.rs.MatrixParam annotation
  • 41.
    USING THE QUERYSTRING - @QUERYPARAM  Generally attributes to a web resources are passed using the Query String of the HTTP protocol  The @javax.ws.rs.QueryParam annotation allows you to inject individual URI query parameters into your Java parameter  GET /customers?start=0&size=10
  • 42.
    INJECTING VIA FORMELEMENT - @FORMPARAM  The @javax.ws.rs.FormParam annotation is used to access application/x-www-form-url encoded request bodies
  • 43.
    @HEADERPARAM  The @javax.ws.rs.HeaderParamannotation is used to inject HTTP request header values.  You could access the HTTP Referer header using the @HeaderParam annotation
  • 44.
    RAW HEADERS  Incase you need access to all the headers passed in by the request, then it can be accessed via HttpHeaders object set via @Context
  • 45.
    @COOKIEPARAMS  HTTP isstateless, but many applications might require a state to be maintained  Maintaining states is accomplished via tools like  Sessions  Cookies  If a client app stores info in a cookie then it is also responsible to send the data via request headers  @CookieParams annotation allows service to access data
  • 46.
    AUTOMATIC TYPE CONVERSION Although, data sent via HTTP is usually represented as String, the java method can receive the data in specific type  JAX-RS converts String into desired type as long as the type conversion matches following criteria 1. The desired type is a primitive value 2. The desired type is a Java class with a constructor that takes a single String as input 3. The desired type is a java class that has a static method named valueOf() that takes a single String argument and returns an instance of the class 4. It is a java.util.List<T>, java.util.Set<T>, or java.util.SortedSet<T>, where T is a type that satisfies criteria 2 or 3
  • 47.
    COLLECTION OF PARAMETERS The client can pass a parameter multiple times, in case there are multiple values to the parameter  GET /customers?orderBy=last&orderBy=first  JAX-RS provider represents these two parameters as a java.util.List and injects this list with one @QueryParam annotation
  • 48.
    DEFAULT VALUE  Manytimes the client may not have value for a specific param and may not pass it  This makes the value null. The null value may cause problems to the service  A default value can be set in such cases
  • 49.
    ENCODED VALUES  Bydefault, JAX-RS decodes the input values before converting them into Java types  If you wish to make use of the raw encoded values, then it is possible via @Encoded annotation
  • 50.
  • 51.
    WRITING RESTFUL CLIENTS One of the major challenges in working with a REST application is writing a client app  Most of the annotations defined earlier are for creating a RESTful service  For writing clients, there are two options  Develop client app using java.net.URL or Apache HTTP Client  Use JAX-RS API Client API, which makes working with Jax RS much simpler
  • 52.
    USING JERSEY FORDEVELOPING CLIENT  The Jersey based implementation can be used for writing JAX-RS 2 clients  Add the following dependency in pom.xml to make use of the library <dependencies> <dependency> <groupId>org.glassfish.jersey.core</groupId> <artifactId>jersey-client</artifactId> <version>2.23.2</version> </dependency> </dependencies>
  • 53.
    CREATING A CLIENT API provides a class called javax.ws.rs.client.Client which represents a JAX-RS client  Create a new Client object using ClientBuilder  Client client = ClientBuilder.newClient();  Create the invocation target  WebTarget target = client.target("http://localhost:8080/SecondApp/services/c ustomers/eg;color=black/2000");  Send a GET request  Response response = target.request().get();  Analyze the response  response.readEntity(String.class)  Close the resources  response.close()  client.close()
  • 54.
    WEBTARGET  The WebTargetinterface represents a specific URI you want to invoke on.  Some of the important methods it provides are
  • 55.
    WEBTARGET  Request invokercan be obtained from the Webtarget via its request methods  Invocation.Builder allows setting up of different types of headers
  • 56.
  • 57.
    NEED FOR CONTENTTRANSFORMATION  Aim of a Java developer is to deal with Java object as much as possible  RESTful services often represent data in the form of XML or JSON  There is a need to seamlessly convert from the raw XML or JSON format to Java object format so that the developers can handle it easily
  • 58.
    BUILT-IN CONTENT MARSHALLING StreamingOutput is a simple callback interface that you implement when you want to do raw streaming of response bodies
  • 59.
    READING DATA  Forreading request message bodies, you can use a raw InputStream or Reader for inputting any media type
  • 60.
    RECEIVING OR RETURNINGFILES  Instances of java.io.File can also be used for input and output of any media type.
  • 61.
    JAXB  JAXB isa specification defined to map Java classes to XML  JAX-RS has built in support for JAXB
  • 62.
    JAXB JAX-RS HANDLERS JAX-RS spec is required to marshall and un- marshall JAXB objects
  • 63.
    CUSTOM MARSHALLING  Incase where there is no direct support for marshalling and unmarshalling of JAXB objects, JAX-RS supports creating custom marshallers  The interface to be implemented are  MessageBodyWriter  MessageBodyReader
  • 64.
    IMPLEMENTING A MESSAGEBODYREADER An implementation needs to be annotated with @Provider and @Consumes
  • 65.
    PASSING OBJECTS FROMCLIENT  JAX-RS client implementation environment may not have in-built support for JAXB transformation  In such cases it is required that the MessageBodyReader and MessageBodyWriter is implemented  To make the class usable, it needs to be registered with the WebTarget  WebTarget target = client.target("http://localhost:8080/SecondApp/services/ customers").register(CustomerReader.class).register (CustomerWriter.class)
  • 66.
  • 67.
    SUCCESSFUL RESPONSES  SuccessfulHTTP response code numbers range from 200 to 399  If a service returns null or empty body, then the response code will be 204, “No Content”
  • 68.
    ERROR RESPONSE  StandardHTTP error response code numbers range from 400 to 599  If the client provides a URI that is not found then the response code will be 404, “Not Found,”  If a client requests text/html response for a resource URI that is not returning anything then the status code will be 406, “Not Acceptable,  If the client invokes an HTTP method on a valid URI to which no JAX-RS resource method is bound, the JAX-RS runtime will send an error code of 405, “Method Not Allowed.”  Example, issuing PUT request to a resource that supports only POST
  • 69.
    COMPLEX RESPONSE  Forthe cases where you need to control the response, your JAX-RS resource methods can return instances of javax.ws.rs.core.Response  A ResponseBuilder can be used to construct a Response
  • 70.
    EXCEPTION HANDLING  Errorscan be reported to a client either by creating and returning the appropriate Response object or by throwing an exception  JAX-RS provides the javax.ws.rs.WebApplicationException. This can be thrown by application code and automatically processed by JAX-RS  A Response object can be set in the exception object which will be returned by JAX-RS service to the client  If there is no Response object set then the server returns 500, “Internal Server Error,”
  • 71.
  • 72.
    SECURING APPLICATIONS  Authentication Authentication is about validating the identity of a client that is trying to access your services.  Authorization  Authorization is about deciding whether or not a certain user is allowed to access and invoke on a specific URI  Encryption  Sensitive data should be protected with cryptographic services like SSL
  • 73.
    BASIC AUTHENTICATION  BasicAuthentication is the simplest protocol available for performing authentication over HTTP  It involves sending a Base 64–encoded username and password within a request header to the server  If invoking a secure resource  GET /customers/333 HTTP/1.1  Pass Base 64 encoded username and password in header username:password  This has to be passed in every request  Prone to hostile interception
  • 74.
    AUTHORIZATION  While authenticationis about establishing and verifying user identity, authorization is about permissions.  Authorization requires users to have one or more roles  Roles need to be assigned permissions to perform operations
  • 75.
    AUTHORIZATION USING JAX-RS Authentication and Authorization in JAX-RS can be enabled either using web.xml or via Annotations  JAX-RS defines following annotations  @RolesAllowed – Lists the roles that are allowed access  @DenyAll – Denies access to all roles  @PermitAll – Allows all roles
  • 76.
    ENABLING AUTHORIZATION  Forthe server to check for authorization, you need to register certain interceptors  The interceptors are specific to the implementation  Jboss Resteasy expects you to register a @Provider that is a PreProcessInterceptor  The Pre-Processor should be registered with the Application
  • 77.
  • 78.
    THE WEB PARADIGM The Internet is commonly referred to as “the Web” because information is connected together through a series of hyperlinks embedded within HTML documents  The architectural principle that describes linking and form submission is called HATEOAS  HATEOAS stands for Hypermedia As The Engine Of Application State
  • 79.
    IMPLEMENTING HATEOAS  MostXML-based RESTful applications use syntax from the Atom Syndication Format as a means to implement HATEOAS
  • 80.
    ATOM LINKS  Atomlinks have some key attributes  rel  It is the logical, simple name used to reference the link  href  This is the URL you can traverse in order to get new information or change the state of your application.  type  This is the exchanged media type of the resource the URL points to  hreflang  Represents the language the data format is translated into.
  • 81.
    HATEOAS AND JAX-RS HATEOAS is to be defined by the application, so JAX-RS restricts itself to some helper methods to construct the links
  • 82.
    BUILD FROM PATH Given a path, the builder can help create a URI  This would result in a URI  http://example.com/customers/333?param=value
  • 83.
    BUILD FROM RESOURCE Given a REST resource, you can build a URI
  • 84.
  • 85.
    CACHING  Caching isone of the most powerful technique to improve performance  Any service that provides static unchanging data is an obvious candidate for caching  Browser knows when to cache using the response header called Expires
  • 86.
    JAX-RS AND CACHING JAX-RS services can specify expires header using Response
  • 87.
    CACHECONTROL  JAX-RS alsoprovides a CacheControl class to control the cache settings
  • 88.
    CONCURRENCY  In ahighly concurrent RESTful application, care should be taken that the a resource is not getting updated with invalid data  This can happen if a client has obtained a resource with a particular state and before making the update, some other client updates the data  This problem can be overcome using conditional PUT or POST
  • 89.
    CONDITIONAL UPDATE  Aclient receives a GET response with its Etag and Last-Modified headers set  When performing conditional PUT or POST, the request should have If-Match or If-Unmodified- Since header
  • 90.
    CONDITIONAL UPDATE WITHJAX-RS  To do conditional updates with JAX-RS, you use the Request.evaluatePreconditions() method
  • 91.
  • 92.
    CONNEG  Clients setan Accept request header that is a comma-delimited list of preferred formats.  The client is asking the server for /stuff formatted in either XML or JSON. It can also specify wildcards  If the server is unable to provide the desired format, it will respond with a status code of 406, “Not Acceptable.”
  • 93.
    JAX-RS AND CONNEG JAX-RS does method dispatching based on the ACCEPT header values  JAX-RS can pick one of these methods based on what is in the Accept header
  • 94.
    JAXB FOR CONNEG You can implement one Java method that can service both formats  The method would return representation as per the ACCEPT header
  • 95.
  • 96.
    EJB  Java EErequires that EJB containers support integration with JAX-RS  When manually registering your resources via your Application class, you must register the bean class of the EJB via the Application.getClasses() method.
  • 97.
    EXAMPLE  Create anapp with following features  Create a Product (Only allowed for Admin)  Place an Order.  Order Can include multiple Products  View Pending Order (Only allowed for Admin)  List All Customers  Also return the list of orders as HATEOAS