Skip to main content

Posts

Java - slf4j vs log4j

Java developers use these two APIs but most of them will not be aware of the differences between these two. slf4j stands for Simple Logging Facade for Java. It can be considered as a simple  Facade  or abstraction for various Java logging frameworks and not an implementation. It adds the flexibility to switch different logging framework for application and this decision can be taken at runtime without recompiling the code. This prevents the application to be dependent on a specific logging framework and unwanted inclusion of different jar/libraries dependent on that specific logging framework. commons-logging  is a competitor or alternate for slf4j. log4j is the implementation and it provides the logging or tracing ability to the application. It is one of the most widely used logging framework for Java. Manual logging can drastically impact the performance of an application and can slow it down, whereas log4j has been designed for flexibility, simplicity and speed.

Hibernate - How to maintain a single Session instance Per Thread?

Hibernate is an Object Relation mapping framework for Java language. It has more benefits over JDBC. Since I am using it since 2010, I have found that one of the biggest benefits of Hibernate is that code written using Hibernate is almost database independent and can be a key feature if one wants to shift the code base from one database to another. Using Hibernate, one has to be careful with the following two a) A singleton SessionFactory instance should be maintained throughout the application (if using a single database)  It can be easily done using either a static code block OR implementing the Singleton pattern. b) Single Session instance should be maintained per Thread This is a tricky part but luckily we have the ThreadLocal  to our rescue.  This class provides thread-local variables. Below is the code to maintain a single Session instance per Thread private static final ThreadLocal<Session> session = new ThreadLocal<Session>();    public static S

Spring Boot RestTemplate - Log the Request and Response

Recently when working on a rest client using the Spring's RestTemplate, I needed to log the request and response as I had no clue what was wrong with my code. Spring provides the option to write your own Interceptors. For this specific requirement, Spring provides the  ClientHttpRequestInterceptor interface. I had to override its intercept method and implement my logic there. Below is the snapshot of my code public class MyInterceptor implements ClientHttpRequestInterceptor  {       @Override     public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] body, ClientHttpRequestExecution execution)                 throws IOException {              printRequest(httpRequest, body);             ClientHttpResponse response = execution.execute(httpRequest, body);             printResponse(response);             return response;     }     private void printRequest(HttpRequest httpRequest, byte[] body) throws IOException {                          System.out.print

Spring Rest web services that accepts Generic JSON instead of specific

Recently when working on restful webservices, I came across a situation where I have to receive variant  JSON  in my Request and have to return the variant JSON in response. In previous projects, I was using the specific Java Objects in my request and response.  In the current project, I had no idea how to handle the generic JSON instead of specific Java objects (jackson lib that automatically marshal/unmarshal JSON/Java Objects).  I came across the jackson's JsonNode class. Using JsonNode, I can accept any kind of Json in my request and similarly can return generic Json in my response.

How to avoid HttpStatusCodeException using Spring RestTemplate

I have written a Rest client using the Spring's RestTemplate with the following code  try {               response = restTemplate.exchange( url,HttpMethod.POST, entity , JsonNode.class);  }catch (HttpStatusCodeException codeException) {         String responseBody = codeException.getResponseBodyAsString();            ......................  } catch(Exception ex) {                   ex.printStackTrace();            ObjectMapper mapper = new ObjectMapper();           JsonNode node = mapper.readTree(" { \"error\" : \"" + ex.getMessage() + "\" }" );            response = new ResponseEntity<>(node, HttpStatus.INTERNAL_SERVER_ERROR );  } In the above code, I am not able to read the response body. This is the issue with the RestTemplate default error handler. In order to fix this issue, I have the following two options a) Write my own Error Handler that implements ResponseErrorHandler b) Write my own Error Handler tha