Sunday, September 6, 2020

Spring Retry

Spring Retry provides the ability to automatically re-invoke a failed operation. This is helpful when errors may be transient in nature (like a momentary network glitch). Spring Retry provides a declarative control of the process and policy-based behavior that is easy to extend and customize.

To make processing more robust and less prone to failure, it sometimes helps to automatically retry a failed operation in case it might succeed on a subsequent attempt. Errors that are susceptible to intermittent failure are often transient in nature.

Retry should be tried only if you think that it may meet your requirements.

  • You should not use it for each use case. This is something you don't build right from the beginning but based on what you learn during development or testing. For example, you might find while testing that when you hit a resource, it works one time, but the next time, it gives a timeout error, then works fine when hit again.
  •  After checking with the downstream system, you're not able to find out any root cause or solution. You might want to build a Retry feature to handle your application's side, but the first attempt should be to fix the downstream side. 
  • Retry may cause resource clogging and make things even worse, preventing the application from recovering; therefore, the number of retries has to be limited. 
  • Retry should not be done for each exception. It should be coded only for a particular type of exception. For example, instead of putting code around Exception.class, do it for SQLException.class.
  • Retry can cause multiple threads trying to access the same shared resource and locking can be a big issue. An exponential backoff algorithm has to be applied to continually increase the delay between retries until you reach the maximum limit.
  • While applying Retry, idempotency has to be handled. Triggering the same request again should not trigger a duplicate transaction in the system.

Enable Retry:

Put the @EnableRetry annotation in the SpringBoot main class.

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

Thursday, September 3, 2020

CodeSmells-SonarQube

CodeSmells are structures in code that violate design principles and negatively impact quality.

 Here are some of the bad smells in Java code. 

Constant Interface:Constant interfaces have only static final data members declared in them without any methods. Suggested refactoring for this smell depends on kind of constants present in the constant interface: the constants can get added as members in the class or can be rewritten as enums.

 The interface java.io.ObjectStreamConstant is an example for this smell. 

Global Variable Class:The class has one public static (non-final) field. Since its freely available for modification by anyone, it becomes an equivalent to a C-like global variable, with only difference that the variable name is prefixed by the class name, thus avoiding name-clashes. Here is an example:

class Balls {

public static long balls = 0;

Global Function Class:It is a public class that has only one static public method and no other fields or methods; it can have an optional private constructor to disallow instantiation. It is equivalent to a C-like global function, except that the function needs to be prefixed by the class name to access the function. 

Publicly Exposed Fields:It is a public class with public non-final, non-static data members and no methods (with an optional constructor). It is difficult to maintain public, C-like classes, as Effective Java notes: "Several classes in the Java platform libraries violate the advice that public classes should not expose fields directly. .

Forgotten Interface:A class implements all the methods with the same signatures as the methods listed in an interface. It is a likely mistake that the class intended to implement an interface, but forgot to list the interface as its base type. A consequence of this smell is that the objects of the class cannot be treated as subtype of the interface and hence the benefit of subtyping and runtime polymorphism is not exploited. 

Clone Class: A Clone class is an exact replica of another class (unrelated by inheritance). Essentially, only the name of the class is different, but all its members, their signature, accessibility, etc. are the same..

Monday, August 31, 2020

Introduction to Junit5

 JUnit5 is the next generation of JUnit. The goal is to create an up-to-date foundation for developer-side testing on the JVM. This includes focusing on Java 8 and above, as well as enabling many different styles of testing.

JUnit 5 is split into three sub-projects: Jupiter, Vintage, and Platform.

They communicate via published APIs, which allows tools and libraries to inject customized behavior. Then, each sub-project is split into several artifacts to separate concerns and guarantee maintainability.

JUnit Vintage:

Implements an engine that allows to run tests written in JUnit 3 and 4 with JUnit 5.

JUnit Jupiter is the combination of the new programming model and extension model for writing tests and extensions in JUnit 5. 



Required Dependencies:

The junit-jupiter-api (version 5.4.2):This dependency provides the public API for writing tests and extensions.

The junit-jupiter-engine (version 5.4.2):This dependency contains the implementation of the JUnit Jupiter test engine that runs our unit tests.

Configuring the Maven Surefire Plugin:

build>

    <plugins>

        <plugin>

            <groupId>org.apache.maven.plugins</groupId>

            <artifactId>maven-surefire-plugin</artifactId>

            <version>2.22.1</version>

        </plugin>

    </plugins>

</build>            

Note: First, if we want to use the native JUnit 5 support of the Maven Surefire Plugin, we must ensure that at least one test engine implementation is found from the classpath. 

That’s why we added the junit-jupiter-engine dependency to the test scope.


Mockito

 Mockito is a mocking framework. It is a Java-based library used to create simple and basic test APIs for performing unit testing of Java applications. It can also be used with other frameworks such as JUnit and TestNG.

The framework allows the creation of test double objects (mock objects) in automated unit tests for the purpose of test-driven development (TDD) or behavior-driven development (BDD).

Mockito allows developers to verify the behavior of the system under test (SUT) without establishing expectations beforehand.One of the criticisms of mock objects is that there is a tight coupling of the test code to the system under test.

Benefits of Mockito:

  • No Handwriting − No need to write mock objects on your own.
  • Refactoring Safe − Renaming interface method names or reordering parameters will not break the test code as Mocks are created at runtime.
  • Return value support − Supports return values.
  • Exception support − Supports exceptions.
  • Order check support − Supports check on order of method calls.
  • Annotation support − Supports creating mocks using annotation.

Following are the mock() methods with different parameters:

mock() method with Class: It is used to create mock objects of a concrete class or an interface. It takes a class or an interface name as a parameter.
Syntax: <T> mock(Class<T> classToMock)

mock() method with Answer: It is used to create mock objects of a class or interface with a specific procedure. It is an advanced mock method, which can be used when working with legacy systems. It takes Answer as a parameter along with the class or interface name. The Answer is an enumeration of pre-configured mock answers.
Syntax: <T> mock(Class<T> classToMock, Answer defaultAnswer)

mock() method with MockSettings: It is used to create mock objects with some non-standard settings. It takes MockSettings as an additional setting parameter along with the class or interface name. MockSettings allows the creation of mock objects with additional settings.
Syntax: <T> mock(Class<T> classToMock, MockSettings mockSettings)

mock() method with ReturnValues: It allows the creation of mock objects of a given class or interface. Now, it is deprecated, as ReturnValues are replaced with Answer.
Syntax: <T> mock(Class<T> classToMock, ReturnValues returnValues)

mock() method with String: It is used to create mock objects by specifying the mock names. In debugging, naming mock objects can be helpful whereas, it is a bad choice using with large and complex code.
Syntax: <T> mock(Class<T> classToMock, String name)


Tuesday, August 25, 2020

Stored Procedures in Sql

Stored Procedures are created to perform one or more DML operations on Database.

 It is nothing but the group of SQL statements that accepts some input in the form of parameters and performs some task and may or may not returns a value.

Syntax :

CREATE or REPLACE PROCEDURE name(parameters)

IS

variables;

BEGIN

//statements;

END;

The most important part is parameters. Parameters are used to pass values to the Procedure. 

There are 3 different types of parameters, they are as follows:

IN:

This is the Default Parameter for the procedure. It always recieves the values from calling program.

OUT:

This parameter always sends the values to the calling program.

IN OUT:

This parameter performs both the operations. It Receives value from as well as sends the values to the calling program.

CREATE or REPLACE PROCEDURE INC_SAL(eno IN NUMBER, up_sal OUT NUMBER)

IS

BEGIN

UPDATE emp_table SET salary = salary+1000 WHERE emp_no = eno;

COMMIT;

SELECT sal INTO up_sal FROM emp_table WHERE emp_no = eno;

END; 

Steps to execute the procedure:

>Declare a Variable to Store the value comming out from Procedure :

VARIABLE v NUMBER;

>Execution of the Procedure:

EXECUTE INC_SAL(1002, :v);

>To check the updated salary use SELECT statement:

 SELECT * FROM emp_table WHERE emp_no = 1002;

or Use print statement :

PRINT :v

Example For Stored Procedures with Multiple Parameters:

CREATE PROCEDURE SelectAllCustomers @City nvarchar(30), @PostalCode nvarchar(10)

AS

SELECT * FROM Customers WHERE City = @City AND PostalCode = @PostalCode

GO;

Execution of Stored Procedures in SQL 

EXEC SelectAllCustomers City = "London", PostalCode = "WA1 1DP";


Example For Stored Procedure with One Parameter:

Example of SQL Stored Procedure with one parameter- 

CREATE PROCEDURE SelectAllCustomers @City nvarchar(30)

AS

SELECT * FROM Customers WHERE City = @City

GO;

Execution of Stored Procedures in SQL –

EXEC SelectAllCustomers City = "London";


ES12 new Features