Skip to main content

Posts

Showing posts from January, 2019

A complete guide to securing Spring RESTful web services using HTTP Basic Authentication header

In the following tutorial, I have shown you how to develop RESTful web services using Spring Boot Spring Data Rest web services for Beginners - Step By Step Guide This is a simple and easy written tutorial for beginners who are interested to explore the trending and widely used J2EE framework. In this tutorial, we will learn how to secure the Restful web services using the HTTP Basic Authentication header. According to rfc7617,  basic authentication is the method for HTTP user agent to provide the following two pieces of information in a request User Name Password In this method, the HTTP request contains the header in the following format Authorization: Basic <credentials>  where <credentials> is base64(username:password) Step 1 Add the following dependency to the maven <dependency>   <groupId>org.springframework.boot</groupId>   <artifactId>spring-boot-starter-security</artifactId> <...

Best way to convert float to int in Java 8?

Most of the time, Java developers have to do type conversion. In this example, I will cover the conversion of  float datatype to int . There are several ways to achieve this. Solution 1 public class FloatToIntCasting {               public static void main( String[] args ) {                  float value = 0.9f;                  System.out.println( "0.9f converted to int : " +  (int) value );                  value = 1.1f;                  System.out.println( "1.1f converted to int : " + (int) value );              } } Output  0.9 f converted to int : 0 1.1 f converted to  int  : 1 As we can see in the above example, casting a float to int results in downcasting. It simply r...

Spring Boot - How to deploy WAR file to Tomcat or any other external container?

Introduction When we develop Spring Boot application using Maven, the project is by default configured to package the project as JAR with an embedded Tomcat or another container. If we wish to export the project as WAR for deployment on the external container, we will have to change the configuration. Below are the steps to export Spring Boot project as WAR STEP 1 Change the maven.xml, replace the packaging value as provided below <packaging> war </packaging> STEP 2 Extend your main application class file from  SpringBootServletInitializer and override its  configure method as shown below Please leave your feedback in the comments box.

Spring Data Rest web services for beginners - Step By Step Guide

This tutorial is designed for those who have not worked with the Spring Framework or rest web services before. I am keeping it simple and less verbose so that readers can easily follow the steps and start developing the restful web services using Spring Data Rest. Spring Framework is the trending and widely used J2EE frameworks. It has various modules for web development. In this tutorial, we will use the Spring Data Rest. RESTful Web services Representational State Transfer (REST)  is based on server-client architecture and uses the HTTP protocol(stateless protocol). CRUD operations can be easily mapped on HTTP methods Create POST Read GET Update PUT Delete Delete Prerequisites for this tutorial Java 8 or later version Eclipse Maven Let's start developing the RESTful web services STEP 1 Open a new Maven Project in the eclipse, let's call it MyFirstRestApp.  We will use the Spring Boot for this tutorial. Open the maven.xml ...

Apache Spark - Could not locate executable null\bin\winutils.exe in the Hadoop binaries

I am passionate about BigData technologies. I am exploring the Apache Spark these days. I found IBM's BigDataUniversity the best place to learn the trending BigData technologies. I wrote my first Apache Spark application but when I ran it, I encountered the following error Could not locate executable null\bin\winutils.exe  in the Hadoop binaries I searched for it over the internet and found variously detailed solutions. In this post,  I am listing down the steps in an easy way to explain how to fix this issue. Step 1  Download the winutils.exe from the following link winutils 32-bit      (depends on your installed Windows version) winutils 64-bit      (depends on your installed Windows version) Step 2  Create the following two directories in C or any other drive  c:\hadoop\bin  C:\tmp\hive Step 3 Place the downloaded winutils.exe inside the c:\hadoop\ bin folder Step 4...

How to change base URI in Spring Data Rest?

If you have worked with Spring Data Rest, you would have observed that by default, Spring serves the requests to the root URI '/'. If you want to append a specific string to the base path, you can specify the following property in application.properties file inside the resources folder spring.data.rest.basePath=/api This solution is provided in Spring Boot 1.2 and later versions. In my case it did not work for me, after searching for it over the internet, I have found the solution,  instead of basePath property, set the following property in application.properties file server.servlet.context-path=/api Please leave your comments.

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...

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>(); ...

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(respon...

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 ...