Blogs On Job Interview Questions

JAX-RS Client

JAX-RS Client

by Vibrant Publishers on Jan 04, 2022
Introduction Resources form the basic building block of any REST service. These resources are accessed using the REST client libraries. JAX-RS client is such an implementation. This library makes it easy for any Java programmer to access any REST resources over the internet. JAX-RS ClientThe first version of JAX-RS ie. JAX-RS 1.1 does not had any client implementation. It is from JAX-RS 2.0 onwards it started supporting REST clients. The JAX-RS client API can be found under the javax.ws.rs.Client package. Classes under this package provide high-level APIs for accessing any REST resources, not just JAX-RS services. Let us have a look into the basic operations of JAX-RS Client API. Creating a basic client requestBefore defining a client request, we have to set certain things in place. They are: Obtain an instance of javax.ws.rs.Client class. Configure the client with a resource target. Create a request. Invoke the client request. Let’s have a look into these steps by considering the following code snippet: Client apiClient = ClientBuilder.newClient(); String URI = “http://foodchain.com/api/foodmenu”; String foodMenu = client.target(URI).request(MediaType.JSON).get(String.class); client.close(); Here we first created the client instance by declaring the client variable using the newClient() method. Client apiClient = ClientBuilder.newClient();After this step, we are chaining a set of methods with the client instance that will return the API resource to the string variable foodMenu. There are three steps involved in this process. Setting the target by apiClient.target(URI). This is the remote location where the resource is located. Building a REST request entity using the apiClient.request(Mediatype.JSON) statement. Here we also set the media type of the entity. Invoking the HTTP GET request with apiClient.target(URI).request(MediaType.JSON).get(String.class) statement. Also, the return type of the entity is set into String type. Once the client API successfully receives the response, we will close the client connection with the apiClient.close() statement.We have now seen a simple JAX-RS client API call in action. Now let us look into some of the extended use cases of JAX-RS client library.Setting multiple client targetsWe used the client.target() method in the previous example to set the target URI. We can also use the javax.ws.rs.client.WebTarget class for the same purpose. This will help us in handling REST resources where multiple targets are involved. In the given example, we are setting a base target “http://restapi.com/assignments” using the WebTarget class. The base target is used for building several resource targets that will point to different API services provided by a given RESTful resource. Client apiClient = ClientBuilder.newClient(); WebTarget base = apiClient.target(“http://restapi.com/assignments”); // WebTarget at http://restapi.com/assignments/read WebTarget read = base.path(“read”); // WebTarget at http://restapi.com/assignments/write WebTarget write = base.path(“write”);  Invoking the WebTarget.path() method with a path parameter creates a new WebTarget instance by appending it with the base URI.Invoking the requestThe JAX-RS client can invoke every available REST request method. This is accomplished by calling the WebTarget.request() method and passing the relevant media type value. This will provide an instance of javax.ws.rs.client.Invocation.Builder. This helper object will provide HTTP methods for the client API request. In the first example, apiClient.target(URI).request(MediaType.JSON).get(String.class) we had invoked the HTTP GET request and the same process stands for POST(), DELETE(), PUT() methods also. SummaryJAX-RS client API that got introduced in version 2.0 is one of the best implementations of the REST client library. It’s quite easy to make client API calls using this library. We can use this library in Java for accessing any REST resource over the web.  
JAX-RS Filters

JAX-RS Filters

by Vibrant Publishers on Dec 14, 2021
Introduction JAX-RS is the Java implementation for REST services.There are a lot of features in this library that helps us to build web services in Java. The JAX-RS Filters are used for processing the incoming and outgoing requests and responses including headers, entity and other parameters. This feature was introduced in JAX-RS 2.0. These filters get executed after a request and before a response.The filters are available for both server and client side processing. Use of filters You might be wondering what is the use of filters in web services. Well, there can be situations where you would like to do a common modification for all the requests originating from a particular client or some signature like “Powered by XX” in all the responses going from a particular server. Instead of doing this implementation on all the service methods we would use a filter which will include this modification in all the API requests and responses. The below given is a diagram that schematically represents the filtering process on both client and server sides.     In the first section we got to know that there are filters available for server side and client side as well. Let us look into the details of their types and implementations. Server Side Filters The server side has got two types of filters. ContainerRequestFilters             They get executed before your JAX-RS request resource method is getting invoked.This filter can be used in two ways post-matching and pre-matching. In post-matching filters will be applied after a suitable resource method selection that processes the actual request. Here the filter will not affect the resource matching process. In certain scenarios, this can become a disadvantage. In-order to solve that problem there is pre-matching. When we mark a server request filter as pre-matching using the @PreMatching annotation, the filters are executed before the request matching process. ContainerResponseFilters        These filters get executed after your response method is invoked.They will help you to alter the outgoing response before it reaches the client. ContainerResponseFilter can only be implemented in the pre-matching way. With this filter one can modify the HTTP headers, media type(json,xml,etc.) and other meta-data. They also have the capability to abort a method execution. Client Side Filters Like we saw on the server side, the client side also has two types of filters. ClientRequestFilters            These filters are executed before the client API request is sent to the server over a network. ClientResponseFilters              These filters will be invoked after the client receives a response from the server, but before it is being unmarshalled. They can modify the response body before it is getting processed by the client side code. Summary JAX-RS filters are useful in dealing with modification of REST API request-response services.These filters can be installed at any point in the REST service pipeline. There can be multiple request-response filters where they are executed in a chain. It is very useful when we are working with API driven applications where we might need modification on multiple REST APIs at a given time.  
JAX-RS Security

JAX-RS Security

by Vibrant Publishers on Nov 23, 2021
Introduction Web services play a very vital role in any web application. Since these services deal with data which are of varied criticality, the security considerations of these services are very high. The JAX-RS library implemented to create REST web services in Java uses strict measures to ensure the security of the APIs built on top of it. Let us examine those security features of JAX-RS in detail. JAX-RS Security The JAX-RS library provides a core set of security features at three levels that are as follows. Encryption Authentication Authorization   Encryption    We all know that the REST is built on top of the HTTP protocol. The security of REST services lies in the security of its transfer protocol also. So while implementing APIs developers also make sure that they use HTTPS protocol with SSL certificates to ensure end-to-end encryption. This will block any third party from reading the information by intercepting the network. Authentication         This is another common strategy that people use to make sure the client has access to a particular API resource. This is done by validating the client identity on the server-side. There will be a credential matching process that will confirm the client. In JavaEE containers, there is a web.xml file that can be configured for such processes. Below shown activity diagram shows a sample API authentication process.       Authorization          When a client is authenticated, the next step in the security process is to check whether the client is authorized to access certain resources from the server. In some cases, certain resources are read-only for certain types of clients. Some may have read and update access. So these permissions have to be validated. These settings are also configured in the web.xml file of the application which is hosted in the server container. JAX-RS Security Implementations  We have seen the main ways by which security can be forced into web services. Now let us see how JAX-RS is implementing these measures.  There are three ways by which JAX-RS security can be implemented. They are: Using a deployment descriptor file. Using the security context. Use of annotations.   Using a deployment descriptor file. The deployment descriptor file is an XML file that is part of the container. It is called web.xml. You will configure the web.xml file for web services security in such a way that any client trying to access a resource via an API, it will be asked for authentication and authorization. This is done through the following steps: Define the tag for every URIs or RESTful API resources that we are planning to protect. Use an element that will define a type of authentication that we would like to use. Define one or multiple security roles by including the tag. Once done, map them with security constraints defined in Step.1.   Using the security context The use of SecurityContext class helps us to get the below mentioned security information for a given resource. java.security.Principal object that has the name of the user who is making a request. Authentication type that is used to secure a resource, like FORM_AUTH, BASIC_AUTH, CLIENT_CERT_AUTH. Check whether the authenticated user has been included in any security roles. See whether the request is coming from a secure channel like HTTPS. Use of annotations The javax.annotations.security package in Java provides security annotations. They can be used for securing APIs methods. Following are the common annotations in use:                                                                                     Annotation Usage @PermitAll Specifies that all security roles are allowed to invoke the given resource method. @RolesAllowed Lists out the security roles that are allowed to access a given resource method. @DenyAll It specifies none of the security roles are allowed to invoke the given resource method. @DeclareRoles This will provide the security role of the current user invoking a resource method.   Summary Security implementation in JAX-RS leverages the help of server container and transport protocols. They are implemented mainly using configuration parameters and through annotations. When we are building APIs for web applications, it is always a good practice to include these security features in our API code.    
JAX-RS Asynchronous Processing

JAX-RS Asynchronous Processing

by Vibrant Publishers on Nov 19, 2021
IntroductionThe JAX-RS library is used for implementing REST web services in Java. They are designed for quick request-response processing to ensure speed and optimal use of the underlying container thread pool. But there can be scenarios where certain resources need to run for a longer time to process and provide a response. To address these scenarios, JAX-RS has implemented an asynchronous processing mechanism. This feature was introduced in JAX-RS version 2.0. Let us have a look into the JAX-RS Asynchronous processing mechanism.Asynchronous processing This means the thread that responds to a request will be a different one than that of the thread that handled the request. In short, the request and response won’t happen in one stretch. There can be a considerable time gap between the two.Why is it required?If you are wondering what is the need for such an implementation, there mainly two benefits: Consider a synchronous request-response scenario. If a JAX-RS client sends a request that requires long waiting for a response from the server, it is blocking the request thread. The same thread, if released faster, could have been used by some other requests. This is avoided by implementing the asynchronous method. Similarly on the server side also, it allows the server to suspend the original request thread and create a new thread for responding to an asynchronous request. Due to the above-said reasons, the implementation will ensure high throughput, responsiveness, and scalability. The below given process diagram will give you a clear picture of this concept. JAX-RS Asynchronous ImplementationThere are separate implementations available on the server-side and client-side for asynchronous APIs.Server-side implementation of Asynchronous processing On the server-side, the asynchronous behavior is ensured by using: AsyncResponse: This class is responsible for bridging the client-side request with the server-side methods. Using this class the server methods update the status of asynchronous processes. Based on this status the underlying logic will take appropriate action. The resource method that is running a long process should call AsyncResponse.resume() so that a response can be sent back to the client. @Suspend: This annotation is used to instruct the container to inject the AsyncResponse method and invoke it asynchronously. The resource methods called with AsyncResponse instance will be in the suspended state. One important thing to remember here is that the resource method that is annotated with @Suspend will not be called using a separate thread. It is the responsibility of the programmer to create a new thread for the long-running process and return the caller thread. One more thing to remember here is to specify a time-out period using AsyncResponse.setTimout(). This will ensure that the client will get back an HTTP 503 (Service Unavailable ) response, in case there are some issues on the server and the resource method could not respond. If this timeout is not specified, the client-side request will end up in a long wait. Client side implementation of Asynchronous processing The client side implementation of asynchronous call is pretty easy. The only thing you need to do is get an instance of the AsyncInvoker. This can be done by executing async() function on an instance of Invocation.Builder class. Let us see an example here:Client restClient = ClientBuilder.newBuilder().build();WebTarget URL = restClient.target(“https://api.example.com/search/menu?query=pasta”);Invocation.Builder requestBuilder = URL.request();AsyncInvoker asyncInvoker = requestBuilder.async();Future futureResponse = asyncInvoker.get();Response apiResponse = futureResponse.get(); String responseBody = apiResponse.readEntity(String.class);In the above example, the highlighted portion explains how to use the asynchronous call on the client-side. Summary There are lots of features in JAX-RS that help for rapid request-response processing. But the asynchronous feature implementation in JAX-RS helps a developer to give a time lag between request and response processing. This is very useful especially when there is heavy server-side processing required on certain client requests.
JAX-RS Miscellaneous

JAX-RS Miscellaneous

by Vibrant Publishers on Nov 02, 2021
Introduction REST APIs serve as the backbone of millions of web applications. This is one of the most commonly used web service standards in today’s world. The JAX-RS provides the REST support in Java and has lots of features that help us build scalable web services. In this article we are going to explore some of the JAX-RS features that are important to know while building a web service. Bootstrapping a JAX-RS applicationIt is very simple to start a JAX-RS application. All you need to do is to create a subclass of  javax.ws.rs.core.Application on your classpath. The below given sample explains how you will do that:                                                                        import javax.ws.rs.core.Application; @ApplicationPath(“api”) public class SampleWebAPIApplication extends Application           {       } The annotation @ApplicationPath provides the context root for all your APIs. In this case the APIs will have a URI starting with ‘/api’. So if you have an API to provide employee details, the URI will look like “http://www.example.com/api/v2/employee/” here the “/v2/” stands for versioning. It’s always a good practice to include versioning while creating APIs. This will be helpful when you want the same resource in custom APIs for different clients. Defining  REST endpointsThe REST endpoints serve as the connection point with the client. The JAX-RS specification has given the @Path annotation to map each HTTP (PUT, DELETE, POST, GET)  method to a java method. Consider the following example:                                                                                 public class EmployeeDatabse {  @GET  @Path(“/{id}”)    public Response getNameById(@PathParam(“id”) Long id,      @QueryParam(“name”)    @DefaultValue(“”) String name) {   @POST       public Response getNameById(Employee employee, @Context UriInfo uriInfo) {  // …  }       // …     } Here the entire class is mapped to “/employee” with different HTTP methods. The @PathParam is used for getting the value of a path variable and the @QueryParam is used for retrieving values for a query parameter of a URL.JAX-RS Providers Providers are extensions of JAX-RS that are responsible for providing functionality to the JAX-RS runtime. Mainly two types of providers are there. Exception mapping providers and Entity providers. Exception Mapping ProvidersThese are responsible for mapping services between JAX-RS response and Java exceptions. The ExceptionMapper interface is provided when a resource method throws a runtime exception. The response provided by these exception mappers are treated as same as the response provided by the resource methods. Entity ProvidersEntity providers provide marshalling / unmarshalling service between Java types and the resource representations (XML/JSON etc.). The MessageBodyReader interface is an entity provider that is used for deserializing a resource representation into a Java type. The reverse operation is performed by another entity provider interface named MessageBodyWriter. Exception Handling The exceptions that are thrown by a resource method are caught by the JAX-RS runtime and they are converted into error responses. By default they are converted into a “HTTP 500 – Server Error” message. There are two ways in JAX-RS to deal with exceptions, the first method is to throw “WebApplicationException” that can customize error response messages. The second method is to use the built in response mechanism of the JAX-RS runtime that will send a default Response to the client when an exception is caught. Summary When dealing with REST implementation using JAX-RS, there are some points that one must know to make use of its full potential. These concepts discussed here will help you build web services that conform to the REST principle.