Blogs On Programming

JAX-RS Basics

JAX-RS Basics

by Vibrant Publishers on Dec 29, 2021
Introduction The implementation of REST framework in Java is done through JAX-RS API. It serves as the basic building block for RESTful services in Java. Let’s take a look at the basics of JAX-RS. JAX-RS JAX-RS (Java API for RESTful Web Services) is also part of the JSR, with a detailed specification definition. Starting with JAVA EE 6, this technology has been built, similar to RESTful WCF in .NET, that exposes the RESTful service by using some simple annotations in the conventional method.The current version of JAX-RS in use is version 2.0. The below-given diagram shows the features of this version. HTTP Methods and annotationsWe know that the REST APIs work through HTTP protocol. The following are the HTTP methods used in REST via annotations. @GET: Defines HTTP GET request method. @PUT: Defines HTTP PUT request method. @POST: Defines the HTTP POST request method. @DELETE: Defines HTTP DELETE request method. A basic GET requestLet’s see how a basic HTTP GET request is implemented using JAX-RS API using a simple ‘Hello World’ example.   @Path(“/”)       public class SampleWebService {         final String XMLNS_NAMESPACE = “http://localhost:8080/rest/service”;         final String ROOT_NODE = “root”;              @GET          @Path(“/json/hello”)          @Produces(MediaType.APPLICATION_JSON)          public JAXBElement<String> getHelloWorldJSON() {         JAXBElement<String> result = new JAXBElement<String>(new QName(“”, ROOT_NODE), String.class, sayHelloWorld());          return result;        }         ……….        }             private String sayHelloWorld() {        return “Hello, this is a sample JAX-RS API!”;       }     @GET indicates that the service can be accessed directly in the browser address bar (for the GET method in HTTP requests). @Path used here twice, the first on Class, the base address of service, and the second time on a method, representing the URL of a specific service method. @Produces defines the output type of method. Here we are opting for a JSON string format output.   We will also deploy the web.xml file in the root folder of the application.                                                                           Now this REST API can be accessed at the address http://localhost:8080/rest/service/json/hello This will return output in the HTML browser as {“root”: “Hello, this is a sample JAX-RS API!”}In this way, any resource at the server side is made available to the client through simple REST API calls over HTTP. Similarly, create, update and delete operations on a resource can be done at the server-side by calling corresponding REST API commands from the client-side. Content NegotiationWhile using REST APIs, we are sharing resources that are represented by multiple data types. JSON and XML are the two most popular content types that are commonly used. The JAX-RS annotations @Produces, @Consumes are used to specify the content format. As the name suggests, @Produces annotation specifies the type of content produced by a method. The @Consumes annotations specify the type of content that a method is expecting as input. For example, @Produces({“application/xml,application/json”})means the method will produce content in two MIME types, XML and JSON. One thing we should understand here is the differences between data and data format. Data can be anything and the data format is the representation of that data. Data transformations occur before or after transmission.  When there is an equal match with the request and response type, the server will return a 200 OK response or a 400 Bad Request if the data format is not matching with the MIME type that the server expects.  Now, let us say the client does not specify any content format, then in JAX-RS 2.0 there is a factor called ‘QS’ ie. ‘QUALITY FROM SERVER’. It can take value from 0 to 1. So in the above scenarios ‘qs’ factor instructs the server to choose a content type that is the default content format. If we consider, @Produces({“application/json qs=0.8; ,application/xml; qs=0.75”}),  it is clear that the server has to consider the JSON format. Request Matching Request matching is a process where the client API request is mapped to the corresponding method at the server-side. This is achieved using the @Path annotation. The value of the @Path annotation is an expression that indicates the relative URI. Consider the following example:  @Path(“/orders”) public class OrderResource {    @GET    public String getAllOrders() {        …    } } Here if you send an HTTP request of GET /orders to the server, that would dispatch to the getAllOrders() method. The JAX-RS has strict precedence and sorting rules for URI expressions matching. This is based on the ‘most specific match wins’ algorithm. You must also abide by the URL encoding rules that only allow alphabetic characters, numbers and some special characters only. Summary The JAX-RS library has specifications and rules that will help a developer to build web services in the RESTful way. In JAX-RS the importance of annotations and how HTTP methods are mapped using these annotations are important to understand. The request – response matching mechanism and specifying the content type while making a request are also important concepts in JAX-RS implementation. 
JAX-RS Response Handling

JAX-RS Response Handling

by bhagyashree kolge on Dec 22, 2021
Introduction The JAX-RS specification for building RESTful services gives clear directions for handling API responses. Some specific annotations and classes are available for this task. Let’s have a look at how the responses are handled at the server-side of JAX-RS web services. Building a JAX-RS ResponseBy default, JAX-RS supports response messages of common Java types. These responses can be either in plain text, XML or JSON format. JAX-RS provides javax.ws.rs.core.Response class for creating responses. The below code sample will produce a response in the plain-text format. @GET   @Path(“color”)   @Produces(TEXT_PLAIN)   public Response getTextileColor()   {     if (color) {       return Response.ok().build();     }     // return 404 Resource not found error.     return Response.status(Response.Status.NOT_FOUND).build();   } }   Normally a response will contain a resource that the client is requesting from the server. The resource representation in java must be marshaled and converted into the media type specified in the REST API request. A POJO [Plain Old Java Object] is converted into REST response format through the process as given below:Response EntityThe response entity is also referred to as ‘payload’ or ‘message body’. While using JAX-RS, response entities are mapped to and from java types by Entity Providers that implement the JAX-RS interface MessageBodyWriter.Message Body WriterThe JAX-RS Message Body Writer converts java types to a stream. There are three main methods in this class. They are isWritable(), getSize() and writeTo() which can be overridden while implementing our logic. Successful ResponsesSuccessful responses are sent along with corresponding HTTP codes. They range from 200 to 399. The JAX-RS response specifications are similar to that of HTTP specifications for GET, PUT, POST, DELETE methods. If an API request is successful and the response contains a message body, then the status code will be 200, ‘OK’. Otherwise, it will be a 204, ‘No Content’ message in the response status. Error ResponsesError response codes range from 400 to 599. These are used based on failure cases. By examining the error code that is returned to the client, we can understand the type of issue faced at the server-side. @Produces AnnotationThe @Produces annotation mentions the media types that a resource can produce and set back to the client. If no method can produce the resource in the specified media type, the REST library will send a “406 Not Acceptable” error to the client. SummaryIn general, responses are built according to the request type. There are classes in JAX-RS that help in the process of building responses. The responses are handled with specific HTTP codes that are sent along with the responses. These codes help the client application to understand the server-side better.  
JAX-RS Exception Handling

JAX-RS Exception Handling

by Vibrant Publishers on Dec 22, 2021
Introduction An exception is a case where an unexpected outcome occurs during computation. This often disrupts the normal flow of the program. There are different mechanisms available to handle an exception. Here in this article, we are going to see some of the mechanisms that JAX-RS has implemented to handle exceptions in its API services. JAX-RS Exceptions A RESTful API may throw exceptions at many scenarios and its proper handling is important for the functionality of that service. In JAX-RS exceptions are handled in two ways. By throwing a web application exception. By mapping exception using exception mapper.   Throwing a web application exception The WebApplicationException is a special RuntimeException class that JAX-RS has implemented in itself. By throwing a WebApplicationException, JAX-RS can abort a particular service method. This exception class can take an HTTP status code or a Response object as its constructor parameter. Let us consider the following code snippet:  @GET   @Path(“{id}”)   public Registration get(@PathParam(“id”) int id) {           Registration registration = getRegistration(id);           if (registration == null) {               Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND);               builder.type(“text/html”);               builder.entity(“   Registration Not Found   “);               throw new WebApplicationException(builder.build());           }           return registration;   }       Here if the object ‘registration’ is null, we create a response using the ResponseBuilder class. Here since we could not find any registration number we are setting the HTTP response code as 404 NOT_FOUND. This response class is then passed to WebApplicationException class which then throws this message as an exception to the client. Throwing a Not Found Exception The above code can be made even simpler by just throwing a NotFoundException. Because this class extends the WebApplicationException. So instead of creating a response using the ResponseBuilder, we can throw this exception as shown below:   @GET   @Path(“{id}”)   public Registration get(@PathParam(“id”) int id) {           Registration registration = getRegistration(id);           if (registration == null) {                     throw new NotFoundException(“Registration NOT found”);           }           return registration;   }       Mapping an exception using ExceptionMapper JAX-RS also provides a mechanism to map generic or custom exceptions into a JAX-RS response. This is done using the ExceptionMapper interface. So the code that throws the exception will implement the ExceptionMapper interface. Let us consider the above code snippet itself. There we were using the exceptions that already existed. Now let’s have a look at how we can use the ExceptionMapper in the same scenario. First, we will build a custom ‘RegistrationNotFoundException’ class.  public class RegistrationNotFoundException extends RuntimeException {       public RegistrationNotFoundException(String message) {          super(message);       }   }     Now we will map this exception to HTTP status message 404 – Resource NOT_FOUND and will build a JAX-RS response. The RegistrationNotFoundMapper class will do this job. Note that it is implementing the ExceptionMapper interface.  @Provider   public class RegistrationNotFoundMapper implements ExceptionMapper {       public Response toResponse(RegistrationNotFoundException exception) {           return Response.status(Response.Status.NOT_FOUND).                   entity(exception.getMessage()).                   type(“text/plain”).                   build();       }   }       Here the @Provider annotation is used for automatic discovery. You don’t need to declare the exception manually. The JAX-RS runtime will automatically discover it during the provider scanning phase. Finally, you throw the RegistrationNotFoundException.   @GET   @Path(“{id}”)   public Registration get(@PathParam(“id”) int id) {           Registration registration = getRegistration(id);           if (exam == null) {               throw new RegistrationNotFoundException(“Registration is not Found”);           }           return registration;   }    This will invoke RegistrationNotFoundMapper.toResponse and will send the custom response to the client.   The mapping of exceptions in this case is explained in the below given diagram.     Exception Mapping Mechanism Exception mapping providers map a runtime or checked exception to an instance of JAX-RS Response. If multiple exception providers are available, then one with the highest priority will be chosen. What will happen if an exception mapper fails to map an exception and that itself throws an error? In this case, a server error with status code 500 is returned to the client as a response. Summary There are different exception handling mechanisms available in JAX-RS. The simple and easy choice would be to use the built-in WebApplicationException. If there is a need to use custom exceptions, then the ExceptionMapper interface can be implemented in the code.    
JAX-RS Request Handling

JAX-RS Request Handling

by Vibrant Publishers on Oct 28, 2021
Introduction Creation and handling of API requests are very important while implementing RESTful services. Invoking a request, mapping of the request, handling the request call and responding to it, etc. are very essential steps in building RESTful services. In this article, let’s have a look at how the Java REST library, JAX-RS handles requests from the clients. JAX-RS Request Handling There are multiple stages for handling a request in JAX-RS. The diagram below shows some of the main aspects of JAX-RS request handling.     JAX-RS uses annotations at the server-side for handling requests from the client. Different types of annotations match different use cases. We are going to have a look at those annotations that are used while handling a client-side API request. @Path Annotation If you want a Java class to be able to handle REST requests, the class must add at least one @Path (“/”)” annotation. The value of this @Path variable can be simple strings to complex regular expressions. Some of the things that we must know about the @Path annotations are: Priority Check Rules  First, check the number of matching characters in a @Path.  Second, check the number of embedded template expressions.  Finally check the number of non-default template expressions. Path Characters If the expression in the path contains characters that need to be escaped, it will be escaped automatically. Otherwise, the URL encoding will be thought and performed. Here the following characters are allowed.  a-z, A-Z, 0-9, -!. ~'()* The following characters are reserved as escape characters.  ??$??/? @ Sub-resource locators If a method that specifies @Path annotations but does not specify HTTP method annotations returns another resource class object that then distributes and processes requests for sub-resources. Sub-resource classes do not need to be exposed as services, so the class can be without @Path annotation. Consider the following example, here @Path(“{database}-dB”) servers as the sub-resource locator.   public class CustomerData    { ……      @Path(“{database}-dB”)      public CustomerDatabase getDatabase(@PathParam(“database”) String dataBase)       {         // find the instance based on the dataBase parameter         CustomerRecord resource = locateCustomerRecord(dataBase);         return resource;        }        …..     }         The @Consumes annotation This annotation specifies which media type a resource can accept at the server-side from an API request. This is important to specify while creating or updating resources at the server side using REST APIs. If this annotation is applied at the class level, all the methods in the class accept the same media type by default. When there is a method that applies @Consumes at a method level, that will override the class level annotation. The value of @Consumes is a string array with acceptable media types. For example: @Consumes({“text/plain,text/html”}) Request Method Annotations The request method annotations are used to map the HTTP methods to Java programming language methods. These are run-time annotations defined by JAX-RS. They correspond to the similarly named HTTP methods. JAX-RS defines @GET, @POST, @PUT, @DELETE, and @HEAD as common request method annotations. You can also create your own custom request method annotations. Methods decorated with request method annotations must return a void or a javax.ws.rs.core.Response Object. Extracting Request Parameters When we create an API request, we can include different parameters into it so that we can extract information at the server side based on these parameters. The following types of parameters can be extracted from a given request. Query Query parameters are specified by @QueryParam in the method parameter arguments. One must import javax.ws.rs.QueryParam class for this. The following example demonstrates application of                                                                   @QueryParam.   @Path(“smooth”)   @GET   public Response smooth(      @DefaultValue(“2”) @QueryParam(“count”) int count,      @DefaultValue(“true”) @QueryParam(“has-min”) boolean hasMin)           {             ……….           }       Here one thing to note is the use of @DefaultValue annotation. They are used to set a specific value to the request if there is no value is provided by the client while using a specific @QueryParam URI path URI path parameters are extracted from the URI request itself. The parameter name is included in the @Path annotation. In the java method arguments, they are specified using the @PathParam annotations. For example:                                                                               @Path(“/{name}”)   public class UserNamePrinter    {      ……    @GET      public String printUserName(@PathParam(“name”) String userID)      {        ……..         }     }     Form Form parameters use the @FormParam annotation and extract information from a request that is of the MIME media type application/x-www-form-urlencoded and conforms to the HTML form encoding specifications. They are mostly used when information is sent in HTML form using the POST method. Cookie Cookie parameters extract information from the cookie-related HTTP headers. It uses @CookieParam annotation. Header Header parameters extracts information from the HTTP headers. Here we use @HeaderParam annotation. One must include the javax.ws.rs.HeaderParam class for using this annotation. Matrix Header parameters extracts information from the URL path segments. The annotation for the Matrix request parameter is @MatrixParam. The class is located in javax.ws.rs.MatrixParam. Summary JAX-RS uses annotations at the server side for handling API requests and there are specific annotations for handling requests from a client-side API. Forming a correct URI, specifying the media types, extracting information from the URI, etc are some of the important steps while processing an API request at the server-side.