Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

RESTing with JAX-RS

241 views

Published on

Introduction to building REST services using JAX-RS. First presented at the Lagos JUG event on 11/11/2017

Published in: Technology
  • Be the first to comment

RESTing with JAX-RS

  1. 1. RESTing with JAX-RS OKAFOR EZEWUZIE @dawuzi
  2. 2. About Me 1. Software Engineer at Seamfix Nigeria (www.seamfix.com) 2. JavaEE Enthusiast
  3. 3. What is REST (Representational State Transfer) 1. Web standards based architecture targeted at distributed hypermedia systems such as the World Wide Web 2. Introduced in the doctoral dissertation of Roy Fielding in 2000 (One of the principal authors of the HTTP specification) 3. Describes how resources are defined and accessed 4. Makes use of several web standards (HTTP, URI, Resource Representations etc)
  4. 4. Some REST Principles 1. All identifiable resources should have an ID 2. Use links to refer to those resources 3. Resources should be accessible via standard (HTTP) methods eg POST, GET, PUT, 4. Resources should have multiple representations 5. Stateless communication (Err not really. Just that state should be at the client side)
  5. 5. Brief Intro to HTTP Methods 1. GET : Used for requesting for resources (Safe to call i.e should not modify any resource) 2. POST: Used for creating resource 3. PUT: Used for updating resources (Idempotent ) 4. DELETE: Used for deleting resources (Idempotent)
  6. 6. Top REST Java frameworks 1. Dropwizard 2. Play Framework 3. RESTEasy 4. Restlet 5. Spark Framework 6. Spring Boot
  7. 7. JAX-RS Introduction 1. Java API for RESTful Web Services (JAX-RS) 2. Java spec that aids creating Web services based on the REST architecture 3. Java annotations based
  8. 8. JAX-RS Brief History 1. JAX-RS 1.0 in 2008 2. JAX-RS 1.1 in 2009. Added to the JavaEE 6. 3. JAX-RS 2.0 in 2014. JavaEE 7. (Client API, Bean validation, Async Processing) 4. JAX-RS 2.1 in Sept 2017. JavaEE 8. (Non-blocking IO, Reactive clients, Server Sent Events)
  9. 9. Common JAX-RS Annotations ● @ApplicationPath : Identifies the application path that serves as the base URI for all resource URIs. ● @Path ● @GET, @POST, @PUT, @DELETE. This maps to the corresponding HTTP methods ● @Produces (used to specify the MIME media types or representations a resource)
  10. 10. Common JAX-RS Annotations (Continued) ● @Consumes (used to specify which MIME media types of representations a resource can accept) ● @*Param eg @PathParam, @HeaderParam, @CookieParam, @QueryParam @BeanParam (used for retrieving request parameters) ● @Context : Used for injecting helper classes and informational Objects e.g URI information, SecurityContext, HTTPHeaders ● @Provider: An injectable interface providing runtime lookup of provider instances
  11. 11. Sample JAX-RS application for JUG Attendees Simple Maven Project with two dependencies. JavaEE API and Lombok (to avoid a lot of boilerplate code) 1. A subclass of Application annotated with @ApplicationPath 2. A resource class annotated with @Path 3. A mock database class https://github.com/dawuzi/jax-rs-attendant-sample
  12. 12. The javax.ws.rs.core.Response Class 1. Response class used for building more complex responses 2. Instances can be obtained from javax.ws.rs.core.Response.ResponseBuilder 3. Instances of ResponseBuilder can be obtained from static helper methods in the Response class itself
  13. 13. Exception Handling 1. Applications can throw javax.ws.rs.WebApplicationException to have the container return specific HTTP codes to the client 2. The response can be customised for other exceptions by implementing the ExceptionMapper. The implementing class can then be annotated with @Provider or added to the list of classes in the Application sub class
  14. 14. ExceptionMapper Interface public interface ExceptionMapper<E extends Throwable> { Response toResponse(Exception e); }
  15. 15. JAX-RS Client API 1. Introduced in JAX-RS 2.0 2. Enabled writing portable client REST call with a fluent API
  16. 16. Client API Sample Client client = ClientBuilder.newClient(); WebTarget target = client.target("https://www.google.com"); Response response = target.queryParam("start", "10").request().cookie("test-cookie", "test") .header("test-header", "test").accept(MediaType.APPLICATION_JSON) .get(); client.close();
  17. 17. Client API Sample (Continued) Client client = ClientBuilder.newClient(); WebTarget target = client.target(""); Attendant attendantResponse = target.queryParam("start", "10") .request() .post(Entity.json(new Attendant()), Attendant.class); client.close();
  18. 18. Client API Async Sample (JAX-RS 2.0) Client client = ClientBuilder.newClient(); WebTarget target = client.target(""); AsyncInvoker asyncInvoker = target.request().async(); Future<Response> future = asyncInvoker.get(); while(future.isDone()){ // or do some other task Response response = future.get(); }
  19. 19. Filters 1. Intercepts request/response to carry out special functions e.g authentication 2. Can be classified broadly into request and response filter 3. Request filters can be annotated to execute before matching is done to a JAX-RS method (i.e @PreMatching) 4. Can be ordered (using @Priority) 5. Client and Server side filter available
  20. 20. ContainerRequestFilter Interface All server request filter implement the ContainerRequestFilter interface defined below public interface ContainerRequestFilter { public void filter(ContainerRequestContext requestContext) throws IOException; }
  21. 21. ContainerResponseFilter Interface All server response filter must implement the ContainerResponseFilter public interface ContainerResponseFilter { public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException; }
  22. 22. ClientRequestFilter Interface All client request filter should implement the following interface public interface ClientRequestFilter { public void filter(ClientRequestContext requestContext) throws IOException; }
  23. 23. ClientResponseFilter All client response filter must implement the ClientResponseFilter public interface ClientResponseFilter { public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException; }
  24. 24. Bean Validation 1. Java specification of the Java API for JavaBean validation in Java EE and Java SE 2. Integrated since Java EE 6 3. Constraints on object model can be expressed via annotations 4. Bean validation 2.0 is the current version 5. Easily extensible
  25. 25. Bean Validation. Examples 1. @Min @Max (Numeric Constraints ) 2. @Past @Future (Date Contraints ) 3. @Size (String and Collections) 4. @Email 5. @Pattern 6. @Null @NotNull
  26. 26. Java EE 8. What’s new ? 1. New REST Reactive CLient API 2. Server-Sent Events support (Client & Server side) 3. Enhanced JSON support with a new JSON Binding API 4. Asynchronous CDI events 5. New portable Security API 6. Servlet 4.0 API with HTTP/2 support 7. Support for Java SE 8 capabilities
  27. 27. New Client REST Reactive API 1. Introduction of the rx() method to the javax.ws.rs.client.Invocation.Builder class which returns a CompletionStageRxInvoker 2. CompletionStageRxInvoker returns CompletionStage that can be used to access the results asynchronously 3. CompletionStage aids chaining various async calls and also expressing their dependencies
  28. 28. Reactive Client Sample Code CompletionStageRxInvoker rxInvoker = ClientBuilder.newClient() .target("url") .request() .rx(); // .rx() CompletionStage<Response> completionStage = rxInvoker.get();
  29. 29. Server Sent Events 1. Browser subscribes to a stream 2. Server sends messages (called event-streams)to the client 3. One communication channel (server to client) 4. Sent over HTTP 5. Supported by many browsers (Errr except Microsoft Edge & IE)
  30. 30. SSE Javascript API if (typeof(EventSource) !== "undefined") { var source = new EventSource('url'); Source.onmessage = function(event){ console.log(event.data); } } else { // Your browser does not support sse :’( }
  31. 31. JAX-RS 2.1 SSE sample @Produces(MediaType.SERVER_SENT_EVENTS) public void eventStream(@Context SseEventSink eventSink, @Context Sse sse){ if(!eventSink.isClosed()){ eventSink.send(OutboundSseEvent) } eventSink.close(); }
  32. 32. JAX-RS for backend Services The services for the following app was written using JAX-RS 1. BioRegistra.com 2. AutoTopup.ng
  33. 33. Conclusion 1. JAX-RS is a good fit for building REST services 2. Explore and Explore. JavaEE projects are now on github
  34. 34. THANK YOU
  35. 35. References ● https://www.infoq.com/articles/rest-introduction ● https://www.tutorialspoint.com/restful/restful_introduction.htm ● https://people.cs.pitt.edu/~chang/265/seminar08/emilio.ppt ● https://dennis-xlc.gitbooks.io/restful-java-with-jax-rs-2-0-2rd- edition/en/part1/chapter1/introduction_to_rest.html ● http://beanvalidation.org/ ● https://docs.oracle.com/javaee/7/tutorial/bean-validation001.htm ● https://www.html5rocks.com/en/tutorials/eventsource/basics/
  36. 36. References continued ● https://docs.oracle.com/javaee/7/tutorial/ ● https://www.youtube.com/watch?v=qLXJTrBcAmM ● https://www.youtube.com/watch?v=1b2tO3gfboE ● https://blogs.oracle.com/theaquarium/java-ee-8-is-final-and-glassfish- 50-is-released

×