All posts by Saurabh Gupta

My Name is Saurabh Gupta, Done MCA from MMMEC Gorakhpur and having approx. 15 Year of experience in Information Technology World manly in Java/J2EE. During this time I have worked with multiple organization with different client, so many technology, frameworks etc.

[Java] Plus Pattern Java Program


In this “Print Plus Pattern” – We have written Java programs to print/draw Plus pattern by using different types of Java loops and you can execute and try these Java program through your IDE. This is most [100+] Frequently Asked Java Program on beginner level to check you Java Programming skills and Concept.

Plus Pattern Example

Logic: To draw Plus Pattern through Java program, there would be one line of the vertical and horizontal. To draw vertical line just double (2*n) the inserted size and run one outer loop for each rows. Inside of this loop put condition as when i!=n, run internal loop print character if (j=n) else print space. When i=n then print 2*n characters for complete row.

This post covers following ways to print Plus Pattern:

  • Print Plus Pattern Java Program: Using for Loop
  • Print Plus Pattern Java Program: Using While Loop
  • Print Plus Pattern Java Program: Using Do-While Loop

Plus Pattern Java Program: For Loop

This Plus Pattern Java Program is following the below logic:

  1. The outer “for” loop first check the condition ( i<=n*2-1), if this condition is true then it check the if condition (i!=n) is true, then first inner “for” loop will be executed otherwise else part will execure for 2nd “for” loop.
  2. The first inner loop, if the condition (j==n) is true then it will display the symbol otherwise display the spaces. This loop will execute until the condition is satisfies.
  3. The second inner “for” loop will execute if the condition at the outer “for” loop is false, in the loop if condition is true display the symbol as given.
package _1_patterns.plus;

import java.util.Scanner;

public class PlusPatternForLoop {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		System.out.println("Enter Pattern Size : ");
		int size = sc.nextInt();

		System.out.print("Enter Symbol : ");
		char symbol = sc.next().charAt(0);

		drawPlusPattern(size, symbol);

		// Close Scanner
		sc.close();
	}

	private static void drawPlusPattern(int n, char c) {
		for (int i = 1; i <= n * 2 - 1; i++) {
			if (i != n)
				for (int j = 1; j <= n; j++) {
					if (j == n)
						System.out.print(c);
					System.out.print(" ");
				}
			else
				for (int j = 1; j <= n * 2 - 1; j++) {
					System.out.print(c);
				}

			System.out.println();
		}
	}
}

Output

Enter Pattern Size : 
9
Enter Symbol : $
        $ 
        $ 
        $ 
        $ 
        $ 
        $ 
        $ 
        $ 
$$$$$$$$$$$$$$$$$
        $ 
        $ 
        $ 
        $ 
        $ 
        $ 
        $ 
        $ 

Plus Pattern Java Program: While Loop

This Plus Pattern Java Program is following the below logic:

  1. The outer “while” loop first check the condition ( i<=n*2-1), if this condition is true then it check the if condition (i!=n) is true, then first inner “while” loop will be executed otherwise else part will execute for 2nd “while” loop.
  2. The first inner “while” loop, if the condition (j==n) is true then it will displays the symbol otherwise display the spaces. This loop will execute untill the condition is satisfies.
  3. The second inner “while” loop will execute if the condition at the outer “while” loop is false, in the loop if condition is true display the symbol as given.
package _1_patterns.plus;

import java.util.Scanner;

public class PlusPatternForLoop {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		System.out.println("Enter Pattern Size : ");
		int size = sc.nextInt();

		System.out.print("Enter Symbol : ");
		char symbol = sc.next().charAt(0);

		drawPlusPattern(size, symbol);

		// Close Scanner
		sc.close();
	}

	private static void drawPlusPattern(int n, char c) {
		int i = 1;
		int j;
		while (i <= n * 2 - 1) {
			if (i != n) {
				j = 1;
				while (j <= n) {
					if (j == n)
						System.out.print(c);
					System.out.print(" ");
					j++;
				}
			} else {
				j = 1;
				while (j <= n * 2 - 1) {
					System.out.print(c);
					j++;
				}
			}
			System.out.println();
			i++;
		}
	}
}

Output

Enter Pattern Size : 
7
Enter Symbol : #
      # 
      # 
      # 
      # 
      # 
      # 
#############
      # 
      # 
      # 
      # 
      # 
      # 

Plus Pattern Java Program: Do-While Loop

This Plus Pattern Java Program is following the below logic:

  1. The first outer “do-while” loop will execute, then checks the condition (i<=n*2-1).
  2. If condition (i!=n) is true, then first inner “do-while” loop will be executed otherwise second inner “do-while” loop will be executed.
  3. The outer “do-while” loop executes until the condition (i<=n*2-1) is false.

package _1_patterns.plus;

import java.util.Scanner;

public class PlusPatternForLoop {

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.println("Enter Pattern Size : ");
    int size = sc.nextInt();

    System.out.print("Enter Symbol : ");
    char symbol = sc.next().charAt(0);

    drawPlusPattern(size, symbol);

    // Close Scanner
    sc.close();
}

private static void drawPlusPattern(int n, char c) {
int i = 1;
		int j;

		do {
			if (i != n) {
				j = 1;
				do {
					if (j == n) {
						System.out.print(c);
					}
					System.out.print(" ");
					j++;
				} while (j <= n);
			} else {
				j = 1;
				do {
					System.out.print(c);
					j++;
				} while (j <= n * 2 - 1);
			}
			System.out.println();
			i++;
		} while (i <= n * 2 - 1);
}
}

Output

Enter Pattern Size : 
8
Enter Symbol : ^
       ^ 
       ^ 
       ^ 
       ^ 
       ^ 
       ^ 
       ^ 
^^^^^^^^^^^^^^^
       ^ 
       ^ 
       ^ 
       ^ 
       ^ 
       ^ 
       ^ 

Hope this post helps you to implement the Plus Pattern through Java Program. Please share your comments.

Happy Learning!!!

[Java] Square Pattern Java Program


In this “Print Square Pattern” – We have written Java programs to print/draw square pattern by using different types of Java loops and you can execute and try these Java program through your IDE. This is most [100+] Frequently Asked Java Program on beginner level to check you Java Programming skills and Concept.

Square Pattern Example

This post covers following ways to print Star (X) Pattern:

  • Print Square Pattern Java Program: Using for Loop
  • Print Square Pattern Java Program: Using While Loop
  • Print Square Pattern Java Program: Using Do-While Loop

Logic: A square will have same number of rows and columns. In this program implemented the logic through outer and inner loop. Outer loop is used for rows and inner loop for columns.

Square Pattern Java Program: For Loop

This Square Pattern Java Program is following the below logic:

  1. The outer for loop iterated n times until the condition i<n is false.
  2. The inner for loop iterates n times and display the symbol until the condition j<n is false.
package _1_patterns.square;

import java.util.Scanner;

public class SquarePatternForLoop {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		System.out.println("Enter Pattern Size : ");
		int size = sc.nextInt();

		System.out.print("Enter Symbol : ");
		char symbol = sc.next().charAt(0);

		drawSquarePattern(size, symbol);

		// Close Scanner
		sc.close();
	}

	private static void drawSquarePattern(int n, char c) {
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				System.out.print(c);
			}
			System.out.println();
		}
	}
}

Output

Enter Pattern Size : 
10
Enter Symbol : ^
^^^^^^^^^^
^^^^^^^^^^
^^^^^^^^^^
^^^^^^^^^^
^^^^^^^^^^
^^^^^^^^^^
^^^^^^^^^^
^^^^^^^^^^
^^^^^^^^^^
^^^^^^^^^^

Square Pattern Java Program: While Loop

This Square Pattern Java Program is following the below logic:

  1. The outer while loop iterated n times until the condition i++<n is false.
  2. The inner while loop iterates n times and display the symbol until the condition j++<n is false.
package _1_patterns.square;

import java.util.Scanner;

public class SquarePatternWhileLoop {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		System.out.println("Enter Pattern Size : ");
		int size = sc.nextInt();

		System.out.print("Enter Symbol : ");
		char symbol = sc.next().charAt(0);

		drawSquarePattern(size, symbol);

		// Close Scanner
		sc.close();
	}

	private static void drawSquarePattern(int n, char c) {
		int i = 0;
		while (i++ < n) {
			int j = 0;
			while (j++ < n)
			{
				System.out.print(c);
			}
			System.out.println();
		}
	}
}

Output

Enter Pattern Size : 
8
Enter Symbol : %
%%%%%%%%
%%%%%%%%
%%%%%%%%
%%%%%%%%
%%%%%%%%
%%%%%%%%
%%%%%%%%
%%%%%%%%

Square Pattern Java Program: Do-While Loop

This Square Pattern Java Program is following the below logic:

  1. The outer do-while loop iterated n times until the condition ++i<n is false.
  2. The inner do-while loop iterates n times and display the symbol until the condition ++j<n is false.

package _1_patterns.square;

import java.util.Scanner;

public class SquarePatternDoWhileLoop {

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.println("Enter Pattern Size : ");
    int size = sc.nextInt();

    System.out.print("Enter Symbol : ");
    char symbol = sc.next().charAt(0);

    drawSquarePattern(size, symbol);

    // Close Scanner
    sc.close();
}

private static void drawSquarePattern(int n, char c) {
       int i = 0;
		do {
			int j = 0;
			do {
				System.out.print(c);
			} while (++j < n);
			System.out.println();
		} while (++i < n);
}
}

Output

Enter Pattern Size : 
7
Enter Symbol : #
#######
#######
#######
#######
#######
#######
#######

Hope this post helps you to implement the Square Pattern through Java Program. Please share your comments.

Happy Learning!!!

[Java] Right Arrow Pattern Java Program


In this “Print Right Arrow Pattern” – We have written Java programs to print/draw Right Arrow Pattern by using different types of Java loops and you can execute and try these Java program through your IDE. This is most [100+] Frequently Asked Java Program on beginner level to check you Java Programming skills and Concept.

Right Arrow Pattern Example

This post covers following ways to print Star (X) Pattern:

  • Print Right Arrow Pattern Java Program: Using for Loop
  • Print Right Arrow Pattern Java Program: Using While Loop
  • Print Right Arrow Pattern Java Program: Using Do-While Loop

Logic: This Right Arrow Pattern logic is implemented mainly in two parts; first outer loop will display the first half of the pattern and second outer loop will display the second half of the pattern. Here outer loop will display the rows and inner loops will display the columns.

Right Arrow Pattern Java Program: For Loop

This Right Arrow Pattern Java Program is following the below logic:

  1. First outer for loop condition will checked if it is true then it checks the inner for loop condition if it is true then display space otherwise display symbol which user have given to display.
  2. Inner for loop will execute the code until the condition is false.
  3. Similarly, the condition at 2nd outer for loop is true, then inner for loop will execute until the condition id false. In inner loop “if” condition is true, then it display space otherwise displays symbol which user have given to display.
package _1_patterns.right_arrow;

import java.util.Scanner;

public class RightArrowPatternForLoop {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		System.out.println("Enter Pattern Size : ");
		int size = sc.nextInt();

		System.out.print("Enter Symbol : ");
		char symbol = sc.next().charAt(0);

		drawRightArrowPattern(size, symbol);

		// Close Scanner
		sc.close();
	}

	private static void drawRightArrowPattern(int n, char c) {
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				if (j < i)
					System.out.print("  ");
				else
					System.out.print(c);
			}
			System.out.println();
		}
		for (int i = 2; i <= n; i++) {
			for (int j = 0; j < n; j++) {
				if (j < n - i)
					System.out.print("  ");
				else
					System.out.print(c);
			}
			System.out.println();
		}	
	}
}

Output

Enter Pattern Size : 
5
Enter Symbol : $
$$$$$
  $$$$
    $$$
      $$
        $
      $$
    $$$
  $$$$
$$$$$

Right Arrow Pattern Java Program: While Loop

This Right Arrow Pattern Java Program is following the below logic:

  1. The condition at first outer while loop is true, then it comes to the inner loop, the inner loop condition also true then checks the “if” condition, is true, then it displays space otherwise will display symbol. The inner loop will execute the code until condition is false. The 1st outer loop executes the code until the condition is i<n.
  2. Similarly, pointer comes to the next line then second outer while loop will be executed until the condition is false.
package _1_patterns.rightarrow;

import java.util.Scanner;

public class RightArrowPatternWhileLoop {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		System.out.println("Enter Pattern Size : ");
		int size = sc.nextInt();

		System.out.print("Enter Symbol : ");
		char symbol = sc.next().charAt(0);

		drawRightArrowPattern(size, symbol);

		// Close Scanner
		sc.close();
	}

	private static void drawRightArrowPattern(int n, char c) {
		int i = 0;
		int j;
		while (i < n) {
			j = 0;
			while (j < n) {
				if (j < i)
					System.out.print("  ");
				else
					System.out.print(c);
				j++;
			}
			System.out.println();
			i++;
		}
		i = 2;
		while (i <= n) {
			j = 0;
			while (j < n) {
				if (j < n - i)
					System.out.print("  ");
				else
					System.out.print(c);
				j++;
			}
			System.out.println();
			i++;
		}
	}
}

Output

Enter Pattern Size : 
8
Enter Symbol : %
%%%%%%%%
  %%%%%%%
    %%%%%%
      %%%%%
        %%%%
          %%%
            %%
              %
            %%
          %%%
        %%%%
      %%%%%
    %%%%%%
  %%%%%%%
%%%%%%%%

Right Arrow Pattern Java Program: Do-While Loop

This Java Program is following the below logic:

  1. in the first outer do-while loop, it executes the code and then checks the condition i<n, The first outer do-while loop will exceute the code until the condition i<n false.
  2. Similarly, the second outer do-while loop will execute the code until the condition i<n is false.

package _1_patterns.rightarrow;

import java.util.Scanner;

public class RightArrowPatternDoWhileLoop {

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.println("Enter Pattern Size : ");
    int size = sc.nextInt();

    System.out.print("Enter Symbol : ");
    char symbol = sc.next().charAt(0);

    drawRightArrowPattern(size, symbol);

    // Close Scanner
    sc.close();
}

private static void drawRightArrowPattern(int n, char c) {
int i = 0;
		int j;
		do {
			j = 0;

			do {
				if (j < i)
					System.out.print("  ");
				else
					System.out.print(c);
				j++;
			} while (j < n);

			System.out.println();
			i++;

		} while (i < n);
		i = 2;
		do {
			j = 0;
			do {
				if (j < n - i)
					System.out.print("  ");
				else
					System.out.print(c);
				j++;

			} while (j < n);

			System.out.println();
			i++;
		} while (i <= n);
}
}

Output

Enter Pattern Size : 
8
Enter Symbol : #
########
  #######
    ######
      #####
        ####
          ###
            ##
              #
            ##
          ###
        ####
      #####
    ######
  #######
########

Hope this post helps you to implement the Right Arrow Pattern through Java Program. Please share your comments.

Happy Learning!!!

[Java] Rhombus Pattern Java Program


In this “Print Rhombus Pattern” – We have written Java programs to print/draw Rhombus pattern by using different types of Java loops and you can execute and try these Java program through your IDE. This is most [100+] Frequently Asked Java Program on beginner level to check you Java Programming skills and Concept.

Pattern Example

This post covers following ways to print Rhombus Pattern:

  • Print Rhombus Pattern Java Program: Using for Loop
  • Print Rhombus Pattern Java Program: Using While Loop
  • Print Rhombus Pattern Java Program: Using Do-While Loop

Rhombus Pattern Java Program: For Loop

This Rhombus Java Program is following the below logic:

  1. In this program ask inputs from the user for size of rhombus pattern and symbol to create it.
  2. Outer for loop is used to print number of rows while inner for loops are used to print number of columns.
  3. First inner for loop (int j = 1; j <= n – i; j++) is used to print spaces and it reduce the number of spaces bases on each count of outer loop.
  4. Second inner for loop (int j = 1; j <= n; j++) print the number symbols as entered in size.
package _1_patterns.rhombus;

import java.util.Scanner;

public class RhombusPatternForLoop {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		System.out.println("Enter Pattern Size : ");
		int size = sc.nextInt();

		System.out.print("Enter Symbol : ");
		char symbol = sc.next().charAt(0);

		drawRhombusPattern(size, symbol);

		// Close Scanner
		sc.close();
	}

	private static void drawRhombusPattern(int n, char c) {
		for (int i = 1; i <= n; i++) {
			for (int j = 1; j <= n - i; j++)
			{
				System.out.print(" ");
			}
			for (int j = 1; j <= n; j++)
			{
				System.out.print(c);
			}
			System.out.println();
		}	
	}
}

Output

Enter Pattern Size : 
6
Enter Symbol : $
     $$$$$$
    $$$$$$
   $$$$$$
  $$$$$$
 $$$$$$
$$$$$$

Rhombus Pattern Java Program: While Loop

This Rhombus Java Program is following the below logic:

  1. Outer while loop is used to print number of rows while inner while loops are used to print number of columns.
  2. First inner while loop (j++ <= n-i) is used to print spaces and it reduce the number of spaces bases on each count of outer loop.
  3. Second inner while loop (j++ <= n) print the number symbols as entered in size.
package _1_patterns.rhombus;

import java.util.Scanner;

public class RhombusPatternForLoop {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		System.out.println("Enter Pattern Size : ");
		int size = sc.nextInt();

		System.out.print("Enter Symbol : ");
		char symbol = sc.next().charAt(0);

		drawRhombusPattern(size, symbol);

		// Close Scanner
		sc.close();
	}

	private static void drawRhombusPattern(int n, char c) {
	int i = 1;
		while (i <= n) {
			int j = 1;
			while (j++ <= n - i) {
				System.out.print(" ");
			}
			j = 1;
			while (j++ <= n) {
				System.out.print(c);
			}
			System.out.println();
			i++;
		}
	}
}

Output

Enter Pattern Size : 
7
Enter Symbol : #
      #######
     #######
    #######
   #######
  #######
 #######
#######

Rhombus Pattern Java Program: Do-While Loop

This Rhombus Java Program is following the below logic:

  1. Outer dowhile loop is used to print number of rows while inner do-while loops are used to print number of columns.
  2. First inner do-while loop (j++ <= n-i) is used to print spaces and it reduce the number of spaces bases on each count of outer loop.
  3. Second inner do-while loop (j++ <= n) print the number symbols as entered in size.

package _1_patterns.rhombus;

import java.util.Scanner;

public class RhombusPatternForLoop {

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.println("Enter Pattern Size : ");
    int size = sc.nextInt();

    System.out.print("Enter Symbol : ");
    char symbol = sc.next().charAt(0);

    drawRhombusPattern(size, symbol);

    // Close Scanner
    sc.close();
}

private static void drawRhombusPattern(int n, char c) {
int i = 1;
		do {
			int j = 1;
			do {
				System.out.print(" ");
			} while (j++ <= n - i);
			j = 1;
			do {
				System.out.print(c);
			} while (++j <= n);

			System.out.println();
			i++;
		} while (i <= n);
}
}

Output

Enter Pattern Size : 
10
Enter Symbol : ^
          ^^^^^^^^^^
         ^^^^^^^^^^
        ^^^^^^^^^^
       ^^^^^^^^^^
      ^^^^^^^^^^
     ^^^^^^^^^^
    ^^^^^^^^^^
   ^^^^^^^^^^
  ^^^^^^^^^^
 ^^^^^^^^^^

Hope this post helps you to implement the Rhombus Pattern through Java Program. Please share your comments.

Happy Learning!!!

[Java] Star (X) Pattern Java Program


In this “Print Star (X) Pattern” – We have written Java programs to print/draw Star (X) pattern by using different types of Java loops and you can execute and try these Java program through your IDE. This is most [100+] Frequently Asked Java Program on beginner level to check you Java Programming skills and Concept.

Pattern Example

This post covers following ways to print Star (X) Pattern:

  • Print Star (X) Pattern Java Program: Using for Loop
  • Print Star (X) Pattern Java Program: Using While Loop
  • Print Star (X) Pattern Java Program : Using Do-While Loop

Star (X) Pattern Java Program: For Loop

This Java Program is following the below logic:

  1. Inner for loop iterates from j=1 to k and prints characters if j=i or j=k-i+1 displays “*” (symbol), else display space.
  2. Inner for loop will execute until condition i<=k is false, then it comes to the outer for loop.
package _1_patterns.xstar;

import java.util.Scanner;

public class XStarPatternForLoop {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		System.out.println("Enter Pattern Size : ");
		int size = sc.nextInt();

		System.out.print("Enter Symbol : ");
		char symbol = sc.next().charAt(0);

		drawXStarPattern(size, symbol);

		// Close Scanner
		sc.close();
	}

	private static void drawXStarPattern(int n, char c) {
		int k = n * 2 - 1;
		for (int i = 1; i <= k; i++) {
			for (int j = 1; j <= k; j++) {
				if (j == i || j == k - i + 1) {
					System.out.print(c);
				}
				System.out.print(" ");
			}
			System.out.println();
		}
	}
}

Output

Enter Pattern Size : 
8
Enter Symbol : $
$              $ 
 $            $  
  $          $   
   $        $    
    $      $     
     $    $      
      $  $       
       $        
      $  $       
     $    $      
    $      $     
   $        $    
  $          $   
 $            $  
$              $ 

Star (X) Pattern Java Program: While Loop

This Java Program is following the below logic:

  1. While loop first checks the condition i.e i<=k, if it true, then it comes to the inner while loop.
  2. Inner while loop first checks the condition i.e j<=k, then it executes the logic in loop until the condition is false, then pointer come out of the inner loop and goes to the outer loop, this will continue until the condition i<=k is false.
package _1_patterns.xstar;

import java.util.Scanner;

public class XStarPatternWhileLoop {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		System.out.println("Enter Pattern Size : ");
		int size = sc.nextInt();

		System.out.print("Enter Symbol : ");
		char symbol = sc.next().charAt(0);

		drawXStarPattern(size, symbol);

		// Close Scanner
		sc.close();
	}

	private static void drawXStarPattern(int n, char c) {
		int i = 1;
		int j;
		int k = n * 2 - 1;

		while (i <= k) {
			j = 1;
			while (j <= k) {
				if (j == i || j == k - i + 1) {
					System.out.print(c);
				}
				System.out.print(" ");
				j++;
			}
			System.out.println();
			i++;
	}
}

Output

Enter Pattern Size : 
5
Enter Symbol : @
@        @ 
 @      @  
  @    @   
   @  @    
    @     
   @  @    
  @    @   
 @      @  
@        @ 

Star (X) Pattern Java Program: Do-While Loop

This Java Program is following the below logic:

  1. Inner do-while loop, first the code in the inner loop executes until the condition j<=k is false. It prints symbol for j=1, j=k-i+1. Other than these j values print space.
  2. If the condition false, then pointer comes to outer do-while loop and execute until the condition i<=k is false.
package _1_patterns.xstar;

import java.util.Scanner;

public class XStarPatternDoWhileLoop {
public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.println("Enter Pattern Size : ");
    int size = sc.nextInt();

    System.out.print("Enter Symbol : ");
    char symbol = sc.next().charAt(0);

    drawXStarPattern(size, symbol);

    // Close Scanner
    sc.close();
}

private static void drawXStarPattern(int n, char c) {
        int i = 1;
		int j;
		int k = n * 2 - 1;

		do {
			j = 1;
			do {
				if (j == i || j == k - i + 1) {
					System.out.print(c);
				}
				System.out.print(" ");
				j++;

			} while (j <= k);
			System.out.println();
			i++;
		} while (i <= k);
}
}

Output

Enter Pattern Size : 
6
Enter Symbol : ^
^          ^ 
 ^        ^  
  ^      ^   
   ^    ^    
    ^  ^     
     ^      
    ^  ^     
   ^    ^    
  ^      ^   
 ^        ^  
^          ^ 

Hope this post helps you to implement the Start (X) Pattern through Java Program. Please share your comments.

Happy Learning !!!

[Solved] SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: “No appropriate protocol (protocol is disabled or cipher suites are inappropriate)


This issue “SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: “No appropriate protocol (protocol is disabled or cipher suites are inappropriate)” was happening to me when upgrade from jDK 8_271 to JDK_8_341 and MSSQL driver.

Below are the stacktrace of the issue.

Stacktrace

Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "No appropriate protocol (protocol is disabled or cipher suites are inappropriate)".
	at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:1368)
	at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1412)
	at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1058)
	at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:833)
	at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:716)
	at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:841)
	at java.sql.DriverManager.getConnection(DriverManager.java:664)
	at java.sql.DriverManager.getConnection(DriverManager.java:208)
	at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153)
	at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144)
	at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:155)
	at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:120)
	at org.springframework.batch.item.database.AbstractCursorItemReader.initializeConnection(AbstractCursorItemReader.java:422)
	... 30 more
Caused by: javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)
	at sun.security.ssl.HandshakeContext.<init>(HandshakeContext.java:171)
	at sun.security.ssl.ClientHandshakeContext.<init>(ClientHandshakeContext.java:106)
	at sun.security.ssl.TransportContext.kickstart(TransportContext.java:238)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:410)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:389)
	at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1379)
	... 41 more

Solutions

SQL Server JDBC Driver versions are specific to JDK versions. Till JDK_8.271, JDBC driver versions supported as 4.1 however for the latest version JDK_8_341 use the SQL Server JDBC driver 8.4.1.

In my case this issue got resolved by updating the jar file as below:

Old Jar : mssql-jdbc4-2.0.jar

New Jar: mssql-jdbc-8.4.1.jre8.jar

Please refer below the complete SQLServer JDBC driver support matrix specific to Java/JDK versions.

https://learn.microsoft.com/en-us/sql/connect/jdbc/microsoft-jdbc-driver-for-sql-server-support-matrix?view=sql-server-ver16#java-and-jdbc-specification-support

Please share your comments if this solutions help you to resolve this issue.

Happy Learning !!!

[Solved] SQLServerException: The TCP/IP connection to the host ABCKXYZ356, port 1345 has failed


This is most common exception when connecting with database through Spring boot application. It’s happen because of connection failed to the database.

com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host ABCKXYZ356, port 1345 has failed. Error: "ABCKXYZ356. 
Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. 
Make sure that TCP connections to the port are not blocked by a firewall.".    
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:234) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:285) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2434) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:659) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:2546) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2216) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:2067) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1204) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:825) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-4.0.3.jar:na]    
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:364) ~[HikariCP-4.0.3.jar:na]    
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-4.0.3.jar:na]    
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:476) ~[HikariCP-4.0.3.jar:na]    
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561) ~[HikariCP-4.0.3.jar:na]    
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-4.0.3.jar:na]

Reason of Exception

These are main reason of this Exception:

  • This issue can occurred because of wrong properties configured for database connection.
  • This issue can also occurred if the database is not running.
  • This issue can also occurred if database only allow to access through vpn.

Solutions

These are some most common solution to resolve this issue:

  • Verify the connection properties.
  • Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port.
  • Make sure that TCP connections to the port are not blocked by a firewall.
  • Check the vpn connection if DB access allow over the vpn.

Hope these solutions help you to resolve this issue. Please share in comments.

Happy Learning !!!

JSON to JAVA Entities Mapping


In previous topics you learn JSON Overview and syntax, Now you will learn about the mapping between the JAVA and JSON entities mappings. These mapping helpful while encoding and decoding of JSON to Java object.

Mapping between JSON and JAVA entities

These are mapping between JSON and JAVA object

JSONJAVA
stringjava.lang.String
numberjava.lang.Number
true | falsejava.lang.Boolen
nullnull
arrayjava.util.List
objectjava.ulit.Map
JSON and JAVA object mapping

Please follow these example to map values. JSON Data Types & Syntax

Happy Learning !!!

Write a program to convert a non-negative integer number to its English words representation


In this program converting Non-negative numbers to English words through Java Program. You can use the same logic to implement with other languages like C, C++, C#, Python, etc.

This program is most frequently asked in programming label tests or interviews to check your logical skills. You can also utilize the same code while generating invoices, bills, reports where want to show sum, average, gross total etc. in form of words.

For Example :

InputOutput
123One Hundred Twenty Three
1234One Thousand Two Hundred Thirty Four
12345Twelve Thousand Three Hundred Forty Five
123456One Hundred Twenty Three Thousand Four Hundred Fifty Six
1234567One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven
1234568One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Eight
12345670Twelve Million Three Hundred Forty Five Thousand Six Hundred Seventy
123456709One Hundred Twenty Three Million Four Hundred Fifty Six Thousand Seven Hundred Nine
1234567090One Billion Two Hundred Thirty Four Million Five Hundred Sixty-Seven Thousand Ninety
Program to convert numbers to English Words

Java Program

To convert a number to English word core logic is to check 10th position of the number the add words for the same. Based on the range between billion to thousand then take reminder and add word (thousand, million or billion) etc. then further dividend of the number by the range and further pass for convert as long as not reaching to less than thousand. Finally, when numbers reach to between 1-20 take the words from map 1-20 range.

Source Code:

package programming;

import java.text.DecimalFormat;

public class NNNumberToWordExample {
	// array of string type for one digit numbers
	private static final String[] doubleDigits = { "", " Ten", " Twenty", " Thirty", " Forty", " Fifty", " Sixty",
			" Seventy", " Eighty", " Ninety" };
	// array of string for two digits numbers
	private static final String[] singleDigit = { "", " One", " Two", " Three", " Four", " Five", " Six", " Seven",
			" Eight", " Nine", " Ten", " Eleven", " Twelve", " Thirteen", " Fourteen", " Fifteen", " Sixteen",
			" Seventeen", " Eighteen", " Nineteen" };

	// converts a number to words (up to 1000)
	private static String convertUptoThousand(int number) {
		String soFar;
		if (number % 100 < 20) {
			soFar = singleDigit[number % 100];
			number = number / 100;
		} else {
			soFar = singleDigit[number % 10];
			number = number / 10;
			soFar = doubleDigits[number % 10] + soFar;
			number = number / 10;
		}
		if (number == 0)
			return soFar;
		return singleDigit[number] + " Hundred " + soFar;
	}

	// converts a long number (0 to 999999999) to string
	public static String convertNumberToWord(long number) {
		// checks whether the number is zero or not if number is zero return zero
		if (number == 0) {
			return "zero";
		}
		// convert long value to string
		String num = Long.toString(number);
		// for creating a mask padding with "0"
		String pattern = "000000000000";
		/**
		 * Convert to DecimalFormat using the specified pattern and also provides the
		 * symbols to default locale
		 */
		DecimalFormat decimalFormat = new DecimalFormat(pattern);
		// format a number of the DecimalFormat
		num = decimalFormat.format(number);
		/**
		 * format: XXXnnnnnnnnn the subString() method returns a new string that is a
		 * substring of this string the substring begins at the specified beginIndex and
		 * extends to the character at index endIndex - 1 the parseInt() method converts
		 * the string into integer
		 */
		int billions = Integer.parseInt(num.substring(0, 3));
		// format to: nnnXXXnnnnnn
		int millions = Integer.parseInt(num.substring(3, 6));
		// format to: nnnnnnXXXnnn
		int hundredThousands = Integer.parseInt(num.substring(6, 9));
		// format to: nnnnnnnnnXXX
		int thousands = Integer.parseInt(num.substring(9, 12));

		String tradBillions;

		switch (billions) {
		case 0:
			tradBillions = "";
			break;
		case 1:
			tradBillions = convertUptoThousand(billions) + " Billion ";
			break;
		default:
			tradBillions = convertUptoThousand(billions) + " Billion ";
		}

		String result = tradBillions;
		String tradMillions;
		switch (millions) {
		case 0:
			tradMillions = "";
			break;
		case 1:
			tradMillions = convertUptoThousand(millions) + " Million ";
			break;
		default:
			tradMillions = convertUptoThousand(millions) + " Million ";
		}
		result = result + tradMillions;

		String tradHundredThousands;
		switch (hundredThousands) {
		case 0:
			tradHundredThousands = "";
			break;
		case 1:
			tradHundredThousands = "One Thousand ";
			break;
		default:
			tradHundredThousands = convertUptoThousand(hundredThousands) + " Thousand ";
		}
		result = result + tradHundredThousands;

		String tradThousand;
		tradThousand = convertUptoThousand(thousands);
		result = result + tradThousand;

		// removing extra space if any
		return result.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b", " ");
	}

	public static void main(String args[]) {
		// Test cases to convert number to words
		System.out.println(convertNumberToWord(5));
		System.out.println(convertNumberToWord(89));
		System.out.println(convertNumberToWord(656));
		System.out.println(convertNumberToWord(1301));
		System.out.println(convertNumberToWord(13512));
		System.out.println(convertNumberToWord(567319));
		System.out.println(convertNumberToWord(90908890));
		System.out.println(convertNumberToWord(2000000000));
		System.out.println(convertNumberToWord(569999999));
		System.out.println(convertNumberToWord(3233000000L));
		System.out.println(convertNumberToWord(5000000));
		System.out.println(convertNumberToWord(333333333));
		System.out.println(convertNumberToWord(5000400));
		System.out.println(convertNumberToWord(600000));
		System.out.println(convertNumberToWord(4000000));
	}
}

Output

Five
Eighty Nine
Six Hundred Fifty Six
One Thousand Three Hundred One
Thirteen Thousand Five Hundred Twelve
Five Hundred Sixty Seven Thousand Three Hundred Nineteen
Ninety Million Nine Hundred Eight Thousand Eight Hundred Ninety
Two Billion 
Five Hundred Sixty Nine Million Nine Hundred Ninety Nine Thousand Nine Hundred Ninety Nine
Three Billion Two Hundred Thirty Three Million 
Five Million 
Three Hundred Thirty Three Million Three Hundred Thirty Three Thousand Three Hundred Thirty Three
Five Million Four Hundred 
Six Hundred Thousand 
Four Million 

Hope this program help you and clear your logics. Please share in comments.

Happy Learning !!!

[Solved] SQLServerException: Arithmetic overflow error converting float to data type numeric :scientific value


This SQLServerException is common with the applications using the MSSQL database. Once it occurs it generate the below stackTrace.

Exception Stack Trace

com.microsoft.sqlserver.jdbc.SQLServerException: Arithmetic overflow error converting float to data type numeric.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1515)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:404)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:350)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)

Reason of Exception

This issue occurred when your precision and scale argument is set two small for decimal column. For Example: decimal(3,2) or float(3,2) . It will float allow maximum value as 9.99

Basically the first argument (precision) is the max number of digits (in this case 3) and the second argument (scale) is the number of digits to the right of the decimal point, which always takes away from the number of digits you can have to the left of the decimal point. So in this case, 3-2 = 1 digit allowed to the left of the decimal point, which is why allow max value can only be 9.99.

if you will try numeric value more than this size Ex : 10.9 then SQL server will throw exception as “SQLServerException: Arithmetic overflow error converting float to data type numeric” because size is more than the defined precision and scale of decimal point.

Note : This issue can also be occurred when you are trying to insert big values in form of scientific notation Ex: 1.5e100 because it’s precision value is high so throw exception.

Solutions

You can follow any of these processes to resolve this issue:

  • Increase the precision and scale of decimal of your column based on your business requirement.
  • Convert the column type as float value so that accept values as per the set precision and scale.
  • You can also use try_cast also to truncate and change the type of passing value.

Hope these processes resolved this issue. Please share your response in comments.

Happy Learning !!!

[Solved] SQLServerException: Arithmetic overflow error converting float to data type numeric


This SQLServerException is common with the applications using the MSSQL database. Once it occurs it generate the below stackTrace.

Exception Stack Trace

com.microsoft.sqlserver.jdbc.SQLServerException: Arithmetic overflow error converting float to data type numeric.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1515)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:404)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:350)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)

Reason of Exception

This issue occurred when your precision and scale argument is set two small for decimal column. For Example: NUMERIC(3,2) or DECIMAL(3,2) . It will allow maximum value as 9.99

Basically the first argument (precision) is the max number of digits (in this case 3) and the second argument (scale) is the number of digits to the right of the decimal point, which always takes away from the number of digits you can have to the left of the decimal point. So in this case, 3-2 = 1 digit allowed to the left of the decimal point, which is why allow max value can only be 9.99.

if you will try numeric value more than this size Ex : 10.9 then SQL server will throw exception as “SQLServerException: Arithmetic overflow error converting float to data type numeric” because size is more than the defined precision and scale of decimal point.

Solutions

You can follow any of these processes to resolve this issue:

  • Increase the precision and scale of decimal of your column based on your business requirement.
  • Convert the column type as float value so that accept values as per the set precision and scale.

Hope these processes resolved this issue. Please share your response in comments.

Happy Learning !!!

[Solved] SQLServerException: String or binary data would be truncated


This SQLServerException is common with the applications using the MSSQL database. Once it occurs it generate the below stackTrace.

Exception Stack Trace

com.microsoft.sqlserver.jdbc.SQLServerException: String or binary data would be truncated. at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216) at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1515) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:404) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:350) at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)

Reason of Exception

This exception occurred when you are trying to insert text in a column of type varchar which is more than the size of defined column size then SQL server through this exception “SQLServerException: String or binary data would be truncated“.

Solutions

You can follow any of these processes to resolve this issue:

  • Apply validation for text length on the source frontend/client where you in insert the values. It should be less than or equal to size of column.
  • Apply truncation on text before inserting to the database and it should be less than the column size.
  • Increase the sufficient size of the column based on you requirement to resolve this issue.

Hope these processes resolved this issue. Please share your response in comments.

Happy Learning !!!

LIQUIBASE Spring Boot Properties


LIQUIBASE is a provider of Spring Boot Data for handling database schemas operations. LIQUIBASE is an Open Source tool which keep track of database schema script revisions. It can handle variety of database types and accepts a variety of file formats for defining the database structures.

See Also:

<dependency>
			<groupId>org.liquibase</groupId>
			<artifactId>liquibase-core</artifactId>
</dependency>

After adding LIQUIBASE dependencies in your application it will automatically download and add the required other dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .

Liquibase Configuration Properties

Spring Boot load these properties in LiquibaseProperties class.

NameDefault ValueDescription
liquibase.change-logclasspath:/db/ changelog/db.
changelog-master.yaml
Change log configuration path.
liquibase.check-change-log-locationtrueCheck the change log location exists.
liquibase.contexts Comma-separated list of runtime contexts to use.
liquibase.default-schema Default database schema.
liquibase.drop-firstfalseDrop the database schema first.
liquibase.enabledtrueEnable liquibase support.
liquibase.labels Comma-separated list of runtime labels to use.
liquibase.parameters.* Change log parameters.
liquibase.password Login password of the database to migrate.
liquibase.rollback-file File to rollback SQL statements will be written when an update is performed.
liquibase.url JDBC url of the database to migrate. Incase not set then use the primary configured data source.
liquibase.user Login user of the database to migrate.
LIQUIBASE Spring Boot Properties

References

https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

Happy Learning !!!

Cassandra Spring Boot Properties


Apache Cassandra is a provider of Spring Boot Data for handling NoSQL database operations. Apache Cassandra is a NoSQL distributed database for managing large amounts of data across many servers (clusters) while providing high availability at the cost of decreased consistency. Cassandra high availability is achieved by replicating data to multiple nodes over cluster and allow one or more nodes to go down so that transaction will continue till that point even one server is running.

To use Apache Cassandra in your Spring boot application you have to add this Cassandra starter in your pom.xml .

<dependency>
         <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-cassandra</artifactId>
        <version>2.0.0.M7</version>
</dependency>

After adding Cassandra Database starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .

Cassandra Configuration Properties

Spring Boot load these properties in CassandraProperties class.

NameDefault ValueDescription
spring.data.cassandra.cluster-name Cassandra cluster Name.
spring.data.cassandra.compression Compression supported by the Cassandra binary protocol.
spring.data.cassandra.connect-timeout-millis Socket option: connection time out.
spring.data.cassandra.consistency-level Queries consistency level.
spring.data.cassandra.contact-pointslocalhostComma-separated cluster node addresses.
spring.data.cassandra.fetch-size Queries default fetch size.
spring.data.cassandra.keyspace-name Keyspace name to use.
spring.data.cassandra.load-balancing-policy Class name of the load balancing policy.
spring.data.cassandra.port Port of the Cassandra server.
spring.data.cassandra.password Login password of the server.
spring.data.cassandra.read-timeout-millis Socket option: read time out.
spring.data.cassandra.reconnection-policy Reconnection policy class.
spring.data.cassandra.repositories.enabled Enable Cassandra repositories.
spring.data.cassandra.retry-policy Class name of the retry policy.
spring.data.cassandra.serial-consistency-level Queries serial consistency level.
spring.data.cassandra.schema-actionnoneSchema action to take at startup.
spring.data.cassandra.sslfalseEnable SSL support.
spring.data.cassandra.username Login user of the server.
Cassandra Spring Boot Properties

References

https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

Happy Learning !!!

Couchbase Spring Boot Properties


Couchbase is a provider of Spring Boot for handling NoSQL database operations through JSON. Couchbase is NoSQL document oriented distributed database over the cloud or on- premises which perform transactions by JSON and provide unmatched versatility, performance and scalability. To use Couchbase in your Spring boot application you have to add this Couchbase starter in your pom.xml .

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-couchbase</artifactId>
    <version>2.6.3</version>
</dependency>

After adding Couchbase Database starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .

Data Couchbase Configuration Properties

Spring Boot load these properties in CouchbaseDataProperties class.

NameDefault ValueDescription
spring.data.couchbase.auto-indexfalsecreate views and indexes automatically.
spring.data.couchbase.consistencyread-your-own-writesBy default Consistency to apply on generated queries.
spring.data.couchbase.repositories.enabledtrueEnable Couchbase repositories.
Data Couch Spring Boot properties

Couchbase Configuration Properties

Spring Boot load these properties in CouchbaseProperties class.

NameDefault ValueDescription
spring.couchbase.bootstrap-hosts Couchbase nodes host/IP address to bootstrap from.
spring.couchbase.bucket.namedefaultbucket name connect to.
spring.couchbase.bucket.password bucket password.
spring.couchbase.env.endpoints.key-value1Number of sockets per node for each Key/value service.
spring.couchbase.env.endpoints.query1Number of sockets per node for each Query (N1QL) service.
spring.couchbase.env.endpoints.view1Number of sockets per node for each view service.
spring.couchbase.env.ssl.enabled Enable SSL support. Enabled automatically if a “keyStore” is provided otherwise specified otherwise.
spring.couchbase.env.ssl.key-store Path to JVM key store which holds the certificates.
spring.couchbase.env.ssl.key-store-password Password used to access the key store.
spring.couchbase.env.timeouts.connect5000Bucket connections timeout. (in milliseconds)
spring.couchbase.env.timeouts.key-value2500Blocking operations performed on a key timeout.( in milliseconds)
spring.couchbase.env.timeouts.query7500N1QL query operations timeout.( in milliseconds)
spring.couchbase.env.timeouts.socket-connect1000Socket connect connections timeout.( in milliseconds).
spring.couchbase.env.timeouts.view7500Regular and geospatial view operations timeout. (in milliseconds).
Couchbase Spring Boot Properties

References

https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

Happy Learning !!!

SOLR Spring Boot Properties


Apache SOLR is a provider of Spring Boot for handling search and indexing of data operations on SOLR content for web. SOLR is a Full Text search engine for content management and also provide REST based SOLR APIs for operations. To use SOLR in your Spring boot application you have to add this SOLR starter in your pom.xml .

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-solr</artifactId>
    <version>2.4.12</version>
</dependency>

After adding SOLR starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .

SOLR Configuration Properties

Spring Boot load these properties in SolrProperties class.

NameDefault ValueDescription
spring.data.solr.hosthttp://127.0.0.1:8983/solrSolr host. Ignored if “zk-host” is set.
spring.data.solr.repositories.enabledtrueEnable Solr repositories.
spring.data.solr.zk-host ZooKeeper host address i.e HOST:PORT.
SOLR Spring Boot Properties

References

https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

Happy Learning !!!

Elasticsearch Spring Boot Properties


Elasticsearch is a provider of Spring Boot for handling search and CRUD operations in Elastic Search. Elasticsearch is a Full Text search engine and also provide REST based Elasticsearch APIs for operations. To use Elastic Search in your Spring boot application you have to add this Elasticsearch starter in your pom.xml .

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

After adding Elasticsearch starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .

ElasticSearch Configuration Properties

Spring Boot load these properties in ElasticsearchProperties class.

NameDefault ValueDescription
spring.data.elasticsearch.cluster-nameelasticsearchcluster name.
spring.data.elasticsearch.cluster-nodes Comma-separated cluster node addresses. If not specified, starts a client node.
spring.data.elasticsearch.properties.* Additional properties used to configure the client.
spring.data.elasticsearch.repositories.enabledtrueEnable Elasticsearch repositories.
Elastic Search Spring Boot Properties

JEST (Elasticsearch HTTP client) Configuration Properties

Spring Boot load these properties in JestProperties class.

NameDefault ValueDescription
spring.elasticsearch.jest.connection-timeout3000Connection timeout in milliseconds.
spring.elasticsearch.jest.password Login password.
spring.elasticsearch.jest.proxy.host Proxy host the HTTP client to use.
spring.elasticsearch.jest.proxy.port Proxy port the HTTP client to use.
spring.elasticsearch.jest.read-timeout3000Read timeout. (in milliseconds)
spring.elasticsearch.jest.urishttp://localhost:9200Comma-separated Elasticsearch instances to use.
spring.elasticsearch.jest.username Login user.
JEST/Elastic Search Client Spring Boot Properties

References

https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

Happy Learning !!!

MongoDB Spring Boot Properties


MongoDB is a provider of Spring Boot for handling NoSQL database operations. To use MongoDB  in your Spring boot application you have to add this MongoDB starter in your pom.xml .

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

After adding MongoDB starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .

Embedded MongoDB Configuration Properties

Spring Boot load these properties in EmbeddedMongoProperties class.

NameDefault ValueDescription
spring.mongodb.embedded.featuresSYNC_DELAYComma-separated features to enable.
spring.mongodb.embedded.storage.database-dir Directory used for data storage.
spring.mongodb.embedded.storage.oplog-size Maximum size of the oplog in megabytes.
spring.mongodb.embedded.storage.repl-set-name Name of the replica set.
spring.mongodb.embedded.version2.6.10Version of Mongo to use.
MongoDB Embedded Spring Boot Properties

MongoDB Configuration Properties

Spring Boot load these properties in MongoProperties class.

NameDefault ValueDescription
spring.data.mongodb.authentication-database Authentication database name.
spring.data.mongodb.databasetestDatabase name.
spring.data.mongodb.field-naming-strategy USe Fully qualified name of the FieldNamingStrategy.
spring.data.mongodb.grid-fs-database GridFS database name.
spring.data.mongodb.hostlocalhostMongo server host.
spring.data.mongodb.password Login password of the mongo server.
spring.data.mongodb.port27017Mongo server port.
spring.data.mongodb.repositories.enabledtrueEnable Mongo repositories.
spring.data.mongodb.urimongodb://localhost/testMongo database URI.host and port are ignored when setting it.
spring.data.mongodb.username Login user of the mongo server.
MongoDB Spring Boot Properties

References

https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

Neo4J Spring Boot Properties


Neo4J is a provider of Spring Boot for handling Graphical database.  Neo4J is a graphical datbase where need to represent stored data in graphical relational forms. You can add Neo4J  in your Spring boot application by adding Neo4J starter in your pom.xml (Maven) or build.gradle (Gradle).

Maven

<dependency>
        <groupId>org.neo4j.driver</groupId>
        <artifactId>neo4j-java-driver-spring-boot-starter</artifactId>
        <version>4.3.6.0</version>
</dependency>

Gradle

dependencies {
    compile 'org.neo4j.driver:neo4j-java-driver-spring-boot-starter:4.3.6.0'
}

After adding Neo4J starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .

Neo4j Configuration Properties

Spring Boot load these properties in Neo4jProperties class.

NameDefault ValueDescription
spring.data.neo4j.compiler Compiler to use.
spring.data.neo4j.embedded.enabledtrueEnable embedded mode when embedded driver is available.
spring.data.neo4j.password Login password of the server.
spring.data.neo4j.repositories.enabledtrueEnable Neo4j repositories.
spring.data.neo4j.session.scopesingletonScope (lifetime) of the session.
spring.data.neo4j.uri URI used by the driver detected by default.
spring.data.neo4j.username Login user of the server.
NEO4J Spring Boot Properties

References

https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

Happy Learning !!!

ATOMIKOS Spring Boot Properties


ATOMIKOS is a provider of Spring Boot for handling transactions atomicity in global transactions involving heterogeneous components. To use ATOMIKOS transaction manager in your Spring boot application you have to add this ATOMIKOS starter in your pom.xml .

<dependency>
      <groupId>com.atomikos</groupId>
      <artifactId>transactions-spring-boot-starter</artifactId>
   </dependency>

After adding ATOMIKOS starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .

Atomikos Configuration Properties

Spring Boot load these properties in AtomikosProperties class.

NameDefault ValueDescription
spring.jta.atomikos.connectionfactory.borrow-connection-timeout30Timeout for borrowing connections from the pool. (in seconds)
spring.jta.atomikos.connectionfactory.ignore-session-transacted-flagtrueSet to ignore the transacted flag when creating session.
spring.jta.atomikos.connectionfactory.local-transaction-modefalseSet local transactions are desired.
spring.jta.atomikos.connectionfactory.maintenance-interval60The time between runs of the pool’s maintenance thread. (in seconds).
spring.jta.atomikos.connectionfactory.max-idle-time60The time after which connections are cleaned up from the pool. (in seconds)
spring.jta.atomikos.connectionfactory.max-lifetime0The time that a connection can be pooled for before being destroyed. 0 denotes no limit.(in seconds)
spring.jta.atomikos.connectionfactory.max-pool-size1The maximum pool size.
spring.jta.atomikos.connectionfactory.min-pool-size1The minimum pool size.
spring.jta.atomikos.connectionfactory.reap-timeout0The reap timeout for borrowed connections. 0 denotes no limit.( in seconds)
spring.jta.atomikos.connectionfactory.unique-resource-namejmsConnectionFactoryThe unique name used to identify the resource during recovery.
spring.jta.atomikos.datasource.borrow-connection-timeout30Timeout for borrowing connections from the pool. (in seconds)
spring.jta.atomikos.datasource.default-isolation-level Default isolation level of connections provided by the pool.
spring.jta.atomikos.datasource.login-timeout Timeout for establishing a database connection.(in seconds)
spring.jta.atomikos.datasource.maintenance-interval60The time between runs of the pool’s maintenance thread.(in seconds)
spring.jta.atomikos.datasource.max-idle-time60The time after which connections are cleaned up from the pool.(in seconds)
spring.jta.atomikos.datasource.max-lifetime0The time that a connection can be pooled for before being destroyed. 0 denotes no limit.(in seconds)
spring.jta.atomikos.datasource.max-pool-size1The maximum pool size.
spring.jta.atomikos.datasource.min-pool-size1The minimum pool size.
spring.jta.atomikos.datasource.reap-timeout0The reap timeout for borrowed connections. 0 denotes no limit.(in seconds)
spring.jta.atomikos.datasource.test-query SQL query or statement used to validate a connection before returning it.
spring.jta.atomikos.datasource.unique-resource-namedataSourceThe unique name used to identify the resource during recovery.
spring.jta.atomikos.properties.checkpoint-interval500Interval between checkpoints.
spring.jta.atomikos.properties.default-jta-timeout10000Default timeout for JTA transactions.
spring.jta.atomikos.properties.enable-loggingtrueEnable disk logging.
spring.jta.atomikos.properties.force-shutdown-on-vm-exitfalseSpecify if a VM shutdown should trigger forced shutdown of the transaction core.
spring.jta.atomikos.properties.log-base-dir Directory in which the log files should be stored.
spring.jta.atomikos.properties.log-base-nametmlogTransactions log file base name.
spring.jta.atomikos.properties.max-actives50Maximum active transactions.
spring.jta.atomikos.properties.max-timeout300000Maximum timeout that can be allowed for transactions. (in milliseconds)
spring.jta.atomikos.properties.serial-jta-transactionstrueSpecify if sub-transactions should be joined when possible.
spring.jta.atomikos.properties.service Transaction manager implementation that should be started.
spring.jta.atomikos.properties.threaded-two-phase-committrueUse different (and concurrent) threads for two-phase commit on the resources.
spring.jta.atomikos.properties.transaction-manager-unique-name Transaction manager’s unique name.
ATOMIKOS Spring Boot Properties

References

https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

Happy Leaning !!!

BITRONIX Spring Boot Properties


BITRONIX is a provider of Spring Boot for handling distributed transaction. To use BITRONIX transaction manager in your Spring boot application you have to add this BITRONIX starter in your pom.xml .

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-jta-bitronix</artifactId>
 </dependency>

After adding BITRONIX starter in your application it will automatically download and add the required dependencies in your application and initialize with default values. You can overwrite these values through application.properties / application.yaml .

BiTronix Configuration Properties

NameDefault ValueDescription
spring.jta.bitronix.connectionfactory.acquire-increment1Number of connections to create when pool grow.
spring.jta.bitronix.connectionfactory.acquisition-interval1Time to wait before trying to acquire a connection again after an invalid connection was acquired.(in second)
spring.jta.bitronix.connectionfactory.acquisition-timeout30Timeout for acquiring connections from the pool. (in second)
spring.jta.bitronix.connectionfactory.allow-local-transactionstrueSet the transaction manager should allow mixing XA and non-XA transactions.
spring.jta.bitronix.connectionfactory.apply-transaction-timeoutfalseSet the transaction timeout should be set on the XAResource when it is enlisted.
spring.jta.bitronix.connectionfactory.automatic-enlisting-enabledtrueSet resources should be enlisted and delisted automatically
spring.jta.bitronix.connectionfactory.cache-producers-consumerstrueSet produces and consumers should be cached.
spring.jta.bitronix.connectionfactory.defer-connection-releasetrueSet the provider can run many transactions on the same connection and supports transaction interleaving.
spring.jta.bitronix.connectionfactory.ignore-recovery-failuresfalseSet recovery failures should be ignored.
spring.jta.bitronix.connectionfactory.max-idle-time60The time after which connections are cleaned up from the pool.(in second)
spring.jta.bitronix.connectionfactory.max-pool-size10The maximum pool size. 0 denotes no limit.
spring.jta.bitronix.connectionfactory.min-pool-size0The minimum pool size.
spring.jta.bitronix.connectionfactory.password The password to use to connect to the JMS provider.
spring.jta.bitronix.connectionfactory.share-transaction-connectionsfalseSet connections in the ACCESSIBLE state can be shared within the context of a transaction.
spring.jta.bitronix.connectionfactory.test-connectionstrueSet connections should be tested when acquired from the pool.
spring.jta.bitronix.connectionfactory.two-pc-ordering-position1The position that this resource should take during two-phase commit (always first is Integer.MIN_VALUE, always last is Integer.MAX_VALUE).
spring.jta.bitronix.connectionfactory.unique-namejmsConnectionFactoryThe unique name used to identify the resource during recovery.
spring.jta.bitronix.connectionfactory.use-tm-jointrue Set TMJOIN should be used when starting XAResources.
spring.jta.bitronix.connectionfactory.user The user to use to connect to the JMS provider.
spring.jta.bitronix.datasource.acquire-increment1Number of connections to create when growing the pool.
spring.jta.bitronix.datasource.acquisition-interval1Time to wait before trying to acquire a connection again after an invalid connection was acquired.(in second)
spring.jta.bitronix.datasource.acquisition-timeout30Timeout for acquiring connections from the pool. (in second)
spring.jta.bitronix.datasource.allow-local-transactionstrueSet the transaction manager should allow mixing XA and non-XA transactions.
spring.jta.bitronix.datasource.apply-transaction-timeoutfalseSet the transaction timeout should be set on the XAResource when it is enlisted.
spring.jta.bitronix.datasource.automatic-enlisting-enabledtrueSet resources should be enlisted and delisted automatically.
spring.jta.bitronix.datasource.cursor-holdability The default cursor holdability for connections.
spring.jta.bitronix.datasource.defer-connection-releasetrueSet the database can run many transactions on the same connection and supports transaction interleaving.
spring.jta.bitronix.datasource.enable-jdbc4-connection-test Set Connection.isValid() is called when acquiring a connection from the pool.
spring.jta.bitronix.datasource.ignore-recovery-failuresfalseSet recovery failures should be ignored.
spring.jta.bitronix.datasource.isolation-level The default isolation level for connections.
spring.jta.bitronix.datasource.local-auto-commit The default auto-commit mode for local transactions.
spring.jta.bitronix.datasource.login-timeout Timeout for establishing a database connection.(in second)
spring.jta.bitronix.datasource.max-idle-time60The time after which connections are cleaned up from the pool.(in second)
spring.jta.bitronix.datasource.max-pool-size10The maximum pool size. 0 denotes no limit.
spring.jta.bitronix.datasource.min-pool-size0The minimum pool size.
spring.jta.bitronix.datasource.prepared-statement-cache-size0The target size of the prepared statement cache. 0 disables the cache.
spring.jta.bitronix.datasource.share-transaction-connectionsfalseSet connections in the ACCESSIBLE state can be shared within the context of a transaction.
spring.jta.bitronix.datasource.test-query SQL query or statement used to validate a connection before returning it.
spring.jta.bitronix.datasource.two-pc-ordering-position1The position that this resource should take during two-phase commit (always first is Integer.MIN_VALUE, always last is Integer.MAX_VALUE).
spring.jta.bitronix.datasource.unique-namedataSourceThe unique name used to identify the resource during recovery.
spring.jta.bitronix.datasource.use-tm-jointrue Set TMJOIN should be used when starting XAResources.
spring.jta.bitronix.properties.allow-multiple-lrcfalseAllow multiple LRC resources to be enlisted into the same transaction.
spring.jta.bitronix.properties.asynchronous2-pcfalseEnable asynchronously execution of two phase commit.
spring.jta.bitronix.properties.background-recovery-interval-seconds60Interval at which to run the recovery process in the background.(in seconds)
spring.jta.bitronix.properties.current-node-only-recoverytrueRecover only the current node.
spring.jta.bitronix.properties.debug-zero-resource-transactionfalseLog the creation and commit call stacks of transactions executed without a single enlisted resource.
spring.jta.bitronix.properties.default-transaction-timeout60Default transaction timeout.(in second)
spring.jta.bitronix.properties.disable-jmxfalseEnable JMX support.
spring.jta.bitronix.properties.exception-analyzer Set the fully qualified name of the exception analyzer implementation to use.
spring.jta.bitronix.properties.filter-log-statusfalseEnable filtering of logs so that only mandatory logs are written.
spring.jta.bitronix.properties.force-batching-enabledtrueSet if disk forces are batched.
spring.jta.bitronix.properties.forced-write-enabledtrueSet if logs are forced to disk.
spring.jta.bitronix.properties.graceful-shutdown-interval60Maximum amount of seconds the TM will wait for transactions to get done before aborting them at shutdown time.
spring.jta.bitronix.properties.jndi-transaction-synchronization-registry-name JNDI name of the TransactionSynchronizationRegistry.
spring.jta.bitronix.properties.jndi-user-transaction-name JNDI name of the UserTransaction.
spring.jta.bitronix.properties.journaldiskName of the journal. Can be ‘disk’, ‘null’ or a class name.
spring.jta.bitronix.properties.log-part1-filenamebtm1.tlogName of the first fragment of the journal.
spring.jta.bitronix.properties.log-part2-filenamebtm2.tlogName of the second fragment of the journal.
spring.jta.bitronix.properties.max-log-size-in-mb2Maximum size in megabytes of the journal fragments.
spring.jta.bitronix.properties.resource-configuration-filename ResourceLoader configuration file name.
spring.jta.bitronix.properties.server-id ASCII ID that must uniquely identify this TM instance. Default to the machine’s IP address.
spring.jta.bitronix.properties.skip-corrupted-logsfalseSkip corrupted transactions log entries.
spring.jta.bitronix.properties.warn-about-zero-resource-transactiontrueLog a warning for transactions executed without a single enlisted resource.
BITRONIX Spring Boot Properties

References

https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

Happy Learning !!!

NARAYANA Spring Boot Properties


Narayana is a popular open source JTA transaction manager implementation supported by Red Hat. To use Narayana JTA in your Spring Boot application you can use You can use the narayana-spring-boot-starter starter to add the appropriate Narayana dependencies to your application.

NARAYANA pom.xml Dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jta-narayana</artifactId>
</dependency>

Spring Boot automatically configures Narayana with default values and post-processes your beans to ensure that startup and shutdown ordering is correct.

NARAYANA Spring Boot Properties

Spring Boot load these properties in NarayanaProperties class with default values you can overwrite these values in your application application.properties/ application.yaml.

NameDefault ValueDescription
spring.jta.narayana.default-timeout60Transaction timeout.(in second)
spring.jta.narayana.expiry-scannerscom.arjuna.ats.internal. arjuna.recovery. ExpiredTransactionStatusManagerScannerComma-separated list of expiry scanners.
spring.jta.narayana.log-dir Transaction object store directory.
spring.jta.narayana.one-phase-committrueEnable one phase commit optimisation.
spring.jta.narayana.periodic-recovery-period120Interval in which periodic recovery scans are performed.(in second)
spring.jta.narayana.recovery-backoff-period10Back off period between first and second phases of the recovery scan.(in second)
spring.jta.narayana.recovery-db-pass Database password for recovery manager.
spring.jta.narayana.recovery-db-user Database username for recovery manager.
spring.jta.narayana.recovery-jms-pass JMS password for recovery manager.
spring.jta.narayana.recovery-jms-user JMS username for recovery manager.
spring.jta.narayana.recovery-modules Comma-separated recovery modules.
spring.jta.narayana.transaction-manager-id1Unique transaction manager id.
spring.jta.narayana.xa-resource-orphan-filters Comma-separated orphan filters.

By default, Narayana transaction logs written location is  transaction-logs directory in your application home directory (the directory in which your application jar file resides). You can customize the location of this directory by setting the narayana.log-dir or spring.jta.log-dir similar to that you can also customize the other properties.

References

Happy Learning !!!

Springboot Framework Exception Hierarchy


Springboot framework having following exceptions. These Spring exceptions occurred while developing applications.

Springboot Framework Exception Hierarchy

References

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/NestedRuntimeException.html

Top [70] HR & Manager Round Interview Questions


HR & Managerial round interview questions can cover a diverse range of discussion topics apart from Technical. These questions asked generally asked by laterals or experienced persons to check his/her personality/behaviour. In some organizations, this is also called a behaviour round of interviews. Generally, the interviewer observes these areas from your answers:

  1. Observe your expressions
  2. Check your leadership skills/soft skills
  3. Team handling skills
  4. Fit for organization cuture or not
  5. Client handling skills
  6. Handling on critical, stressed and pressurise work environment.
How to introduce yourself

The interviewer can create different scenarios for organization culture, team conflicts situation and some cases ask for combination with technology-related questions. Based on answered will ask for further questions. In such type questions, the interviewer wants to understand how you cope with change, approach learning, and overcome challenges and obstacles.

In this article, we share some behaviour round interview questions with sample answers and also provide an overview of some additional example questions to prepare with a scenario that will fit your profile.

Do you have any questions?

How to answer to such behaviour and situational quetions?

To prepare for these questions, take a moment to think of a number of challenging situations you have faced, such as difficulty with new technology, project, timeline, customer, ambiguity, process, or even a team member. Think of situations where you were challenged with what was the right thing to do. What did you do and how did you handle it? and how you can fit your previous experiences with current organization requirements.

Always keep in mind the STAR rule to answer such behavioural questions.

  • S – Situation. What was the situation? Describe in brief. (This is the challenge you were facing.)
  • T – Task. What was the task you were assigned? What was your responsibility?
  • A – Action. What action did you take?
  • R – Result. What happened because of your action?

You can use examples for reference and resolution you provided on a particular case.

What are your strengths?

Some of most frequently asked questions in behavioural interview

Common Interview Questions

These are common interview questions that can be asked in technical as well as in behavioural/manager/HR rounds of interviews. Through these questions, the interviewer wants to check your communication, understanding of your educational and professional background
and your core technical skills instead of going through the complete CV.

  1. Tell Me About Yourself. Example
  2. Do you have any questions for us? Example
  3. What is your technical streagths and rate yourself in out of 10 points? Example
  4. Tell us about your educational and technical background. Example

Behavioural Questions


These questions are to check your personality, how you are socially connected, motivated and performed as an individual as part of the team so that interviewer can understand your compatibility with your current position requirement.

  1. How might you describe yourself? Example
  2. How might your friends describe you? Example
  3. What is your work ethic like? Example
  4. What are your strengths and weaknesses? Example
  5. Where Do You See Yourself In 5 Years? Example
  6. Why do you believe you are a good fit for this position? Example
  7. What is your idea of a friendly work environment? Example
  8. How do you react to sudden changes in the work you are doing? Example
  9. Share with us reasons you think we should hire you. Example
  10. If you could work in any position, what job might you want and why? Example
  11. Where did you learn about this open position? Example
  12. Have you ever worked in a leadership position? Example
  13. Share with us how you have emerged as a leader in the past. Example
  14. Talk to us about your skills, and how you believe they can help you excel in this position. Example
  15. How do you intend to continue expanding your professional skills? Example
  16. What roles have you previously worked in? Example
  17. What companies have you previously worked for? Example
  18. Do you have any references from previous experiences that we can contact? Example
  19. Explain the duties you have handled in the past. Example
  20. Have you ever received recognition for being a leader? Example
  21. How do you introduce new ideas or operations to teams? Example
  22. Why are you interested in leaving your current job? Example
  23. What feedback have previous managers given you about your work? Example
  24. How do you prioritise your tasks? Example
  25. Can you explain this gap in your resume? Example
  26. What are your salary expectations? Example
  27. Why Do You Want to Work Here? Example
  28. Why Should We Hire You? Example
  29. What Are Your Career Goals? Example
  30. What Is Your Greatest Accomplishment? Example

Situational Questions


These questions generally asked for lateral roles as lead or manager where you need to handle team or more on interacting with clients.

  1. What process might you use to make presentations for clients? Example
  2. Have you faced any hard time with client? Example
  3. What is your greatest professional accomplishment? Example
  4. Have you faced any critism from client or coworker? if yes, how you handled it? Example
  5. Have you faced any conflict with team or your manager? How did you deal with it? Example
  6. Have you resolved any conflict between team members? How did you deal with it? Example
  7. How do you handle workplace pressures? Example or
  8. Tell me about a time when you were under a lot of pressure. How did you handle it? Example
  9. Tell me about a time when you faced conflict at work. Example
  10. What is your greatest achievement? Example
  11. Tell me about a time you went above and beyond for work. Example
  12. Give me an example of a time you made a mistake. How did you manage the consequences? Example
  13. How would you respond to a request for doing a task you’ve never done before? Example
  14. Did you ever have to collaborate with a difficult coworker? How did you manage the situation? Example
  15. Tell me about a time when you handled a challenging situation. Example
  16. Was there a time when you were overwhelmed with work? How did you handle the situation? Example
  17. Sometimes almost impossible todo what are the things in our todo list. What you will do when your list of responsibilities overwhelming. Example
  18. Tell me a situation where you took the initiative to fix a problem. Example
  19. Tell me about a time when you and the team you were managing had opposing views on an issue. How did you get to a conclusion? Example
  20. How you accomplish task when there is tight deadline. Example
  21. Describe a long term project you managed. How did you make sure everything was running smoothly. Example
  22. Tell me about a time you had to deal with a client that was asking the impossible. Example
  23. Was there a time when you had to be very strategic in order to meet a goal?
  24. Give me an example of a situation when you showed initiative and took charge of a situation.
  25. Tell me about a time when you went above and beyond your duties for a job or task.
  26. Did you ever have to correct one of your superiors when they were wrong? How did you approach that situation?
  27. Have you ever had to work under a tight deadline?
  28. How do you deal with coworkers that don’t cooperate or can’t contribute enough?
  29. Tell me about a time when a client was asking for the impossible. How did you explain and communicate this to them?
  30. Give me an example of a time when you didn’t meet a client’s expectations. How did you deal with the situation?
  31. Is there a situation you think you could’ve handled better or differently?
  32. How do you adapt to sudden changes in the workplace? Could you give me an example? Example
  33. Tell me about a time when you had to think on your feet in order to deal with a situation.
  34. Sometimes employers put too much on their employees’ plates. Was there a time when you were overwhelmed with work? How did you handle the situation?
  35. Tell me about a time when you had the liberty to be creative with your work. Was it exciting or difficult for you?

You can go through these questions to prepare any interview with your scenarios that best fit your roles and responsibility.

Share your thoughts about these questions and also share if you faced any other questions to help others.

Happy Learning !!!

Spring Boot : Set JVM Parameters for an Application


In Spring Boot application, you can set the JVM parameters by two ways so that increase the JVM heap size, in case required you can also configure the other parameters like GC alogorithms, MetaSpace etc.

  • Configure Parameters in pom.xml: To pass the JVM parameters for an application , we can set these parameters in spring-boot-maven-plugin in pom.xml plugin section.
<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <jvmArguments>-Xms512m -Xmx1024m -XX:+UseZGC -XX:MaxMetaspaceSize=512m</jvmArguments>
    </configuration>
</plugin>
  • Pass JVM parameters through Command line: We can pass the JVM parameters through the command line while running the Spring Boot application jar file.
java -jar zyz-service.jar -Dspring-boot.run.jvmArguments="-Xms512m -Xmx1024m -XX:+UseZGC -XX:MaxMetaspaceSize=512m"

Note: In both the cases these parameters are as below :

  • -Xms512m : Minimum heap size allocate for JVM as 512 MB.
  • -Xmx1024m : Max heap size can be allocate for JVM as 1024 MB.
  • -XX:+UseZGC : Garbage collection algorithm as Z Garbage Collector.
  • -XX:MaxMetaspaceSize=512m : By default in Java 8 or after the MetaSpace size is unlimited but we can configure fix Max limit also.

Let me know the your thought on this post. If this was helpful for make a comment.

Happy Learning !!!

[Solved] OpenShift : MetaSpace Issue with SpringBoot based Micro-services


The java.lang.OutOfMemoryError: Metaspace indicates that allocated native memory for Java class metadata is exausted. That’s why issue occured in standalone and cloud based applications.

In Java 8 and later versions, the maximum amount of memory allocated for Java classes (MaxMetaspaceSize) is by default unlimited, so in most cases there is no need to change this setting. On the other hand, if you want to fix the amount of memory allocated for Java classes, you can set it as follows:

java -XX:MaxMetaspaceSize=1024m

This JVM parameter -XX:MaxMetaspaceSize is just an set the upper limit of MetaSpace. The current Metaspace size (i.e. committed) will be smaller. In fact, there is a setting called MaxMetaspaceFreeRatio (default 70%) which means that the actual metaspace size will never exceed 230% of its occupancy.

And for it to grow it first would have to fill up, forcing a garbage collection in an attempt to free objects and only when it cannot meet its MinMetaspaceFreeRatio (default 40%) goal it would expand the current metaspace. That can however not be greater than 230% of the occupancy after the GC cycle.

Monitoring MetaSpace Size with Java Native Memory tracking

A good way to monitor the exact amount of Metadata is by using the NativeMemoryTracking, which can be added through the following settings:

-XX:+UnlockDiagnosticVMOptions -XX:NativeMemoryTracking=detail -XX:+PrintNMTStatistics

When Native Memory Tracking is enabled, you can request a report on the JVM memory usage using the following command:

$ jcmd <pid> VM.native_memory

OutOfMemoryError: Metaspace on OpenShift/Kubernetes

When using openjdk Image on OpenShift/Kubernetes, the default maxium value for the Metaspace is XX:MaxMetaspaceSize=100m. You might have noticed that setting this value through the JAVA_OPTIONS environment variable, doesn’t work as the default value is appended to the bottom:

VM Arguments: -Xms128m -Xmx1024m -XX:MetaspaceSize=128M -XX:MaxMetaspaceSize=256m    -XX:AdaptiveSizePolicyWeight=90 -XX:MaxMetaspaceSize=100m -XX:+ExitOnOutOfMemoryError

Once the MetaSpace get full in your application it will stop the service and through exception as below in your logs.

oc logs XYZ-service-7b856cc89-kpc6k  | grep -i metaspace
INFO exec  java -javaagent:/usr/share/java/jolokia-jvm-agent/jolokia-jvm.jar=config=/opt/jboss/container/jolokia/etc/jolokia.properties -XX:+UseParallelOldGC -XX:MinHeapFreeRatio=10 -XX:MaxHeapFreeRatio=20 -XX:GCTimeRatio=4 -XX:AdaptiveSizePolicyWeight=90 -XX:MaxMetaspaceSize=100m -XX:+ExitOnOutOfMemoryError -cp "." -jar /deployments/XYZ-service-0.0.1-SNAPSHOT.jar
Picked up JAVA_TOOL_OPTIONS:  -Dappdynamics.agent.accountAccessKey=600a90af-582a-4ae2-87b1-4599708b65dd -Dappdynamics.agent.reuse.nodeName=true -Dappdynamics.socket.collection.bci.enable=true -XX:MaxMetaspaceSize=1024m -javaagent:/opt/appdynamics-java/javaagent.jar
Terminating due to java.lang.OutOfMemoryError: Metaspace

Solutions

The correct way to set the MaxMetaspaceSize is through the GC_MAX_METASPACE_SIZE environment variable. Here are the different cases ti implement this solutions:

  • Jenkins Pipeline: For example, if you are using a jenkins pipeline to deploy your application or services then you can meke following changes in the json template to refelect these changes in deployment.yaml file to deploy your application with JKube, the following settings will override the default values for the MaxMetaspaceSize and MaxMetaspaceSize:
spec:
  template:
    spec:
      containers:
      - env:
        - name: JAVA_OPTIONS
          value: '-Xms256m -Xmx1024m'
        - name: GC_MAX_METASPACE_SIZE
          value: 1024
        - name: GC_METASPACE_SIZE
          value: 256
  • Manual Deployment through S2I: You can directly pass these MetaSpace parameters while deploying your service manually.
oc new-app xyz-service -e JAVA_OPTIONS="-Xms256m -Xmx1024m" -e GC_MAX_METASPACE_SIZE=1024 -e GC_METASPACE_SIZE=256

Note : After deploying your service over OpenShift/Kernates validate the deployment configuration file(deployment.yml) for these parameters. In case not not reflecting then delete your pods completly and reploy the application.

In case, you want make changes on other parameters also for improving the puformance of your applictaion then you can follow these documents to list of parameters for OpenShift.

Let me know your thought on this post. if this solution was helpful for you make comment on the post.

Happy Learning !!!

Spring Boot: Custom Actuator EndPoints Creation


In the previous post , Spring Boot Actuator : : Monitor Health of Application you have learn about the Spring Boot actuator enabling and access health monitoring parameters through Spring Boot Actuator provided endpoints (default).

In this post, You will learn about to create custom Spring Boot Actuator end points. Sometimes these custom actuator endpoints required to get some specific information or customization of information instead of providing all detailed application health related information.

You have to follow these steps in Spring Boot application to create custom actuator endpoints.

Step 1:

Create or import any Spring Boot REST application. For Example using for User related Rest service (CRUD).

Step 2:

Enable the actuator in Spring Boot application by adding actuator starter in application pom.xml

<dependency>
	  <groupId>org.springframework.boot</groupId>
	  <artifactId>spring-boot-starter-actuator</artifactId>  
</dependency>

Step 3:

By default actuator allows external access for endpoints /actuator /health and /info, to access others custom actuator endpoints. you have add this property in your application.properties file.

management.endpoints.web.exposure.include=* 

Now, start your application and see the actuator is working fine or not by trying below url. If your server running on port 8090.

http://localhost:8090/actuator/health

{"status":"UP"}

UP status shows your application is running fine.

See More : Spring Boot Actuator : : Monitor Health of Application

Step 4:

Now to create custom actuator endpoints , you can create a class MyUserEndPoints in package com.facingIssuesOnIT.actuator as below:

To create a new endpoint you have to create a class and annotate it with @Component and @Endpoint annotation. The @Endpoint annotation has a parameter id (Ex: users) which determines the URL path of endpoint. This class contains the methods which returns the response of the endpoint. 

package com.FacingIssuesOnIT.actuators;

impert java.util.List;
impert java.util.Optional;

impert org.springframework.beans.factory.annotation.Autowired;
impert org.springframework.boot.actuate.endpoint.annotation.DeleteOperation;
impert org.springframework.boot.actuate.endpoint.annotation.Endpoint;
impert org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
impert org.springframework.boot.actuate.endpoint.annotation.Selector;
impert org.springframework.boot.actuate.endpoint.annotation.WriteOperation;
impert org.springframework.core.env.Environment;
impert org.springframework.stereotype.Component;

impert com.FacingIssuesOnIT.model.User;
impert com.FacingIssuesOnIT.repository.UserRepository;

at2Component
at2Endpoint(id = "users")
public class MyUserEndpoints {
	
		at2Autowired
		private UserRepository userRepository;
		
		at2Autowired
		private Environment environment;
		
		at2ReadOperation
		public List<User> getAllUsers(){
			List<User> users =  userRepository.findAll();			
			return users;
		}
		
		at2WriteOperation
	    public String updateUser(Integer userId, String emailId) throws Exception {
		Optional<User> optional = userRepository.findById(userId);
			User user = optional.orElseThrow(() -> new Exception("Service.USER_NOT_FOUND"));
			user.setEmail(emailId);			
		return environment.getProperty("API.UPDATE_SUCCESS");
	}
		
		at2DeleteOperation
		public String deleteUser(at2Selector Integer userId) {
			userRepository.deleteById(userId);
			return environment.getProperty("API.DELETE_SUCCESS");
		}		
} 

In above class,

  • The value of id parameter of @Endpoint is usersSo this endpoint is accessible by URL /actuator/users.
  • a method defined with @ReadOperation which will be mapped to HTTP GET method and automatically be exposed over HTTP.
  • a method defined with @WriteOperation which will be mapped to HTTP POST method and automatically be exposed over HTTP. The methods that are annotated with @WriteOperation can take parameters in JSON format alone.
  • a method defined with @DeleteOperation which will be mapped to HTTP DELETE method and automatically be exposed over HTTP.
  • technology-specific endpoints defined with @WebEndpoint/@JmxEndpoint. For ex, @WebEndpoint is exposed over HTTP only.

Step 5:

Restart the application and try with different custom actuator end points as below:

GET Method : http://localhost:8090/actuator/users

Response: Existing users list

Spring Boot Custom Actuator Endpoints : Get Method

POST Method : http://localhost:8090/actuator/users

Request Body

Spring Boot Actuator Endpoints : Post Method

It will create new user sunny with Id 345

Delete Method: http://localhost:8090/actuator/users/3

Spring Boot Actuator Endpoints : Delete Method

Here you have seen the custom actuator endpoints urls and response through the postman.

Conclusion

In this post you have learn about the below points:

  • Spring Boot Actuator configuration and enabling
  • Spring Boot custom actuator endpoints creation steps.
  • Spring Boot custom actuator endpoints access through Postman.

Let me know your thought on this post.

Happy Learning !!!

Spring Boot Actuator : : Monitor Health of Application


Once Spring Boot application deployed into production environment, you always want to monitor the application. This is because you want to ensure that the application must be always up and running and in case of any issues you want to fix it quickly. Therefore, an application monitoring tool is required so that you can analyze the health of your application.

Spring Boot has an in-built mechanism for monitoring application called as Actuator. It is a sub-project of Spring Boot. It offers several production grades features to monitor the application. Once you enable actuator in your Spring Boot application, a set of endpoints are exposed using which you can monitor and manage your application.  You can also integrate these endpoints with other application monitoring tools such Prometheus, Graphite etc.

Now let us see how you can enable Actuator in your Spring Boot application.

Spring Boot Actuator Configuration

Actuators can be easily enabled in your application by adding following spring-boot-actuator dependency in pom.xml file:

<dependency>
	  <groupId>org.springframework.boot</groupId>
	  <artifactId>spring-boot-starter-actuator</artifactId>  
</dependency> 

See More : Spring Boot: Custom Actuator EndPoints Creation

Actuator Endpoints

Once Actuator is enabled in your application, using actuator endpoints you can monitor and manage your application. These endpoints are exposed over HTTP in Spring MVC application using the ‘id’ of endpoints as the URL path along with /actuator as prefix. The following table shows some important actuator endpoints:

Actuator EndpointsDescription
/beansProvides list of all Spring beans available in the application
/configpropsProvides a collated list of all @ConfigurationProperties
/envExposes all the properties from Spring’s Configurable Environment
/infoDisplays arbitrary application information
/metricsDisplays metric information for the current application
/mappingsDisplays a collated list of all request mapping paths
/shutdownAllows the application to shutdown
/traceDisplays trace information, by default latest 100 HTTP requests
/healthProvides applications health information
Spring Boot Actuator Endpoints

Note : By default spring boot actuator only only allow the access of /health and /info end points because other end points provide application sensitive information.

You can also access the other specific end points by making below changes in your application.properties / application.yml file.

Access actuator all endpoints

You can add below properties to access all the end points:

#Access all actuator endpoints
management.endpoints.web.exposure.include=* 

Restrict specific actuator endpoints

You can add below exclude property to restrict the specific urls:

#Access all actuator endpoints
management.endpoints.web.exposure.include=*
#Retrict env endpoints to access
management.endpoints.web.exposure.exclude=env 

If you want to restrict access for more than one endpoints the specify as comma separated:

#Access all actuator endpoints
management.endpoints.web.exposure.include=*
#Retrict env endpoints to access
management.endpoints.web.exposure.exclude=env,beans

We will discuss on all the spring boot actuator end points in further sections.

If your application is running application on port number 8090, you can use below end point to get list of all the actuator endpoints and it will give you following response:

http://localhost:8090/actuator

Endpoint /actuator

By default actuator endpoint return only endpoints for /info and /health only as below.

Response:

{
	"_links": {
		"self": {
			"href": "http://localhost:8090/actuator",
			"templated": false
		},
		"health": {
			"href": "http://localhost:8090/actuator/health",
			"templated": false
		},
		"health-path": {
			"href": "http://localhost:8090/actuator/health/{*path}",
			"templated": true
		}
	}
}

If your actuator is enabled for all the endpoints as below then you will get complete list of end points of actuator:

#Access all actuator endpoints
management.endpoints.web.exposure.include=* 

Response:

{
	"_links": {
		"self": {
			"href": "http://localhost:8090/actuator",
			"templated": false
		},
		"beans": {
			"href": "http://localhost:8090/actuator/beans",
			"templated": false
		},
		"caches": {
			"href": "http://localhost:8090/actuator/caches",
			"templated": false
		},
		"caches-cache": {
			"href": "http://localhost:8090/actuator/caches/{cache}",
			"templated": true
		},
		"health": {
			"href": "http://localhost:8090/actuator/health",
			"templated": false
		},
		"health-path": {
			"href": "http://localhost:8090/actuator/health/{*path}",
			"templated": true
		},
		"info": {
			"href": "http://localhost:8090/actuator/info",
			"templated": false
		},
		"conditions": {
			"href": "http://localhost:8090/actuator/conditions",
			"templated": false
		},
		"configprops": {
			"href": "http://localhost:8090/actuator/configprops",
			"templated": false
		},
		"configprops-prefix": {
			"href": "http://localhost:8090/actuator/configprops/{prefix}",
			"templated": true
		},
		"env-toMatch": {
			"href": "http://localhost:8090/actuator/env/{toMatch}",
			"templated": true
		},
		"env": {
			"href": "http://localhost:8090/actuator/env",
			"templated": false
		},
		"loggers": {
			"href": "http://localhost:8090/actuator/loggers",
			"templated": false
		},
		"loggers-name": {
			"href": "http://localhost:8090/actuator/loggers/{name}",
			"templated": true
		},
		"heapdump": {
			"href": "http://localhost:8090/actuator/heapdump",
			"templated": false
		},
		"threaddump": {
			"href": "http://localhost:8090/actuator/threaddump",
			"templated": false
		},
		"metrics-requiredMetricName": {
			"href": "http://localhost:8090/actuator/metrics/{requiredMetricName}",
			"templated": true
		},
		"metrics": {
			"href": "http://localhost:8090/actuator/metrics",
			"templated": false
		},
		"scheduledtasks": {
			"href": "http://localhost:8090/actuator/scheduledtasks",
			"templated": false
		},
		"mappings": {
			"href": "http://localhost:8090/actuator/mappings",
			"templated": false
		}
	}
}

Now in further section will use the above endpoints of actuator and show the response of each API’s call.

Endpoint /health

This actuator health endpoint gives you the information about health of application. You can access this endpoint using the URL http://localhost:8090/actuator/health. It will give you following response:

{"status":"UP"}

The status will be UP if application is running and healthy. If application has some issues such as database is down etc. then you will get following response:

{"status":"DOWN"}

It tells only whether the status of application is UP or DOWN.  If you want to get details information about health of application then add the following property in the application.properties file:

management.endpoint.health.show-details=always
{
	"status": "UP",
	"components": {
		"db": {
			"status": "UP",
			"details": {
				"database": "H2",
				"validationQuery": "isValid()"
			}
		},
		"diskSpace": {
			"status": "UP",
			"details": {
				"total": 300662386688,
				"free": 277733244928,
				"threshold": 10485760,
				"exists": true
			}
		},
		"ping": {
			"status": "UP"
		}
	}
}

If you noticed from above response, it’s connected with database H2 and application consuming data disc spaces.

Endpoint /metrics

This actuator metrics endpoint displays various metrics options that can be checked for your application. You can access this endpoint using the URL http://localhost:8090/actuator/metrics. It will give you following response :

{
	"names": [
		"hikaricp.connections",
		"hikaricp.connections.acquire",
		"hikaricp.connections.active",
		"hikaricp.connections.creation",
		"hikaricp.connections.idle",
		"hikaricp.connections.max",
		"hikaricp.connections.min",
		"hikaricp.connections.pending",
		"hikaricp.connections.timeout",
		"hikaricp.connections.usage",
		"http.server.requests",
		"jdbc.connections.active",
		"jdbc.connections.idle",
		"jdbc.connections.max",
		"jdbc.connections.min",
		"jvm.buffer.count",
		"jvm.buffer.memory.used",
		"jvm.buffer.total.capacity",
		"jvm.classes.loaded",
		"jvm.classes.unloaded",
		"jvm.gc.live.data.size",
		"jvm.gc.max.data.size",
		"jvm.gc.memory.allocated",
		"jvm.gc.memory.promoted",
		"jvm.gc.pause",
		"jvm.memory.committed",
		"jvm.memory.max",
		"jvm.memory.used",
		"jvm.threads.daemon",
		"jvm.threads.live",
		"jvm.threads.peak",
		"jvm.threads.states",
		"logback.events",
		"process.cpu.usage",
		"process.start.time",
		"process.uptime",
		"system.cpu.count",
		"system.cpu.usage",
		"tomcat.sessions.active.current",
		"tomcat.sessions.active.max",
		"tomcat.sessions.alive.max",
		"tomcat.sessions.created",
		"tomcat.sessions.expired",
		"tomcat.sessions.rejected"
	]
}

The above metrics endpoint response has the name of individual metric. To get more information about these metrics you need to append the metric name to the URL. For example if you want to know more about jvm.memory.used metric then the URL will be http://localhost:8090/actuator/metrics/jvm.memory.used. This URL will give the following response:

{
	"name": "jvm.memory.used",
	"description": "The amount of used memory",
	"baseUnit": "bytes",
	"measurements": [
		{
			"statistic": "VALUE",
			"value": 1.67400072E8
		}
	],
	"availableTags": [
		{
			"tag": "area",
			"values": [
				"heap",
				"nonheap"
			]
		},
		{
			"tag": "id",
			"values": [
				"G1 Old Gen",
				"CodeHeap 'non-profiled nmethods'",
				"G1 Survivor Space",
				"Compressed Class Space",
				"Metaspace",
				"G1 Eden Space",
				"CodeHeap 'non-nmethods'"
			]
		}
	]
}

According to above response, you can get you application JVM memory space consumption, Garbage collectors configure etc.

Same way you can explore more about the application configuration, http requests hits, beans creation information by using actuators other endpoints.

You can also create your own Actuator endpoints. In next post you will learn about the the custom actuator end points creation.

See More : Spring Boot: Custom Actuator EndPoints Creation

Conclusion

In this post you learn about these points for Spring Boot actuators:

  • Spring Boot Actuator configuration and enabling.
  • Spring Boot Actuator endpoints
  • Spring Boot actuator specific endpoints enabling for end users.
  • Spring Boot Actuator health and metrics information retrieval.

Let me know your thoughts on this post.

Happy Learning !!!

Spring Boot Main Class Configuration


A spring boot application starts from the main class (class with main() method) that contains main method with below signature. On Startup of spring boot application it create Spring ApplicationContext and beans also for application..

@SpringBootApplication
public class SpringBootMainClassApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootMainClassApplication.class, args);
    }
}

By default spring boot search the main class in the class path at compile time. if it’s find multiple main class or none then it will throw exception as below.

Spring Boot Application without Main class

While running the application through STS/Eclipse it will show popup as “Selection does not contain a main type”.

Spring Boot Application without Main Class

Spring Boot Application with multiple main class

If you run the application manually through STS/Eclipse then you have to select one of the Main class below before execution. If you are trying to maven package of install from CMD it will throw exception as below.

mvn package -Dmaven.test.skip=true

it will through exception as below in CMD.

Spring Boot Application with Multiple Main Class

Solutions

To start a Spring Boot application, it’s mandatory to specify one Main class in your class path. If there is one Main class as above then will not be any issue to start a Spring boot application.

Now if there are multiple main class in your Spring Boot application then below solutions will help to start your application.

Solution 1: Specify the Main class in pom.xml properties

You can specify your main class in property start-class as below.

<properties>
      <!-- The spring boot main class to start by executing "java -jar" -->
      <start-class>com.FacingIssuesOnIT.SpringBootMainClassApplication</start-class>
</properties>

Note : This property configuration will help only when you added the spring-boot-starter-parent as in your pom.xml otherwise follow the solutions 2 or 3 to configure the main class.

Solution 2 : Specify the Main class in spring-boot-maven-plugin of pom.xml

You can also specify the main class of Spring Boot in spring-boot-maven-plugin of pom.xml as below:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>             
            <configuration>    
                <mainClass>com.FacingIssuesOnIT.SpringBootMainClassApplication</mainClass>
            </configuration>
        </plugin>
    </plugins>
</build>

Solution 3: Specify the Main Class on run time through CLI

You can also specify the Spring Boot Main class on runtime through CLI as below:

java -cp spring-boot-app.jar -Dloader.main=com.FacingIssuesOnIT.SpringBootMainClassApplication org.springframework.boot.loader.PropertiesLauncher

By using any of these configuration, You can decide you Spring Boot application main class for start the application.

Conclusion

In this post you learn about the different way to configure Spring Boot Application main class to start the application if your application having multiple Main classes.

Let me know your thoughts on this post.

Happy Learning !!!

[Solved] Spring Boot IllegalStateException: Ambiguous mapping. Cannot map ‘XYZController’ method


In Spring Boot Rest/MVC application, we got this exception “java.lang.IllegalStateException: Ambiguous mapping. Cannot map ‘XYZController’ method” which will not allow to create bean for your controller and also throw “UnsatisfiedDependencyException: Error creating bean with name XYZ” as given in below stack trace.

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'documentationPluginsBootstrapper' defined in URL [jar:file:/C:/Users/saurabh.gupta14/.m2/repository/io/springfox/springfox-spring-web/2.4.0/springfox-spring-web-2.4.0.jar!/springfox/documentation/spring/web/plugins/DocumentationPluginsBootstrapper.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webMvcRequestHandlerProvider' defined in URL [jar:file:/C:/Users/saurabh.gupta14/.m2/repository/io/springfox/springfox-spring-web/2.4.0/springfox-spring-web-2.4.0.jar!/springfox/documentation/spring/web/plugins/WebMvcRequestHandlerProvider.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'helloController' method 
com.FacingIssuesOnIT.controller.HelloController#sayHello()
to {GET [/api/FacingIssuesOnIT]}: There is already 'helloController' bean method
com.FacingIssuesOnIT.controller.HelloController#sayHiHello() mapped.
	at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800) ~[spring-beans-5.3.9.jar:5.3.9]
	at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229) ~[spring-beans-5.3.9.jar:5.3.9]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1354) ~[spring-beans-5.3.9.jar:5.3.9]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webMvcRequestHandlerProvider' defined in URL [jar:file:/C:/Users/saurabh.gupta14/.m2/repository/io/springfox/springfox-spring-web/2.4.0/springfox-spring-web-2.4.0.jar!/springfox/documentation/spring/web/plugins/WebMvcRequestHandlerProvider.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'helloController' method 
com.FacingIssuesOnIT.controller.HelloController#sayHello()
to {GET [/api/FacingIssuesOnIT]}: There is already 'helloController' bean method
com.FacingIssuesOnIT.controller.HelloController#sayHiHello() mapped.
	at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800) ~[spring-beans-5.3.9.jar:5.3.9]
	at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229) ~[spring-beans-5.3.9.jar:5.3.9]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1354) ~[spring-beans-5.3.9.jar:5.3.9]
	... 24 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'helloController' method 
com.FacingIssuesOnIT.controller.HelloController#sayHello()
to {GET [/api/FacingIssuesOnIT]}: There is already 'helloController' bean method
com.FacingIssuesOnIT.controller.HelloController#sayHiHello() mapped.
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1786) ~[spring-beans-5.3.9.jar:5.3.9]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:602) ~[spring-beans-5.3.9.jar:5.3.9]
		... 41 common frames omitted
Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'helloController' method 
com.FacingIssuesOnIT.controller.HelloController#sayHello()
to {GET [/api/FacingIssuesOnIT]}: There is already 'helloController' bean method
com.FacingIssuesOnIT.controller.HelloController#sayHiHello() mapped.
	at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.validateMethodMapping(AbstractHandlerMethodMapping.java:665) ~[spring-webmvc-5.3.9.jar:5.3.9]
	at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.register(AbstractHandlerMethodMapping.java:631) ~[spring-webmvc-5.3.9.jar:5.3.9]
	at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.registerHandlerMethod(AbstractHandlerMethodMapping.java:328) ~[spring-webmvc-5.3.9.jar:5.3.9]
		... 55 common frames omitted

Reason of Exception

The exception “java.lang.IllegalStateException: Ambiguous mapping. Cannot map ‘xyzController’ method” is throw when there is end point of REST urls of two method are same with Verb in your application. So on time of deploy your spring boot application the dispatcher servlet will create mapping of urls with respect to method because two methods having the same name with http verb (GET/POST/PUT/DELETE) then dispatcher got confuse for particular url which method need to point and throw this exception “java.lang.IllegalStateException: Ambiguous mapping”.

Solution

As explained above the reason of this exception. Once this exception happen check for the recently added urls for REST services . This url can be same with in same controller of your application where the exception occurred or match with other controller if no request mapping on class level.

Let me know your thoughts on it.

Happy Learning !!!

Spring Boot Banner Customization Enable / Disable


In Spring Boot by default configure for Banner “Spring Boot” as below which will display on your console with version number.

Spring Boot Banner

Possible Values for Spring Boot Banner

Spring Boot support these three types of configuration for Banner:

  • OFF : Disable printing of Banner
  • CONSOLE : Display Banner to System.out
  • LOG : Display Banner on your Log also.

How to set these Spring Boot Banner Configuration?

There are two ways to configure Spring Boot Banner:

  • Banner setting by application.properties / applictaion.yml

You can add this property in application.properties/ application.yml file to change in configuration of Banner. If you set as off will not display in console and log.

application.properties

##possible values off, console, log
spring.main.banner-mode=console

application.yml

##possible values off, console, log
spring
  main
    banner-mode:console
  • Banner Setting in Spring Boot main() method

You can also change in Spring Boot class main() method to set Banner configuration as below in this case no setting required on application properties file.

Spring Boot Banner Setting
  • Customize Spring Boot Banner

By default Spring Boot show default banner “Spring Boot” with version number. If you want to customize this banner and replace it then create one banner.txt file and place it on your Spring boot application resource folder.

Example:

${Ansi.RED}                  $$$        $$$$$      $$$$         $$$$     $$$$$
${Ansi.GREEN}                  $$$       $$$$$$$     $$$$         $$$$    $$$$$$$
${Ansi.BLUE}                  $$$       $$$$$$$     $$$$$       $$$$$    $$$$$$$
${Ansi.RED}                  $$$       $$$$$$$      $$$$       $$$$     $$$$$$$
${Ansi.GREEN}                  $$$      $$$$ $$$$     $$$$$     $$$$$    $$$$ $$$$
${Ansi.BLUE}                  $$$      $$$$ $$$$      $$$$     $$$$     $$$$ $$$$
${Ansi.RED}                  $$$     $$$$$ $$$$$     $$$$     $$$$    $$$$$ $$$$$
${Ansi.GREEN}                  $$$     $$$$   $$$$     $$$$$   $$$$$    $$$$   $$$$
${Ansi.BLUE}                  $$$     $$$$   $$$$      $$$$   $$$$     $$$$   $$$$
${Ansi.RED}                  $$$    $$$$$   $$$$$     $$$$$ $$$$$    $$$$$   $$$$$
${Ansi.GREEN}                  $$$    $$$$$$$$$$$$$      $$$$ $$$$     $$$$$$$$$$$$$
${Ansi.BLUE}          $$$$   $$$$    $$$$$$$$$$$$$      $$$$ $$$$     $$$$$$$$$$$$$
${Ansi.RED}          $$$$   $$$$   $$$$$$$$$$$$$$$      $$$$$$$     $$$$$$$$$$$$$$$
${Ansi.GREEN}          $$$$$ $$$$$   $$$$       $$$$      $$$$$$$     $$$$       $$$$
${Ansi.BLUE}          $$$$$$$$$$$  $$$$$       $$$$$     $$$$$$$    $$$$$       $$$$$
${Ansi.RED}           $$$$$$$$$   $$$$         $$$$      $$$$$     $$$$         $$$$
${Ansi.GREEN}            $$$$$$$    $$$$         $$$$      $$$$$     $$$$         $$$$

${Ansi.RED} :: Spring Boot${spring-boot.formatted-version} :: ${Ansi.DEFAULT}

Once you will run your application will show updated banner as below.

Customize Spring Boot Banner

Let me know your thoughts on it.

Happy Learning !!!

[Solved] Spring Data JPA :QueryCreationException: Could not create query for public abstract method XYZ


In Spring boot Data JPA this exception QueryCreationException occurred when there is auto creation of Query or mismatch or column name in column/property in Entity class.

Spring Data JPA supports two ways of creating auto generation of query:

  • JQL in Spring data JPA or HQL when using the Hibernate.
  • Spring Data methods in Repository interface for Example : findByUserName() or findByUserNameOrDesignation() etc.

Reason for Exception

Spring Data JPA generate queries based on name of property in your Entity class , If entity based custom methods defined in repository interfaces also generate queries internally based on method name.

If there is any mismatch or incorrect name in custom methods of repository interface when comparing to entity class properties then on compile time it will not through any issue but when you run or deploy spring boot application will through QueryCreationException: Could not create query for method XYZ.

For Example : In User Entity class there is property userName while in custom methods in repository, you are trying to get detail from method findByName() so this property name not exist in User Entity class . Till compile time this method will not show any issue and compile successfully while on deploy time because using Spring Data JPA so will try to fetch data by Name and it will through exception as QueryCreationException: Could not create query for method XYZ.

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userrepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository' defined in com.FacingIssuesOnIT.repository.UserRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.Optional com.FacingIssuesOnIT.repository.UserRepository.findByUsername(java.lang.String)! Reason: Failed to create query for method public abstract java.util.Optional com.FacingIssuesOnIT.repository.UserRepository.findByUsername(java.lang.String)! No property username found for type User!; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional com.FacingIssuesOnIT.repository.UserRepository.findByUsername(java.lang.String)! No property username found for type User!
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:660) ~[spring-beans-5.3.9.jar:5.3.9]
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.3.9.jar:5.3.9]
	Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository' defined in com.FacingIssuesOnIT.repository.UserRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.Optional com.FacingIssuesOnIT.repository.UserRepository.findByUsername(java.lang.String)! Reason: Failed to create query for method public abstract java.util.Optional com.FacingIssuesOnIT.repository.UserRepository.findByUsername(java.lang.String)! No property username found for type User!; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional com.FacingIssuesOnIT.repository.UserRepository.findByUsername(java.lang.String)! No property username found for type User!
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1786) ~[spring-beans-5.3.9.jar:5.3.9]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:602) ~[spring-beans-5.3.9.jar:5.3.9]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) ~[spring-beans-5.3.9.jar:5.3.9]
		... 25 common frames omitted
Caused by: org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.Optional com.FacingIssuesOnIT.repository.UserRepository.findByUsername(java.lang.String)! Reason: Failed to create query for method public abstract java.util.Optional com.FacingIssuesOnIT.repository.UserRepository.findByUsername(java.lang.String)! No property username found for type User!; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional com.FacingIssuesOnIT.repository.UserRepository.findByUsername(java.lang.String)! No property username found for type User!
	at org.springframework.data.repository.query.QueryCreationException.create(QueryCreationException.java:101) ~[spring-data-commons-2.5.3.jar:2.5.3]
	at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:106) ~[spring-data-commons-2.5.3.jar:2.5.3]
	at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lambda$mapMethodsToQuery$1(QueryExecutorMethodInterceptor.java:94) ~[spring-data-commons-2.5.3.jar:2.5.3]
			... 35 common frames omitted
Caused by: java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional com.FacingIssuesOnIT.repository.UserRepository.findByUsername(java.lang.String)! No property username found for type User!
	at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:96) ~[spring-data-jpa-2.5.3.jar:2.5.3]
	at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:107) ~[spring-data-jpa-2.5.3.jar:2.5.3]
		... 57 common frames omitted
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property username found for type User!
	at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:90) ~[spring-data-commons-2.5.3.jar:2.5.3]
	at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:437) ~[spring-data-commons-2.5.3.jar:2.5.3]
	at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:413) ~[spring-data-commons-2.5.3.jar:2.5.3]
		... 61 common frames omitted

Solutions

To solve “QueryCreationException” in Spring boot data JPA follow these steps:

  • Go to stack trace of exception and see which query and methods of repository interface is throwing the exception.
  • Go to repository interface where this particular query and methods are defined and also check the Entity name with respect to repository.
  • Go to Entity class and check the properties name defined in method/queries are same or not.
  • If it’s not same or some typing mistake then only you will get this exception.

Note: Whenever you change any property name / column name in Entity class then always check for dependency in Native Queries/ JQL/HQL and Custom methods in repository otherwise your application will not deploy and fail on runtime.

Let me know your thoughts on it.

Happy Learning !!!

[Solved] Disable Directory Listing in Spring Boot Tomcat server for Web application


One common tomcat web server issue is directory listing that’s can cause to hackers attacked. By default tomcat directory listing is enabled or some developers set as enabled then it’s create a Information Disclosure Issue (leakage of sensitive information).

In your website/application if directory listing is enabled and index page is not configured as index.html or index.php then on typing the context path or URL till directory will display the list of directory and file as below and user/hacker can see all these files sensitive information.

Tomcat Directory Listing Enabled

As you can see from the above screenshot, the directory listing feature generates an output similar to command (‘dir’ or ‘ls’) on an operating system. Directory listing issues can not protect from a SSL certificate. However, These types of issue can be identified by running through vulnerabilities scanner on your application through Microfocus Web inspect.

Solutions

As a solution to disable directory listing depends on the tomcat server because in some of Spring boot application use tomcat as embedded server:

  • Disable directory listing on embedded tomcat in Spring boot
  • Disable directory listing on external tomcat server

Disable directory Listing on embedded tomcat in Spring boot

In Spring boot application where tomcat is defined as embedded tomcat then the application is deployed as jar and there is no web.xml file the you have to define this property setting on your application.properties / application.yml file to disable directory listing.

server.servlet.jsp.init-parameters.listings=false

Disable directory listing on external tomcat server

When you deploy your application using package as war on external tomcat server then you have to make these changes on your web.xml file to disable the directory listing on external tomcat server.

<servlet>
      <servlet-name>default</servlet-name>
      <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
      <init-param>
           <param-name>debug</param-name>
           <param-value>0</param-value>
      </init-param>
      <init-param>
           <param-name>listings</param-name>
           <param-value>false</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
 </servlet>

Here in above xml in web.xml file the init-param tag for listing is defined as false to disable the directory listing for application on web application.

f you are using the other web servers then you can check these configuration through below link.

https://www.netsparker.com/blog/web-security/disable-directory-listing-web-servers/

Let us know your thought on this post.

Happy Learning !!!

JAXB Overview


JAXB (Java Architecture for XML Binding) provides efficient and standard API and concepts to convert java object to XML and XML to Java Object. These conversion are also called as marshalling and unmarshaling as below:

Marshalling: Java Object to XML
Unmarshalling: XML to Java Object

Current Version of JAXB: 2.0

JAXB Marshalling and Unmarshalling

JAXB is a binding framework which provides support to mapping java fields with XML attributes and properties by annotations.

Why to use JAXB?

JAXB is required when need to deal with XML over Java platform because working on XML is not easy and you have to write code for each tags, attribute and condition etc.

By using JAXB framework make your life easy by using annotations, it’s provide annotations which customize your generated XML as per your business requirement and no need to write schema for XML.

Where JAXB Can We Use?

JAXB can we use in following cases:

  1. In webservices communication where one application in Java and another may be different technologies. As XML is platform and Language independent language so through JAXB convert POJO classes to XML through JAXB and call services provided by other application.
  2. Sometimes in distributed systems are connected through SFTP/MFTP so you can keep generated XML file there and another system will pick it.
  3. Most of the third party tools support XML for input/output data medium as XML, so we can use generated XML file for data transformation.

Let me know your thought on it.

Happy Learning !!!


References

https://javaee.github.io/jaxb-v2/

[Solved] JAXBException: Implementation of JAXB-API has not been found on module path or classpath.


JAXBException is the root exception class for all the JAXB exceptions. Generally this exception occurred when the implemented code is not fulfill the pre-requisite for JAXB related dependencies.

Constructors

JAXBException class having following constructors.

  • JAXBException(String msg): Construct exception with detail message..
  • JAXBException(String msg, String errorCode) : This construct exception with detail message with error code.
  • JAXBException(String msg, String errorCode, Throwable exception) : Construct detail message with error code and stacktrace of linked exception stacktrace.
  • JAXBException(String msg, Throwable exception) :Construct exception with detail message and stacktrace of linked exception.
  • JAXBException(Throwable exception) : Construct exception with stacktrace of linked exception.

Problem

This JAXBException occurred in your code because on runtime JAXB is not able to find JAXB-API related dependency.

javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
 - with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory]
	at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:278)
	at javax.xml.bind.ContextFinder.find(ContextFinder.java:421)
	at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721)
	at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662)
	at com.facingIssuesOnIT.domain.EmployeeJAXBTest.marshal(EmployeeJAXBTest.java:23)
	at com.facingIssuesOnIT.domain.EmployeeJAXBTest.main(EmployeeJAXBTest.java:15)
Caused by: java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory
	at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
	at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
	at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
	at javax.xml.bind.ServiceLoaderUtil.nullSafeLoadClass(ServiceLoaderUtil.java:122)
	at javax.xml.bind.ServiceLoaderUtil.safeLoadClass(ServiceLoaderUtil.java:155)
	at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:276)
	... 5 more

Solutions

To implement JAXB marshalling and unmarshalling in your application, you need to add following dependencies in you code. As above exception message explained “JAXB-API has not found in module or class path” this exception occurred when you forget to add JAXB-API dependency.

<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-core</artifactId>
    <version>2.3.0.1</version>
</dependency>

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.1</version>
</dependency>

<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.3.1</version>
</dependency>
 
<dependency>
    <groupId>org.javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.25.0-GA</version>
</dependency>

Conclusion

In this post , You learn about the JAXBException cases to occurred, different constructors and example to solve JAXB-API has not found in module or class path” JAXBException.

Let me know your thought to about this post.

Happy Learning !!!

[Solved]: JAXB empty Tag without xsi:nil=”true” for null values by using jaxb.properties


Generally when we do marshaling from JAVA object to XML through JAXB, the null values String or other objects not considered while marshalling and xml tag for these objects not generated.

If we need to get xml tags also for null values object then define these property in model class with attribute nillable=true.

 @XmlElement(name = "description", nillable = true)
 private String description;

After adding nillable=true property attribute this will generate output XML tag as below

<description xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>

Problem Statement

Here problem is we don’t want the XML description tag with schema url and xsi:nil=”true” as above. We want only the empty tag for XML as below

<description />

Solutions

Here the problem is when any value in model class property is found as null the JAXB does not call any xmlAdaptor and generate tag with schema link with xsi:nil=”true”.

To solve this problem we can use third party JAXB provider EclipseLink JAXB (MOXy) . It’s required to make below changes on your application and model class.

  • Add this EclipseLink MOXy dependency in you application
<dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>org.eclipse.persistence.moxy</artifactId>
        <version>2.6.8</version>
    </dependency>
  • Add XmlNullPolicy on all the fields of model where need to generate empty tag for null values.
 @XmlElement(name = "description", nillable = true)
 @XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE)
 private String description;
  • Now we need to set below property in our JVM while marshaling through java object to XML.
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

There are following ways to add above property based on you application need.

Solution 1: In case of simple java application, you can add this line of code before marshaling

System.setProperty("javax.xml.bind.JAXBContextFactory", "org.eclipse.persistence.jaxb.JAXBContextFactory");

Solution 2: Create jaxb.properties file in your each model package/resource folder and add below property

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

Note: Once you will run your code in your local machine it will generate empty tag but you will face problem when deploy application after making maven build because this property file will not add in your generated classes folder model packages. In this case you have to add below lines of code in pom.xml to copy jaxb.properties file in model package.

<plugin>
            <artifactId>maven-resources-plugin</artifactId>
            <version>2.6</version>
            <executions>
                <execution>
                    <id>copy-resources01</id>
                    <phase>validate</phase>
                    <goals>
                        <goal>copy-resources</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${basedir}/target/classes/model package location</outputDirectory>
                        <encoding>UTF-8</encoding>
                        <resources>
                            <resource>
                                <directory>${basedir}/src/main/resources</directory>
                                <includes>
                                    <include>jaxb.properties</include>
                                </includes>
                            </resource>
                        </resources>
                    </configuration>
                </execution>
            </executions>
        </plugin>

Solution 3: If your application is Spring boot then you can also pass the below arguments while deploying application.

-Djavax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

or

Add the property in application.properties/application.yml file

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

This solution will also help when you are having multiple packages for model classes and no need to include jaxb.properties in each package.

Conclusion

In this topic you learn about the steps to generate empty tags for XML incase null values for Java objects. you can also learn about the copy of jaxb.properties file in packages by maven. Incase of having multiple packages for model classes you can follow solutions to handle it.

Let me know about your thoughts on these solutions.

Happy Learning !!!

JDBC: ResultSet Interface


The object of ResultSet maintains a cursor pointing to a particular row of data. Initially, cursor points to before the first row.

By default, ResultSet object can be moved forward only and it is not updatable.
But we can make this object to move forward and backward direction by passing either TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int) method as well as we can make this object as updatable by:


Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);

Commonly used methods of ResultSet interface:

  1. public boolean next(): is used to move the cursor to the one row next from the current position.
  2. public boolean previous(): is used to move the cursor to the one row previous from the current position.
  3. public boolean first(): is used to move the cursor to the first row in result set object.
  4. public boolean last(): is used to move the cursor to the last row in result set object.
  5. public boolean absolute(int row): is used to move the cursor to the specified row number in the ResultSet object.
  6. public boolean relative(int row): is used to move the cursor to the relative row number in the ResultSet object, it may be positive or negative.
  7. public int getInt(int columnIndex): is used to return the data of specified column index of the current row as int.
  8. public int getInt(String columnName): is used to return the data of specified column name of the current row as int.
  9. public String getString(int columnIndex): is used to return the data of specified column index of the current row as String.
  10. public String getString(String columnName): is used to return the data of specified column name of the current row as String.

For example of ResultSet follow below links:

Learn More on JDBC

Follow below links to learn more on JDBC and solving JDBC related issues :

JDBC: Statement Interface


The Statement interface provides methods to execute queries with the database. The statement interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.

Commonly used methods of Statement interface:

  1. public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the object of ResultSet.
  2. public int executeUpdate(String sql): is used to execute specified query, it may be create, drop, insert, update, delete etc.
  3. public boolean execute(String sql): is used to execute queries that may return multiple results.
  4. public int[] executeBatch(): is used to execute batch of commands.

For example of statement interface follow below links:

See Also :

More on JDBC

Follow below links to learn more on JDBC and solving JDBC related issues :

Junit : Best Practices


In the previous topics we learn about the unit testing by Junit and implementation of Test Cases by using Junit 5. In this topic we will learn about the some Junit Best Practices and Why it’s required.

Why JUnit Best Practice Needed?

When writing Junit test case, we need to ensure the following points:

  • Test cases should be easily readable
  • Test cases should be extremely consistent and reliable
  • It should indicate the real issues in the production code
  • Tests should fail only when there is a bug in the system
  • It will be good if more test cases executed frequently
  • All the test cases should execute very fast

You can achieve all these Junit features when apply the “Junit Best Practices” when writing the Junit Test cases.

What is the Junit Best Practices for Test Case writing?

These are some high-level points that’s need to keep in mind while writing the test cases for an application or project.

  • Test cases should be readable.
  • The name of the test class and test methods should be descriptive.
  • Develop the JUnit test cases in a way that it should execute faster.
  • Always first plan unit tests for functionalities that have fewer dependencies.
  • Plan for proper tests for all functionalities.
  • Don’t use test case constructor to setup test cases.
  • Avoid skipping test cases with the usage of @Disabled without any reason, a reason could also be passed for @Disabled for any developer to know why a particular test case was is skipped.
  • Each unit test method should have only one assertion.
  • Maintain proper order of parameters in assertions.
  • Practice the resilient assertions.
  • Make each test independent of all others.
  • Don’t go for unit-testing of any settings or configuration.
  • Confirm that unit test code is parted from production code.
  • Do not print anything out in unit tests.
  • Avoid the usage of static members inside the test class, if you have used then re-initialize on each test case.
  • Do not give your own exception that occurs only to fail a test.
  • Don’t write testcases for configuration settings.
  • Plan to run the test cases completely in-memory, avoid doing a test for availing file system and DB, and for HTTP requests, Use mocking Junit framework like Mockito etc. for external or third-party dependency.
  • Implement Code Coverage tools like Cobertura, JACOCO etc. with your project so that verify that written Junit Test cases covering complete code. As per industry standard code coverage ratio should configure as 80%.
  • Integrate test cases with build script(ant or maven or gradle) so that all Junit test case will execute before your application ready for deploy.
  • Capture the results using XML formatter so that make test case report readable with color text.

Note: While writing test case assume these test cases will not execute in sequence so never try to use one test case result on another test case.

Good Tips for Junit Test Cases Writing

Here are some good tips for Junit Test Cases Writing that will guide when writing the test cases for any method in class.

  • Write descriptive name of your test case
TestCreateUser_NullUserId_ShouldThrowException
TestCreateUser_DuplicateUserId_ShouldThrowException
TestCreateUser_ValidUserId_Should_Pass
  • When writing test cases for method arguments then check for each parameters of method for null and these methods should return Invalid parameter exception if any parameter is null.
  • After null unit test implementation write test for functional unit.
  • Each test case should have only one assertion and it should cover one functional condition of code. Like if-else, switch, loops, exception etc.
  • For some methods where need to meet SLA of time or dependent of third-party API result write test cases for @Timeout.
// Timeout after 3 nanoseconds
@Timeout(value = 3, unit = TimeUnit.NANOSECONDS) 
@Test
void annotationDelayInValidTest() throws InterruptedException {
		obj.delay(2); // Delay for 2 seconds
}

JUnit 4

@Test(expected=ArithmeticException.class)
public void testCalculatorDivide()
{
assert(5, obj.devide(5,0))
}

JUnit 5

@Test
void testCalculatorDivide() {
Exception exception = assertThrows(ArithmeticException.class, () -> cobj.division(5, 0));
assertEquals("divide by zero", exception.getMessage());
	}
  • If need to test particular test case for multiple parameter values then write test case as @ParameterizedTest
@ParameterizedTest
	@NullAndEmptySource
	@ValueSource(blankStrings = { " ", "   ", "\t", "\n" })
	void checkText(String sampleText) {
	    assertTrue(sampleText == null || sampleText.trim().isEmpty());
	}

  • Use @Before and @After or @BeforeAll or @AfterAll test method for Initialization and close the dependencies of test method.
  • Use Mocking Junit framework for testing external service or DB related methods.
  • Don’t write test cases for configuration and constant related classes.
  • Ensure tests that are time dependent so that test data will not consider as expired data.
  • Use local when using date and time while implementing test cases.
  • Keeps your test cases on test packages in same project so that maintain easily and skip also in case required.

Summary

No doubt writing Junit increase the code quality of the code and by following the best practices reduce the maintenance and execution time of test. If you keep above points in mind that will help you to write good quality of test cases and make your application reliable and reduce the regression testing time with less defects in your code.

Let me know your views for Junit implementation and Junit Best Practices for writing Unit test cases for your code.

JUnit 5 : Environment Setup


Let us discuss on JUnit 5 environment setup in Java Application.

Pre-Requisite

JUnit 5 does not required any major setup. It’s required following library and IDE:

  • JDK : Min 1.8 or above
  • IDE : Eclipse/STS or Netbean or IntelliJ
  • Latest version of Junit 5 is readily available with latest version of IDE

More :

Junit 5 Setup in Java Application

You can add JUnit 5 library in your Java Application by follow below steps:

  • Right clock on your project -> Properties->Build Path-> Configure Build Path
  • Select Junit Library by following below steps in screen shot.
Junit 5 Environment Setup
  • After clicking in Next button (Step 5). You will get below screen where you can select Junit 5.
JUnit 5 Environment Setup
  • After click on Finish button (Step 7) this JUnit 5 library will add on your application.
  • Now you can click on “Apply” or “Apply and Close” button to complete this process.

Now your application is setup to write test JUnit 5 test cases.

In further topic you will learn about how to write JUnit Test Cases.

Junit 5 : How to write JUnit Test Cases?


In previous topic you learn about the JUnit setup in Java Application. In this topic you will learn about the Junit test cases writing of methods for particular java class.

Lets discuss about the test cases writing in Java application.

  • Right click on your java project -> Select New -> Junit Test Case as below.
How to write Junit Test Cases in Java application
  • After selecting the Junit Test Cases you will get below screen. Here the Jupiter option (Step 1) is for implementing the Junit Test cases with Junit 5. You can write test class name (Step 2) as CalcularTest and also select Fixture (Step 3) if initialization required for your test cases.
How to write Junit Test Case with Junit 5
  • Instead of writing the test cases, If you want to generate the Test cases for particular class then select browse (step 4) option and you will get below screen where you can search for class.
How to generate Junit test cases for particular class
  • After selecting class, click on OK button. You will get next screen with names of method where you can select methods for which you want to generate the test cases.
How to generate Junit test cases
  • After selecting methods click on Finish button, you will see a class CalculatorTest.java class added in you application with some test cases code as below.

CalculatorTest.java

JUnit Test Cases Generated
  • Now your some test cases generated with some dummy code where you can write your own logic inside of these test method by using assertion or assumption and run these test cases.

How to run Test Junit Cases?

Once you will done with the test case writing. You can follow these steps to run test cases:

  • Right click on your Java Application->select run as -> Junit
  • After executing the test cases you will see the test case result as below with red and green colors. Where green represent success and red as failure of test cases.

Junit Failed Cases

Junit some test cases failed

JUnit Success Case

Junit all success

Here I have done some changes in auto generated test cases as below and after execution showing as success as above. You can try with same or update it.

JUnit for success case

In the further topic you will learn more about the Junit 5 Annotations, Fixtures, Assertions and Assumptions in detail with examples.

Junit 5 : Architecture


Junit 5 Architecture mainly divide in three modules:

JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage

JUnit 5 Architecture

In Junit 5 Architecture each module having specific purpose as below:

JUnit Platform

Junit Platform is core of JUnit 5 which provides a bunch of libraries that provide Console Launcher to launch a platform from the command line and invokes JUnit Runner for running Test Engine in JUnit 4 based environment.

JUnit Jupiter

Jupiter provides the APIs for developer to interact assertions and assumptions instead of Runner itself.

JUnit Vintage

By default, JUnit 5 does not provide backward compatibility, instead, it uses another module called as Vintage which provides APIs to write test cases supported by older version JUnit 3 or Junit 4.

Extensions (Third Party)

JUnit 5 supports third-party APIs also on its platform with the help of the Extensions module.

In further topics you will learn about the JUnit 5 Annotations and Implementation of test cases by considering different scenarios.

JUnit 5: Introduction


In the previous topic you learned about the JUnit introduction and compare between different Junit framework like Junit vs TestNG. Here we will discuss about some important points to remember about Junit 5.

  • JUnit 5 is the latest version of JUnit which require a minimum JDK 8 version.
  • Junit 5 supports popular IDEs such as Eclipse/STS and IntelliJ for test case executions.
  • Junit 5 supports all new Java Language features including Lambdas.
  • Junit 5 provides various assertions and assumptions.
  • Junit 5 provides a whole new architecture that is comprised of modules, making it suitable to be used in small memory-based systems.
  • Junit 5 vintage module supports backward compatibility with previous version Junit 3 and Junit 4.

In the further topic you will learn about the JUnit 5 Architecture, JUnit 5 Annotations and Implementation of test cases by considering different scenarios.

JUnit Introduction


  • JUnit is an open-source framework for Java programming language, used to write and run automated unit test cases. It is widely accepted as a standard for unit testing in Java.
  • JUnit is a simple testing framework created by Kent Beck and Erich Gamma during a long airplane trip.
  • It is released under IBM’s common public license version 1.0 and hosted on SourceForge.
  • Till JUnit 3.8 there were no stable versions.
  • It is the Java version of the xUnit architecture for unit and regression testing frameworks
  • According to a survey of 2013, 10,000 Java projects hosted on GitHub were using JUnit as a testing framework.
  • In this tutorial, we will perform unit testing with JUnit 5 which is the latest stable JUnit version.

In the further topics we will discuss more about the Junit basics and implementation of test cases by using JUnit 5 after considering different scenarios and backward compatibility with previous version JUnit 3 and JUnit 4.

Unit Testing


Unit testing is process of Software development which validate that each unit/line of code is performing as expected or not. On broader prospect Unit Testing is defect prevention and detection strategy to reduce software development risks, cost, and time to deliver a quality software.

Developers write Unit Test cases which covers the functionality of specific section of code, function level, class level and branches level so that ensure the implemented code is working as expected. Unit testing not completely verify the functionality of software but it’ ensure that building block of software work independently as expected from others.

Why Unit Testing Framework?

In Unit Testing, we verify each section of code for success and failure scenarios where need to implement the conditions in code Test code by considering the different cases.

Let’s take the below examples of Calculator.java class on addition() method where need to verify output of result by considering different test cases for success and failure.

Calculator.java

public class Calculator {
		public int addition(int a, int b) {
			return a + b;
		}
	}

Test Cases Implementation

In this case for testing this method we need to create one test class i.e CaculatorTest.java and implement the condition for all scenarios of every method test as follows:

Success Case: Pass arguments as a=2, b=3 return result=5, Expected Result =5

Failed Case: Pass arguments as a=2, b=3 return result=Other, Expected Result=5

class CalculatorTest {
private static final Logger logger = Logger.getLogger(CalculatorTest.class.toString());
private Calculator calc = new Calculator();
		void additionTest() {
		int sum = calc.addition(2, 3);
		if (sum == 5) {
		logger.info("Addition method test has passed.");
		} else {
		logger.info("Addition method test has failed.");
			}
		}	
		public static void main(String[] args) {
			CalculatorTest cTest = new CalculatorTest();
		cTest.additionTest();
	}	
	}

Here if you noticed for testing a single small addition() method required to write these many lines of code for creating object of Calculator class, calling method and check for pass and failed scenarios. Apart from it you need monitor the console logs also for verify the expected result. Think of when there are multiple methods in class and software having lots of classes on that case writing Junit code is cumbersome process for developers.

From the above example, Now analyze tasks that need to be done manually with and without framework :

TaskWithout FrameworkWith Framework
PreparationManually Manually
Provide Test Inputs Manually Manually
Run the tests Manually Framework
Provide expected outputs Manually Manually
Verify results Manually Framework
Notify developer if test failed Manually Framework

Now it should be clear that how important to use framework because it saves significant amount of time of developers.

There are lots of framework for Unit Testing but when we talk about the Java unit testing mainly these two are most popular.

  1. Junit
  2. TestNG

TestNG is a testing framework for Java and is inspired by JUnit and NUnit which covers a wide range of testing like unit testing, functional testing, integration testing, and system testing.

In the further topics we will discuss more about the Junit basics and implementation of test cases by using Junit 5 after considering different scenarios.

Software Testing


What is Software Testing?

When developer create a new software and deploy in market for use of public. The success of software depends on popularity of software, but it becomes terrible when users complains bugs, issues in the software. In this case developer need to debug the issues and fixed again for release the software that’s time-consuming process.

To overcome this practice “Software testing” comes in picture. This activity makes sure that every functionality or component of software is working as expected and outcome of software is as expected. The main purpose of software testing is delivered as defect free software.

Why Software Testing?

“Prevention is better better than care”

This phrase is very well suite for software development, If developers do the software testing on the time of development then all the issues will identify and fixed on the time of development which will make the bug free software. Software testing saves a lot of time for developers and reduces the frustration level caused by detecting bugs after deployment.

Software Testing Types

Software testing mainly categories in two types:

Software Testing Types
  1. Manual Testing: In this testing strategy is done manually by a tester to discover the bugs in software and check the results. This is also required because 100% automation testing is not possible.
  2. Automated Testing: In this testing, scripts and codes are written by testers to automate the test cases execution. This testing strategy saves lots of time as well manpower and generate report by automation tool.

Software Testing Hierarchy

In software testing, whether you choose automation or manual testing it can’t complete on one go. It comprises through 4 testing levels as below:

Software Testing Hierarchy

Unit Testing

Unit testing covers all independent parts or components of code i.e. known as Units. Unit testing is the first level of testing which perform on time of the development phase by developers while developing the software.

Integration Testing

Once the unit testing is working fine of all units of code then testing will be preform after integrating them i.e. called the integration testing. In this testing we check the communication between each unit are working as expected or not.

System Testing

Once the integration testing completed for all modules, then testing start for complete software i.e. called as System testing.

Acceptance Testing

After completing the System testing the software is evaluate as per business requirements i.e. called as Acceptance Testing. Once acceptance testing is completed successfully the software deployed to market for general user’s access.

The above testing hierarchy is very high level, there are other sub phases also for software testing, you will get to know by following this link https://en.wikipedia.org/wiki/Software_testing

In the further topics we will discuss more on Unit Testing by using Junit 5 and implementation on time of development.

Junit: Jacoco Code Coverage Plugin Integration with Eclipse/STS


In previous post you learn about the Junit Code Coverage Report generation by using Maven POM.xml that’s help to generate report for auditing purpose and check the status of junit test case implementation but everytime for these report you have to visit directory target/site/jacoco/index.html or target/jacoco-report/index.html

To reduce this effort, we can add this Jacoco plugin our eclipse/STS IDE and directly check the status over IDE.

Integration of JACOCO Code Coverage Plugin in Eclipse/STS

You can follow these steps to integrate this JACOCO code coverage plug in you eclipse or STS IDE.

  • Go to IDE top header Help->Eclipse Market Place it will open the pop up for Eclipse Market Place.
  • Type text as “Code Coverage” in search text box and click “Go” button. You will get below screen
JACOCO Code Coverage Plugin for Eclipse/STS
  • You will get list of plugins select the plugin “EclEmma Code Coverage” click on Install button for this plugin.
  • You will get next screen where need to accept terms and conditions and click continue.
  • After installing this code coverage plugin, It will ask to restart your IDE.
  • After restart your IDE, go to the top Windows->Show View->Others then search for “Coverage” as below then select option click on Open button.
  • You will see one additional tab “Coverage” on your console view section as below.
Coverage tab on view
  • Also get “Coverage As” option as below when right click on your application. Now you can run you Junit.
JACOCO coverage as option
  • Once you run your application Junit by using “Coverage As” option you will see the results on “Coverage” tab as below.
JUnit Code coverage report by Eclipse/STS plugin

To learn more detail about this report and metrics header you can follow this link Junit: Code coverage by using JaCoCo.

Conclusion

In this topic you learn about the steps to add code coverage plugin in you eclipse/STS IDE.

If this port help you to add Code Coverage plugin in you eclipse/STS IDE the like this post and share your comments. In case you are facing issue related to code coverage implementation share with us will try to resolve it.

Junit: Code coverage by using JaCoCo


Why Code Coverage Require while writing JUnit?

Code coverage is a matric indicator that shows the line of code are executed while running the automated JUnit test cases. This helps developer to identify that any unit test is not missing for developed code or newly added functionality of code so that improve the code quality and reduce number of bugs on time of integration testing.

While audit of your application source code auditor also asked for Code Coverage report so that observe your written Junit test cases covering complete application or not.

For Java development there are couple of tools for Code Coverage like Cobertura and Jacoco etc. Here you will learn about the integration of JACOCO with maven project.

JCOCO Code Coverage Plugin Integration with Eclipse/STS

Note : Cobertura support till Java version 8 only while JACOCO support all the Java 5 and above.

Code Coverage Tools generate report in percentage ratio as below in screen shot. Each header section described in detail in this table.

Junit Code Coverage

You can further extend this package section to get more code coverage detail on class and method level. You will get to know more detail in further sections.

Here these color represent as :

  • Green: Code is tested or covered
  • Red: Code is not tested or covered
  • Yellow: Code is partially tested or covered
HeaderDescription
INSTRUCTION
BRANCHAll the if-else or switch statements are consider as branch and represent as diamond in a method that can be executed or missed.
No coverage (Red diamond): No branches in the line has been executed.
Partial coverage (Yellow diamond): Only a part of the branches in the line have been executed.
CYCLOMATIC COMPLEXITYhttps://en.wikipedia.org/wiki/Cyclomatic_complexity
LINEConsider as executed when at least one instruction that is assigned to this line has been executed.
No coverage (Red): No instruction in the line has been executed.
Partial coverage (Yellow): Only a part of the instruction in the line have been executed.
Full coverage (Green): All instructions in the line have been executed
METHODConsider as executed when one of the instruction has been executed.
CLASSConsider as executed when one of the method has been executed.
JUnit Code Coverage Criteria

Implementation of Code Coverage

In this further section you will learn about the implementation of Code Coverage for Junit. Here we are using dependency as below:

  • JUnit 5
  • Maven 4
  • Maven Surefire plugin 3.0.0-M5
  • Jacoco 0.8.2 (Code Coverage library)

POM.XML

You can make following changes in your maven java application pom.xml.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.FacingIssuesOnIT</groupId>
  <artifactId>maven-junit-code-coverage-Jacoco</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>Maven-junit-CodeCoverage-Jacoco</name>
  <description>Maven JUnit Code Coverage</description>
  <properties> 
     <maven.compiler.source>1.8</maven.compiler.source>
     <maven.compiler.target>1.8</maven.compiler.target>    
	<java.version>1.8</java.version>
	<!-- add property to enable or disable code coverage by default id false for Jacoco -->
	<jacoco.skip>false</jacoco.skip>
</properties>
<dependencies>
<!-- Junit 5 -->
	<dependency>
		<groupId>org.junit.jupiter</groupId>
		<artifactId>junit-jupiter-engine</artifactId>
		<version>5.5.2</version>
	</dependency>
</dependencies>
	<build>
		<plugins>
		<!-- Maven plugin for surefire with Dependency junit 5 -->
			<plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M5</version>
            <dependencies>
                <dependency>
                    <groupId>org.junit.jupiter</groupId>
                    <artifactId>junit-jupiter-engine</artifactId>
                    <version>5.5.2</version>
                </dependency>
            </dependencies>
        </plugin>
        <!-- Jacoco plug in for code coverage -->
			<plugin>
				<groupId>org.jacoco</groupId>
				<artifactId>jacoco-maven-plugin</artifactId>
				<version>0.8.2</version>
				<configuration>
					<!-- exclude classes for code coverage -->
					<excludes>
						<exclude>**/*fiot/*Application.class</exclude>
						<exclude>fiot/controller/*</exclude>
					</excludes>
				</configuration>
				<executions>
					<execution>
						<goals>
							<goal>prepare-agent</goal>
						</goals>
					</execution>
					<!-- attached to Maven test phase -->
					<execution>
						<id>jacoco-report</id>
						<phase>test</phase>
						<goals>
							<goal>report</goal>
						</goals>
						<!-- default target/site/jacoco/* you can define your directory for code coverage report -->
						<configuration>
							<outputDirectory>target/jacoco-report</outputDirectory>
							<skip>${jacoco.skip}</skip>
						</configuration>
					</execution>
					<!-- Define rule for successful build based on code code coverage criteria -->
					<execution>
						<id>jacoco-check</id>
						<goals>
							<goal>check</goal>
						</goals>
						<configuration>
							<rules>
								<rule>
								<!-- When code coverage is 90% and no class missed then consider for successful build -->
									<element>PACKAGE</element>
									<limits>
										<limit>
											<counter>LINE</counter>
											<value>COVEREDRATIO</value>
											<minimum>0.9</minimum>
										</limit>
										<limit>
											<counter>CLASS</counter>
											<value>MISSEDCOUNT</value>
											<maximum>0</maximum>
										</limit>
									</limits>
								</rule>
							</rules>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>

Here is more detail about the Jacoco code coverage implementation.

Maven Junit Code Coverage Implementation Detail

Now lets create some classes by some code implantation and check this code coverage implementation by implementing Junit.

Here i have created one Maven Java project with below directory/file structure.

Maven Junit Code Coverage Example

Implement some code as below:

Calculator.java

package com.FacingIssuesOnIT;

public class Calculator {

	   public double divide(int a, int b)
	   {
		   if(b==0)
		   {
			   throw new ArithmeticException();
		   }
		   else
		   {
		   return a/b;
		   }
	   }

	    public int multiply(int a, int b) {
	        return a * b;
	    }
	    
	    public int add(int a, int b) {
	        return a + b;
	    }
}

Address.java

package com.FacingIssuesOnIT;

public class Address {
  public String printAddress()
  {
	  return "Facing Issues On IT \n Learn from Others Experience";
  }
}

CalculatorTest.java

You can write your own Junit test cases or use in git hub by following below link. Maven JUnit Code Coverage Example

Junit Test Cases

Code Coverage report

After writing test cases you can execute same by mvn test and verify the report in folder {application path}/target/jacoco-report/index.html

It will generate report as mentioned in below screen. Here Green percentage showing code coverage for JUnit while red showing for missing Junit for code.

Maven Junit Code Coverage Report

To get in-depth detail on code coverage on class and method level you can extend by clicking package.

Maven Junit code coverage report on class level

On further extend by click on class you will het detail on method level.

Maven Junit Code Coverage report on method level

On further extend by click on particular method you will get detail about the line and branch level code coverage.

Maven JUnit Code Coverage on Line and branch level

After collecting all such information you can write junit test cases for all these missing lines/method/branch (red) of statements.

Code Coverage Rules for application build

In the above example, I have define rule for code coverage as 90% instruction execution and missing class as 0. Even If our implemented Junit executed successfully but code coverage criteria is not match with define rules then our maven install will fail and throw exception as below .

[ERROR] Failed to execute goal org.jacoco:jacoco-maven-plugin:0.8.2:check (jacoco-check) on project maven-junit-code-coverage-Jacoco: Coverage checks have not been met. See log for details. -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.

Once all the missing Junit will implement and criteria will match successful then build sucessfully.

Conclusion

In this blog you learn about the implementation of code coverage for Unit and defining rule to make build. Some times while audit of you application code quality auditor also asked about the JUnit code coverage report so that auditor can verify the written Junit covering the complete source code of your application.

References

https://www.eclemma.org/jacoco/trunk/doc/maven.html

Source Code

Download Maven Junit Code Coverage Source Code

If this example this Junit Code Coverage detail help you like post make comments. In case you are facing any issue while implementing share detail will try to help you.

[Solved]: Maven Error “Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-test) on project XYZ: There are test failures.”


While running through Run As-> Junit executing Junit test cases but when run through Maven test throwing below error.

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  2.916 s
[INFO] Finished at: 2021-05-08T04:50:23+05:30
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-test) on project maven-junit-code-coverage-Jacoco: There are test failures.
[ERROR] 
[ERROR] Please refer to D:\Workspace\maven-junit-code-coverage-Jacoco\target\surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

Problem

In maven java project, maven-surefire-plugin is required for any types of reports generation because mvn test command execute the test cases but there is not added the plug in for maven-surefire-plugin that’s why maven is not able to execute test cases.

Solution

To execute your test cases with Junit in maven Java project, you can add Junit dependency with maven-surefire-plugin.

JUnit 5 Dependency

<dependencies>
	<dependency>
		<groupId>org.junit.jupiter</groupId>
		<artifactId>junit-jupiter-engine</artifactId>
		<version>5.5.2</version>
	</dependency>
</dependencies>

Maven Surefire Report Plugin

<build>
		<plugins> 
			<plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M5</version>
            <dependencies>
                <dependency>
                    <groupId>org.junit.jupiter</groupId>
                    <artifactId>junit-jupiter-engine</artifactId>
                    <version>5.5.2</version>
                </dependency>
            </dependencies>
        </plugin>
</plugins>
</build>

I have tested this solution with Junit 5 and working perfectly fine for me. You can change this dependency in case using Junit 4.

I have solved this problem by using above solution. If you know any other way to solve it write in comments to help others.

[Solved]: Maven Error “Source option 5 is no longer supported. Use 6 or later”


While build my maven java project getting below exception.
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Sym360: Compilation failure: Compilation failure: 
[ERROR] Source option 5 is no longer supported. Use 6 or later.
[ERROR] Target option 1.5 is no longer supported. Use 1.6 or later.
[ERROR] -> [Help 1]

Problem

This issue is because the maven is not able to identify which version of java compiler need to use while build your code.

Solution

There are two solution to handle such problem.

  1. If you are using simple maven java application then you can add these lines in you pom.xml properties tag .
<properties> 
   <maven.compiler.source>1.8</maven.compiler.source>
   <maven.compiler.target>1.8</maven.compiler.target>
</properties>
  1. If you application is spring boot application and defining maven compiler then add these lines in your pom.xml build tag.
<build>
   <plugins>
   <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
    </plugin>
   </plugins>
   </build>

Based on your code written and compatibility of java version, you can update this java version like java 11 etc.

I have solved this problem by using these two solution. If you know any other way to solve it write in comments to help others.