Posts

Showing posts from March, 2022

Jersey client API for reading chunked input

  Jersey client API for reading chunked input To read the chunked input on the client, Jersey offers the  org.glassfish.jersey.client.ChunkedInput<T> class. Here is a client example that reads the employee list in chunks, as returned by the server: //Other imports omitted for brevity import org.glassfish.jersey.media.sse.EventInput; import javax.ws.rs.client.ClientBuilder; String BASE_URI = "http://localhost:8080/hr-app/api"; Client client = ClientBuilder.newClient(); Response response = client.target().path("employees") .path("chunk").request().get(); ChunkedInput<List<Employee>> chunks = response .readEntity(new GenericType<ChunkedInput<List<Employee>>>(){}); List<Employee> chunk; while ((chunk = chunks.read()) != null) { //Code to process List<Employee> received in chunks goes here } //Close the client after use client.close(); Having discussed chunked output and input, we now wil...

Generating a chunked output using Jersey APIs

  Generating a chunked output using Jersey APIs A chunked response means that instead of waiting for the entire result, the results are   split  into chunks (partial results) and sent one after the other. Sending a response in chunks is useful for a RESTful web API if the resource returned by the API is huge in size. With Jersey, you can use the  org.glassfish.jersey.server.ChunkedOutput  class as the return type to send the response to a client in chunks. The chunked output content can be any data type for which  MessageBodyWriter<T>  (entity provider) is available. When you specify  ChunkedOutput  as the return type for a REST resource method, it tells the runtime that the response will be chunked and sent one by one to the client. Seeing  ChunkedOutput  as the return type for a method, Jersey will switch to the asynchronous processing mode while processing this method at runtime, without you having to explicitly use  A...

Reading and writing large binary objects using Jersey APIs -storing images

Reading and writing large binary objects using Jersey APIs When you work on enterprise-grade business applications, you may often want to build RESTful web APIs for reading and writing large binary objects, such as images, documents, and various types of media files. Unfortunately, the JAX-RS API does not have standardized APIs for dealing with large binary files. In this section, we will see offerings from the Jersey framework to store and retrieve images files. These APIs are generic in nature and can be used with any large binary file.   Building RESTful web services for storing images Let's build a REST API to store the image sent by the client. We will start with the client and then move on to the server-side implementation. This example uses an HTML client to upload images to the REST API. When you make a  POST  request to the server, you have to encode the data that forms the body of the request. You can use the  multipart / form-data  encoding to deal wi...

Declaratively building links using Jersey annotations

Image
  Declaratively building links using Jersey annotations we saw the offerings in JAX-RS APIs for programmatically building hypermedia links for the REST resources. Jersey simplifies this task further with its annotation-driven API model. In this session, we will take a quick look at the Jersey annotations for building HATEOAS APIs. Specifying the dependency to use Jersey declarative linking <dependency> <groupId>org.glassfish.jersey.ext</groupId> <artifactId>jersey-declarative-linking</artifactId> <!-- Choose the right version --> <version>RELEASE</version> </dependency> Enabling the Jersey declarative linking feature for the application Once you have the appropriate dependency set up, the next step is to enable the declarative linking feature by registering the  org.glassfish.jersey.linking.DeclarativeLinkingFeature  class with the application. You can do this via the  org.glassfish.je...

Programmatically building header links using JAX-RS APIs

Programmatically building header links using JAX-RS APIs The JAX-RS APIs allow you to add links to the HTTP header content as well. In the following code snippet, a link to the access manager for a department resource is added to the HTTP response header: //Rest of the code is omitted for brevity @GET @Path("{id}") @Produces(MediaType.APPLICATION_JSON) public Response find(@PathParam("id") Short id) { Department deptEntity = findDepartmentEntity(id); //Add links to header return Response.ok() .links(getLinks(deptEntity.getManagerId())) .entity(deptEntity).build(); } //Get the link object representing URI for manager private Link[] getLinks(int departmentId) { Link managerLink = Link.fromUri("{id}/employees") .rel("manager").build(departmentId); return new Link[]{managerLink}; } Programmatically building header links using JAX-RS APIs The JAX-RS APIs allow you to add links to the HTTP he...

Building Hypermedia As The Engine Of Application State (HATEOAS) APIs

  Building Hypermedia As The Engine Of Application State (HATEOAS) APIs When exposing operations to be performed on an entity via RESTful services, one of the key things that gets undermined is exposing the entity relationships to the consumer of the service. The flow-on impact is that the consumer ends up hardcoding the logic in the client application. Let's take the case of an online shopping cart application. Is it wise to allow the creation of an order without any products added to the basket or any payments done? Autonomously implementing an order, product, or payments entity service without considering the relationship is obviously not a good design. The realization of entity linking while developing RESTful services is made possible using the HATEOAS constraint. Also, this gives a representation of the state of the application, with the choice of the next possible actions based on the state of the entity. Since the next possible actions are commonly represented as the endpoi...
  Introducing JAX-RS Implementation Framework Extensions we gave an overview of popular JAX-RS implementations, such as Jersey, Apache CXF, RESTEasy, Restlet, and so on As you may know, Jersey is one of the many reference implementations available in the market today for the JAX-RS specification. In reality, the Jersey framework is more than just a JAX-RS reference implementation. It offers additional features and utilities to further simplify RESTful services and client development. In this chapter, we will discuss some of the most useful extension APIs provided by the Jersey and RESTEasy frameworks, which are not part of the JAX-RS standard. We will cover the following topics in this chapter: Dynamically configuring JAX-RS resources during deployment Modifying JAX-RS resources during deployment using ModelProcessor Building HATEOAS APIs Reading and writing large binary objects using Jersey APIs Generating chunked output using Jersey APIs Supporting server-sent events (SSE) in RES...

Understanding the JAX-RS resource life cycle

Image
Understanding the JAX-RS resource life cycle The following diagram depicts the sequence of actions taking place on the server when a client invokes the JAX-RS RESTful web service: For an incoming REST API call, the container identifies the Java servlet configured for handling the REST API calls by parsing the URI, and then delegates the request to the designated servlet. The servlet initializes the JAX-RS runtime and kicks off the RESTful web service request processing cycle for the REST API call in the following sequence: The runtime executes prematching filters ( ContainerRequestFilter  with the  @Prematching  annotation), which happens before resolving the resource method. The prematching filters are useful if you want to influence resource method resolution. The next step is to identify the resource method for serving the request. After the resolution of the resource method, postmatching filters are executed (filters without  @Prematching ). Postmatching filters ...

Understanding filters and interceptors in JAX-RS

  Understanding filters and interceptors in JAX-RS The default request-response model offered in the JAX-RS implementation fits well for many common use cases. However, at times, you may look at extending the default request-response model. For instance, you may need such extension capabilities while adding  support for the custom authentication, customized caching of responses, encoding request content, and so on, without polluting the application code.  JAX-RS allows you to do this by adding your own interceptors and filters for both the REST requests and responses, as appropriate. Typically, filters are used for processing the request-response headers, whereas interceptors are concerned with the marshaling and unmarshaling of the HTTP message bodies . Filters and interceptors can be set on both the client and the server. Modifying request and response parameters with JAX-RS filters The JAX-RS APIs offer distinct filters for both the client and the server.  Impleme...