How to Use Lombok to remove boilerplate setters getters in Java

Hello Friends,

One of the point which is said time and again against Java is that ,we have to write lot of boilerplate code in the form of setters and getters for our simple POJO classes which unnecessarily increases the length of our code.

To tackle this problem,there is open source project called Project Lombok which solves this problem by allowing you to just write few annotation and it will generate getters and setters in the .class which are generated from Java files.

Dockerizing a Spring Boot Application

Hello Friends,

In this tutorial,we will see how we can dockerize our Spring Boot Application.By dockerizing ,we mean that we are going to run our application as docker container.





Following are the steps involved :

1. Create a Spring Boot Application
2. Install Docker on your machine
3. Create a Docker file in your project
4. Docker build using docker file
5. Docker run

Let us see these steps one by one.

Step 1. Create a Spring Boot Application

Please follow my tutorial How to Create Spring Boot Project With Spring Initializer for steps needed to create a Spring Boot project using Spring Boot Initiailizer.

So once you complete this,you should be ready with springBootApp project in your workspace.

Step 2. Install Docker on your machine(Example here is for Windows10)

 2.1 Go to Docker Hub 



     
 2.2 Sign in to the Docker Hub.If you don't have account,create a new account by clicking on Create Account.

   

 2.3 Click on Download Docker Desktop on the below screen


2.4 Click on the "Download Docker Desktop for Windows" to download Installer for Windows.

     For downloading installer for Mac,click on "Docker Desktop for Mac".






















2.5 Follow the steps mentioned here to install Docker from Installer and your Docker should be up and running.

From Docker Docs

- What the Docker Desktop for Windows install includes: The installation provides Docker Engine, Docker CLI client, Docker Compose, Docker Machine, and Kitematic.

- Containers and images created with Docker Desktop for Windows are shared between all user accounts on machines where it is installed. This is because all Windows accounts use the same VM to build and run containers.

- Nested virtualization scenarios, such as running Docker Desktop for Windows on a VMWare or Parallels instance might work, but there are no guarantees.

3. Create a Docker file in your project

    Before we create a docker file,let us understand what is docker file and why it is required.

3.1 What is Docker File ?

Docker file is text file which has set of instructions or commands which will be executed by      Docker demon to create a docker image.

Example of Docker file :

FROM openjdk:8u212-b04-jdk-stretch
COPY target/springBootApp-0.0.1-SNAPSHOT.jar springBootApp-0.0.1-SNAPSHOT.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "springBootApp-0.0.1-SNAPSHOT.jar"]


3.2 Why Docker File is required

By executing the docker file basically we are creating a docker image.This image has all the details required to run the application viz. application code,system libraries,tools.Now we can run this image on any machine which has docker installed and it will get same execution environment.Say I have multiple environments to which my application code will go through before moving to production like ST,ET.Now if I execute this docker image on any of these(ST,ET,Prod) machine,it will make sure that application has same execution environment.

Also it is worth mentioning that once we run our docker image ,it becomes container and we can see container by executing following command:

docker container ls

4. Docker build using docker file

To execute commands or instructions in docker file,we need to execute docker build command on the command prompt as below :

docker build -t <tag name> .

docker build command builds the docker images from a dockerfile and  a "context".A build's context is a set of files  located in the specified PATH or URL.The build process can refer to any of the file in the context.For example,our build can use a COPY instruction to reference a file in the context.

4.1 PATH

In the below example,PATH is current directory(dot),so the context will be built by using files and folders in the project folder(from  where we are executing this command)

docker build -t <tag name> .

In the below example,

docker build -t "springbootapp" .

docker build command needs to be executed from the root of your project where you have placed your docker file and name of the file has to be dockerfile(case insensitive).When we execute docker build,all the instructions in the docker file are executed one by one and a docker Image is created with name given in "tag name".

We can check the newly created docker image by executing following command:

docker image ls


4.2 URL


With the URL parameter,we can mention the url of the Github or bitbucket repository.Docker build will then recursively pull the directories ,subdirectories,files from that repository and will use it as build context and send it to the Docker daemon.

docker build -t <tag name>  <Repository Url>

In this case,docker will clone the remote repository and will use cloned repository as build context.

5. Docker run


Docker run command runs the docker image. Runtime instance of docker image is called docker container.

docker run -p 8080:8080 <image name>
   

By default container does not publish any port.Here we are mapping port 8080 of the container to the port 8080 of the host machine.

So basically,after docker run,your application will be up and running as container.

Summary

By dockerizing our Java application,we make sure that our application gets same kind of execution environment across DEV,ST,ET,PR to make sure that application behaviour does not change due to change in application environment(DEV,ST etc.).

References :



How to integrate and use EclEmma plugin for having good Junit Coverage


Hello Friends,

If writing good code is important,then it is equally important to write good Junit test cases which covers all the business logic.By writing Junit test cases which covers business logic thoroughly ,we actually make sure that individually each method of our code is working fine as per expectation and hence reduce the chances of getting bugs in the later phases of software development.

In this tutorial,we will see how we can use EclEmma plugin to check code coverage of our java code and hence can make sure that we have good coverage through Junit test cases.


Step 1 :

Go to following link :
Step 2 :

Click  on Installation -> Download option on left menu.

Step 3 :

Right click on top most(latest) link(At the time of writing this article, it is “eclemma-3.1.2.zip”) and save Zip on your machine.



Step 4 :

Extract the zip at the same location or location of your choice.

Step 5 :

Copy the extracted folder and go to eclipse folder(Where your eclipse is installed) and paste this extracted folder to the dropins folder within eclipse folder.

Step 6 :

Restart Eclipse.

Step 7 :

Right click on your project folder and select Coverage As-> JUnit Test and click Coverage button.It will run all your test cases and check for coverage.

Now because at this stage,we don't have any test case in our code for Service layer,we are getting 0.0% coverage and all code lines are shown red which means these lines are not covered under Junit test.




In general :

If you see Green colour, it means all those lines are covered under Junit testing.

If you see Red colour, it means all those lines are not covered under Junit testing.


If you see Yellow colour, it means your tests have run through those lines but not all test cases have been covered.

Example 

What we are going to do next is,we will create a Spring boot project,add some code in it and then gradually write test cases and see how EclEmma plugin gives as code coverage.

Step 8 : 

Let us look at it how it works by creating a simple Spring boot project with name "eclemma".Please  follow my tutorial How to create spring boot project with Spring Initializer to create spring boot project.

Step 9:

In  newly created project,create packages  and classes with names as per following screenshot


Step 10 :

Here is the source code for CalculatorService 

package com.blogspot.javasolutionsguide.eclmma.service;

/**
 * @author JavaSolutionsGuide
 *
 */
public interface CalculatorService {

 int add(int a , int b);
 
 int subtract(int a,int b);
}



Here is the source code for  CalcualtorServiceImpl 

package com.blogspot.javasolutionsguide.eclemma.service.impl;

/**
 * @author javaSolutionsGuide
 *
 */
public class CalculatorServiceImpl {
 
 public int add(int a , int b) {
  int c = a + b;
  return c;
 }

 public int subtract(int a,int b) {
  int c = a - b;
  return c;
 }
}

Step 11 :

So ,first we will write test cases only for add() method and then run Eclemma coverage

Here is the code for JUnit test cases for add() method :

package com.blogspot.javasolutionsguide.eclEmma.service.impl;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.blogspot.javasolutionsguide.eclemma.service.impl.CalculatorServiceImpl;


/**
 * @author JavaSolutionsGuide
 *
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {CalculatorServiceImpl.class})
public class CalculatorServiceImplTest {
 
 @Autowired
 private CalculatorServiceImpl calculatorService;
  
 @Test
 public void add_for_givenTwoInteger_shouldReturn_sumOfTwo() {
  Assert.assertEquals("Test case to check if add returns sum of two give positive numbers", 3, calculatorService.add(1, 2));
    }
 
}



Step 12 :

Now let us run the EclEmma Coverage again and see the results :



As we can see,the coverage percentage has increased from 0.0% to 60% for CalculatorServiceImpl class and also the lines of code for add() method has now green colour after running coverage,which means that these lines are covered by Junit tests.

Step 13 :

Similarly ,we will write all test cases for subtract method and see coverage.

Add following test case in  CalculatorServiceImplTest.java :

@Test
public void subtract_for_givenTwoInteger_shouldReturn_differenceOfTwo() {
  Assert.assertEquals("Test case to check if subtract returns sum of two give positive numbers", 1, calculatorService.subtract(2, 1));
}


As we can see now,coverage is 100% for CalculatorServiceImpl class.

Summary 

So in this tutorial,we learnt how we can use EclEmma plugin to see the Junit test coverage of your code.On the basis of the Junit Code coverage report,we can find out which part of our code is covered by Junit and which is still left and then we can accordingly write more test cases for the uncovered lines of code,which will make sure that we have covered all required lines of code through Junit and hence result in better code quality. 

If you like reading this article,share it with your friends,colleagues for whom you think it might be helpful.

How to use profiles in Spring Boot Application

Hello Friends,

In this tutorial,we will learn,how we can use profiles in a Spring Boot Application.


How to Setup Multifactor Authentication (MFA) for your AWS account


Step 1 :

Go to AWS console and login with your username ,password.


Spring Boot Actuator Tutorial


Hello Friends,

In this tutorial, we will learn about Spring actuator and what all it helps us with.

1. What is Spring Actuator?
2. How to add Spring actuator to Maven Project or Gradle Project?
3. Create a Spring Boot project with Spring Actuator dependency.
4. Monitoring the Application with Spring Actuator Endpoints.

How to check which Process is using port 8080 or any other port and vice versa on Windows

Hello Friends,

In this tutorial, you will learn the following :

- How to check which process/application is using a particular port on Windows
- How to check which port is being used by a particular process/application on Windows

Restful API using Spring Rest + Spring Data JPA + H2 with Spring Boot Example

Hello Friends,

In this tutorial, you will learn the following :

1. Configuring Spring Rest, Spring Data JPA and H2 in Spring Boot
2. Example of Spring Rest, Spring Data JPA, and H2 to create restful services endpoints with Spring Boot
3. Using Swagger to test the Restful endpoints

How to Integrate H2 database in Spring Boot App

Hello Friends,

In this tutorial, we will try to explore that how we can integrate with the H2 database in a Spring Boot application.


How to Create Spring Boot Project in STS

Hello Friends,

We already saw in the tutorial  How to Create Spring Boot Project using Spring Initializer.

In this tutorial, we will see step by step, how we can create a Spring Boot project in sts(Spring Tool Suite).


Step 1:

Download Spring tool suite, if you don't have already from the following link for your respective operating system :

https://spring.io/tools/sts/all

Step 2 :

Extract and Open Spring tool suite by click on its icon, which looks like as below


Step 3:

Choose the path where you want to create Workspace and click on Launch.



Step 4:

Spring tool suite will be launched with the following screen :


Step 5 :

Right-click in the package explorer and select New -> Spring Starter Project as below :


Step 6 :

Next screen that will show up is the following :


Step 7 :

In the screen mentioned in Step 6, we can Change the  "Name" to whatever name we want to give to our project. Also, we can change group id, artifact and package name.

I am going to change to following :

Name : springToolSuiteProject
Group : nl.blogspot.javasolutionsguide
Artifact : springToolSuiteProject
Package :nl.blogspot.javasolutionsguide. springToolSuiteProject

Leave following as is :

Service Url : https://start.spring.io

Type: Maven
Note: If you want to use Gradle as a build tool, then you are free to choose Gradle.

Packaging: Jar
Note: Can be changed to War as per requirement.

Java Version: 8
Note: Can be changed to 10 as well as of writing this tutorial.


Step 8 :

Click Next and we will see the following screen :


Step 9 :

As of writing this tutorial, the Latest release version of Spring Boot is 2.0.3, which is selected by default, so leave it as is.

Add dependencies as per requirement. I am going to add only Web here.


Step 10 :

Click Finish. As you can see in the following screenshot, a Maven project with name springToolSuiteProject is added in the STS :


Step 11 :

Let us expand this project and see what Spring Boot has added to it.

As we can see in below screenshot, Spring boot has added lots of required dependencies on its own.


Before the introduction of Spring Boot, we have to add all these dependencies on our own and considering compatibility between different jar versions, it was really chaotic thing, but now we need not worry about it. Spring Boot takes care of all necessary dependencies. We just need to tell Spring Boot only at a high level that which kind of dependencies we want to add, just like in this case we told spring boot about adding Web dependencies and Spring Boot will add all web related dependencies along with other core dependencies.

Following is how pom.xml of this project looks like :



Following dependencies are added in POM for a standard Spring Boot project, even when we have not added any additional dependencies(example Web).


spring-boot-starter-parent makes sure that all necessary basic Spring dependencies are added,as can be seen in below screenshot : 





spring-boot-starter-web dependency is added additionaly as we selceted Web dependency while creating project.



On adding spring-boot-starter-web, we can see that lots of additional dependencies which are required for web project are added to the build path. This includes embedded tomcat dependencies as well, such that we need not install and configure Tomcat separately to deploy Spring Boot application:



Also, Spring Boot has added the following class, which acts as a starting point for the Spring Boot Application.


- The @SpringBootApplication annotation used at the class level above is basically equivalent to combined following three annotations :

@Configuration
@EnableAutoConfiguration
@ComponentScan

- From the main method of 
SpringToolSuiteProjectApplication, SpringApplicaiton class's run method is called. This method makes sure that Spring application's applicationContext(the Spring Container) is initialized. Spring boot uses AnnotaionConfigApplicationContext.

Step 12 :

Run the main method of SpringToolSuiteProjectApplication and you will notice that jar is automatically deployed to embedded Tomcat server and Tomcat server has been started at port 8080.

Check Console log of eclipse:


With this,we saw that How we can Create a Spring Boot Project in sts tool and how we can deploy and run it on embedded Tomcat server.

Thanks for reading.if it helped you,share it with others to help others.