Category Archives: Java

Export Data in CSV/Excel Using Angular-Spring

Client Side Changes:

Step 1: HTML file implementation

html_impl

Step 2: Angular controller/service.js implementation in the respective download function

downloadPOCReport:

angular_impl

Server Side Changes:

Step 3: Controller/Resource.java implementation

controller_impl

Step 4: Service implementation

service_impl

Advertisements

JUnit 5 Tutorial – New Features with Examples

What is JUnit?

It is an opensource testing framework which performs unit testing on Java based application. The current version is JUnit 5.

What’s New in JUnit 5?

Unlike its previous version, JUnit 5 is composed of several different modules from three different sub directories. (JUnit 5 requires Java 8 at run-time)

JUnit 5JUnit Platform + JUnit Jupiter + JUnit Vintage

1. JUnit Platform:

a) It serves as a foundation for launching testing frameworks on JVM.

b) It defines TestEngine API for developing testing framework that runs on the platform.

c) It provides console launcher to launch the platform from command line.

d) It provides build plugin for maven and Gradle as well as a JUnit4 based runner for running any TestEngine on platform.

2. JUnit Jupiter:

a) It is the combination of new programming model and extension model for writing tests and extensions.

b) It provides a TestEngine for running Jupiter based tests on platform.

3. JUnit Vintage:

a) It provides a TestEngine for running junit 3 and junit 4 based tests on platform.

Installation Guide of JUnit 5:

To install JUnit 5 in the application, please add the following maven dependencies in the respective pom.xml.


 <dependencies>
<!-- JUnit Platform -->
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-commons</artifactId>
<version>1.0.0-M2</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-console</artifactId>
<version>1.0.0-M2</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-engine</artifactId>
<version>1.0.0-M2</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-gradle-plugin</artifactId>
<version>1.0.0-M2</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<version>1.0.0-M2</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>1.0.0-M2</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>1.0.0-M2</version>
</dependency>

<!-- JUnit Jupiter -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.0.0-M2</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.0.0-M2</version>
</dependency>

<!-- JUnit Vintage -->
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>4.12.0-M2</version>
</dependency>
</dependencies>

Example: FirstJunit5Test.java


/**
*
*/
package com.abhi.junit5.learning;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;

import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;

/**
* @author Abhinav
*
*/
@RunWith(JUnitPlatform.class)
class FirstJunit5Test {

@Test
void testCaseFirst(){
assertEquals(2, 1+1);
}

@Test
@CustomTag
void failingTest() {
fail("Failing for failing's sake.");
}
}

JUnit 5 Annotations:

. @Test : It denotes that annoted method is a test method. It does not declare any attributes, since test extensions in junit jupiter operate based on their own annotations.

. @TestFactory : It denotes that annoted method is a test factory for dynamic tests*.

. @DisplayName : It declares the custom display names for the test class or test method. It could be the text with blank spaces, special characters, and even emojis.

. @BeforeEach : It denotes that the annoted method should be executed before each @Test annoted method. Such methods are inherited. Similar to junit 4 @Before.

. @AfterEach : It denotes that the annoted method should be executed after each @Test annoted method. Such methods are inherited. Similar to junit 4 @After.

. @BeforeAll : It denotes that the annoted method should be executed before all @Test annoted method. Such methods must be static and inherited. Similar to junit 4 @BeforeClass.

. @AfterAll : It denotes that the annoted method should be executed after all @Test annoted method. Such methods must be static and inherited. Similar to junit 4 @AfterClass.

. @Nested : It denotes that the annoted class is a nested, non static test class. @BeforeAll and @AfterAll annotations cannnot be used in @Nested test class.

. @Tag : It is used for filtering the test cases either at class or method level. Similar to junit 4 TestNG or categories.

. @Disabled : It is used to disable a test class or test method. Similar to junit 4 @ignore.

. @ExtendWith : It is used to register custom extensions*.

Meta Annotations and Composed Annotations:

In JUnit Jupiter you can define your own custom composed annotations that will automatically inherit the semantics of its meta-annotations.
Example: CustomTag.java

Sample Test Case example: BasicJUnit5Test.java


/**
 *
 */
package com.abhi.junit5.learning;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;

/**
 * @author Abhinav
 *
 */
@RunWith(JUnitPlatform.class)
@DisplayName("Sample test class for showcasing the annotations")
class BasicJUnit5Test {

@BeforeAll
 static void beforeALL(){
 System.out.println("It will execute once before executing all the Test case");
 }

 @BeforeEach
 void beforeEach(){
 System.out.println("It will execute each time before executing the Test case");
 }

 @Test
 void passedTestCase(){
 System.out.println("Success Test case");
 }

 @Test
 void failedTestCase(){
 System.out.println("Failed Test case");
 }

 @Test
 @Disabled("For demo purpose")
 void disabledTestCase(){
 System.out.println("Ignored Test case");
 }

 @AfterEach
 void afterEach(){
 System.out.println("It will execute each time after executing any Test case");
 }

 @AfterAll
 static void afterAll(){
 System.out.println("It will execute once After executing all Test case");
 }
}

JUnit 5 Assertions:

JUnit 5 have many assertions methods packaged under JUnit Jupiter. Their are few new assertion methods introduce in JUnit 5 to support the Java 8 lambda expression feature. Else most of them are similar what we had in JUnit 4.

Example: AssertionsJunit5.java


/**
 *
 */
package com.abhi.junit5.learning;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;

import static org.junit.jupiter.api.Assertions.*;
/**
 * @author Abhinav
 *
 */
@RunWith(JUnitPlatform.class)
@DisplayName("Assertions in JUnit5")
public class AssertionsJunit5 {

@Test
 @DisplayName("Test case to show standard assertion methods.")
 void basicAssertions(){
 assertEquals("Abhi", "Abhi");
 assertNotEquals(4, 2, ()-&amp;amp;gt;"Assertion not equals message.");
 assertTrue(3&amp;amp;gt;2, ()-&amp;amp;gt;"Assertion messages can be lazily evaluated to avoid constructing complex messages unnecessarily.");
 }

 @Test
 @DisplayName("Test case to show Grouped assertion methods.")
 void newAssertion(){
 assertAll("Group Assertions",
 ()-&amp;amp;gt;assertEquals("Abhi", "Abhi"),
 ()-&amp;amp;gt;assertNotEquals(4, 3, ()-&amp;amp;gt;"Assertion not equals message."),
 ()-&amp;amp;gt;assertTrue(3&amp;amp;gt;2, ()-&amp;amp;gt;"Assertion messages can be lazily evaluated to avoid constructing complex messages unnecessarily.")
 );
 }

 @Test
 @DisplayName("Test case to show exception handle through assertion methods.")
 void exceptionAssertion(){
 Throwable exception = expectThrows(NullPointerException.class, ()-&amp;amp;gt;{ throw new NullPointerException("Got exception message");
 });

 assertEquals("Got exception message", exception.getMessage());
 }
}

JUnit 5 Assumptions:

Junit 5 have many assumption methods packaged under JUnit Jupiter. Their are few new assumption methods introduce to support the Java 8 lambda expression feature. Else most of them are similar what we had in JUnit 4.

Example: AssumptionsBasic.java


/**
 *
 */
package com.abhi.junit5.learning;

import static org.junit.jupiter.api.Assumptions.*;
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;

/**
 * @author Abhinav
 *
 */
@RunWith(JUnitPlatform.class)
@DisplayName("Assumptions in JUnit5")
public class AssumptionsBasic {

@BeforeAll
 static void setUp(){
 System.setProperty("TestEnv", "JUnit5");
 System.setProperty("Environment", "Stage");
 }

 @Test
 void showAssumeTrue(){
 assumeTrue("Stage".equals(System.getProperty("Environment")), ()-&amp;amp;gt; "Not on development environment");
 }

 @Test
 void showAssumptionBasic(){
 assumingThat("JUnit5".equals(System.getProperty("TestEnv")),
 ()-&amp;amp;gt;{
 assertEquals(2, 2);
 System.out.println("Inside assumption");
 });

 }
}

You can checkout/clone the JUnit 5 example repository from the mentioned path – https://github.com/erabhinavrana/my-junit5-learning

 

Jave 8 New Features

JAVA 8 New Features With Examples

Introduction to Java 8:

JAVA 8 (jdk 1.8) provide support for functional programming, new JavaScript engine, new API’s for Date time manipulation, new streaming API, etc

Java 8 New Features:

There are a lot of features added to java 8, few of them are mentioned below:

1. Lambda expression : It provides functional processing capability to java.

2. Method references : Instead of calling the functions directly, reference them by their name. Using functions as parameter.

3. Default method : It introduces a default method implementation in an Interface.

4. Stream API : A new stream API is introduce to facilitate the pipeline processing.

5. Date Time API : Improved Date Time API.

6. Optional : It emphasis on best practices to handle null values.

7. Nashorn, JavaScript Engine : It is java based engine to execute JavaScript code.

NOTE: Apart from these new features, a lot of feature enhancements are done at both compiler and JVM level.

Lambda Expressions:

Lambda expression facilitates the functional programming, and simplifies the development a lot.

Syntax: parameter -> expression body

Following are the important characteristics of a lambda expression:

a) Optional type declaration: There is no need to declare the type of a parameter. The compiler will inference the same from the value of parameter.

Example:

//Operation without type declaration
 CalculatorOperation subtraction = (a, b) -> a - b;

b) Optional parenthesis around parameter: There is no need to declare parenthesis around single parameter, but in case of multiple parameter parenthesis is required.

Example:

//Operation without parenthesis
 Message subtractInfo = msg -> System.out.println(msg);

c) Optional Curly braces: There is no need to put curly braces around expression if expression contains single statement.

Example:

//Operation without curly braces
 CalculatorOperation multiplication = (double a, double b) -> a*b;

d) Optional return keyword: The compiler will automatically return the value if the body has single expression which will return the value. Curly braces are required to indicate that expression will returns a value.

Example:

//Operation with return statement along with curly braces
 CalculatorOperation multiplication = (double a, double b) -> {return a*b;};

Points to be considered:

  • Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only.
  • Lambda expressions gives a very simple yet powerful functional programming capability to Java.
  • Lambda expressions can also be used to refer final variables.

Below is the example of basic implementation of lambda expression. In this example we have two different interface, one is for calculator operation and other one is to display input message. Also there are two more classes; one utility class and other is main class.

The CalculatorOperation Interface with method operation.


/**
*
*/
package com.abhi.lambdaexpression;

/**
* @author Abhinav
*
*/
public interface CalculatorOperation {

/**
* @param valA
* @param valB
* @return
*/
double operation(double valA, double valB);

}

The Message Interface with method showMessage.


/**
*
*/
package com.abhi.lambdaexpression;

/**
* @author Abhinav
*
*/
public interface Message {

/**
* @param msg
* @return
*/
void showMessage(String msg);
}

The Calculator utility class with method operations.


/**
*
*/
package com.abhi.lambdaexpression;

/**
* @author Abhinav
*
*/
public class Calculator {

private Calculator(){

}

/**
* @param valA
* @param valB
* @param calcOperation
* @return
*/
public double operations(double valA, double valB, CalculatorOperation calcOperation) {

return calcOperation.operation(valA, valB);
}

/**
* @return
*/
public static Calculator getInstance(){
return new Calculator();
}

}

The executor class CalculatorMain with different declarations of lambda expressions.


/**
*
*/
package com.abhi.lambdaexpression;

/**
* @author Abhinav
*
*/
public class CalculatorMain {

final static String ADDITION = "1 + 1 = ";
final static String SUBTRACTION = "4 - 1 = ";
final static String MULTIPLY = "2 * 2 = ";
final static String DIVIDE = "10 / 2 = ";
/**
* @param args
*/
public static void main(String[] args) {

Calculator calc = Calculator.getInstance();

//Operation with type declaration
CalculatorOperation addition = (double a, double b) -> a + b;

//Operation without type declaration
CalculatorOperation subtraction = (a, b) -> a - b;

//Operation with return statement along with curly braces
CalculatorOperation multiplication = (double a, double b) -> {return a*b;};

//Operation with return statement along with curly braces
CalculatorOperation division = (double a, double b) -> a/b;

//Operation with parenthesis
Message addInfo = (msg)-> System.out.println(msg);

//Operation without parenthesis
Message subtractInfo = msg -> System.out.println(msg);

//Operation with parenthesis
Message info = (msg) -> System.out.println(msg);

addInfo.showMessage("Addition");
System.out.println(ADDITION+ calc.operations(1, 1, addition));
subtractInfo.showMessage("Subtract");
System.out.println(SUBTRACTION+ calc.operations(4, 1, subtraction));
info.showMessage("Multiplication");
System.out.println(MULTIPLY+ calc.operations(2, 2, multiplication));
info.showMessage("Division");
System.out.println(DIVIDE+ calc.operations(10, 2, division));

}

}

You can checkout/clone the lambda expression example repository from the mentioned path – https://github.com/erabhinavrana/my-java8-learning

Chain of Responsibility Design Pattern

Chain of Responsibility Design Pattern

Design Pattern:

A design pattern is a description or template that can be used in many different situations to solve a commonly occurring problem in software design.

Chain-of-responsibility Pattern:

The chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects.Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain.

Example:

Below is the example of this pattern using java. In this example we have different payment types, each having its own debit functionality. Every time a Payment utility receives a payment request, the request is passed to his successor, if it is of different payment type.

The Payment Abstract class with abstract method debitAmount.


/**
*
*/
package com.abhi.corpattern.chainservice;

/**
* @author Abhinav
*
*/
public abstract class Payment {

protected int paymentType;

protected Payment payment;

/**
* @param nextPayment
*/
public void setPaymentType(Payment nextPayment) {
this.payment = nextPayment;
}

/**
* @param paymentType
*/
public void executePayment(int paymentType) {

if (this.paymentType == paymentType) {
debitAmount();
}

if (payment != null) {
payment.executePayment(paymentType);
}
}

/**
*
*/
abstract protected void debitAmount();

}

Three implementation of the above mentioned abstract class:

1. CreditCardPayment


/**
*
*/
package com.abhi.corpattern.chainservice.impl;

import com.abhi.corpattern.chainservice.Payment;

/**
* @author Abhinav
*
*/
public class CreditCardPayment extends Payment {

/**
* @param type
*/
public CreditCardPayment(int type) {
this.paymentType = type;
}

/*
* (non-Javadoc)
*
* @see com.abhi.corpattern.chainservice.Payment#executePayment()
*/
@Override
protected void debitAmount() {
System.out.println("Payment has been done using Credit Card");
}

}

2. DebitCardPayment


/**
*
*/
package com.abhi.corpattern.chainservice.impl;

import com.abhi.corpattern.chainservice.Payment;

/**
* @author Abhinav
*
*/
public class DebitCardPayment extends Payment {

/**
* @param type
*/
public DebitCardPayment(int type) {
this.paymentType = type;
}

/*
* (non-Javadoc)
*
* @see com.abhi.corpattern.chainservice.Payment#executePayment()
*/
@Override
protected void debitAmount() {
System.out.println("Payment has been done using Debit Card");
}

}

3. NetBankingPayment


/**
*
*/
package com.abhi.corpattern.chainservice.impl;

import com.abhi.corpattern.chainservice.Payment;

/**
* @author Abhinav
*
*/
public class NetBankingPayment extends Payment {

/**
* @param type
*/
public NetBankingPayment(int type) {
this.paymentType = type;
}

/*
* (non-Javadoc)
*
* @see com.abhi.corpattern.chainservice.Payment#executePayment()
*/
@Override
protected void debitAmount() {
System.out.println("Payment has been done using Net Banking");
}

}

In the PaymentMain class, the successor are set as follows:

CreditCardPayment -> DebitCardPayment -> NetBankingPayment


/**
*
*/
package com.abhi.corpattern.main;

import com.abhi.corpattern.chainservice.Payment;
import com.abhi.corpattern.chainservice.impl.CreditCardPayment;
import com.abhi.corpattern.chainservice.impl.DebitCardPayment;
import com.abhi.corpattern.chainservice.impl.NetBankingPayment;
import com.abhi.corpattern.constant.PaymentConstant;

/**
* @author Abhinav
*
*/
public class PaymentMain {

/**
* @return
*/
public static Payment getChainOfPaymentType() {
Payment creditcardpayment = new CreditCardPayment(
PaymentConstant.CREDIT_CARD);
Payment debitcardpayment = new DebitCardPayment(
PaymentConstant.DEBIT_CARD);
Payment netbankingpayment = new NetBankingPayment(
PaymentConstant.NET_BANKING);

creditcardpayment.setPaymentType(debitcardpayment);
debitcardpayment.setPaymentType(netbankingpayment);

return creditcardpayment;
}

/**
* @param args
*/
public static void main(String[] args) {

Payment payment = getChainOfPaymentType();

payment.executePayment(PaymentConstant.DEBIT_CARD);
payment.executePayment(PaymentConstant.NET_BANKING);

}

}

In the PaymentConstant, three payment type constants defined


/**
*
*/
package com.abhi.corpattern.constant;

/**
* @author Abhinav
*
*/
public class PaymentConstant {

public static final int CREDIT_CARD = 1;
public static final int DEBIT_CARD = 2;
public static final int NET_BANKING = 3;

}

You can checkout/clone the chain of responsibility example repository from the mentioned path – https://github.com/erabhinavrana/my-chaindesign-pattern

Date Format Utility with ThreadLocal

DateFormat

DateFormat is an abstract class for date/time formatting subclasses which formats and parses dates or time in a language-independent manner. The date/time formatting subclass, such as SimpleDateFormat, allows for formatting (i.e., date -> text), parsing (text -> date), and normalization. DateFormat helps you to format and parse dates for any locale but they are not synchronized.

Synchronization

Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally by using ThreadLocal.

ThreadLocal

The ThreadLocal class in Java enables you to create variables that can only be read and written by the same thread. Thus, even if two threads are executing the same code, and the code has a reference to a ThreadLocal variable, then the two threads cannot see each other’s ThreadLocal variables.

Example of Date Format Utility:

I have created the date format utility project to achive the mentioned goals :

  • Convert the input date string to the given date format.

String ddMMMYYYYHHMM = "15Jun2016 10:00";

DateFormatUtil.formatDate(ddMMMYYYYHHMM, "ddMMMyyyyHHmm", "yyyy-MM-dd'T'HH:mm:ss");

  • Parse the input date string format.
 String ddMMMyyyy = "06Jul1985";
DateFormatUtil.parseInputDateString(ddMMMyyyy);

Note: I have implement the date format utility using ThreadLocal.


ThreadLocal<SimpleDateFormat> inputDateFormatter = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat(inputDateFormat);
}
};

You can download the complete code of date format utility from the mentioned path – https://github.com/erabhinavrana/my-dateformat-utility.git