Wednesday, 22 June 2022

Multiple Database Configuration in Spring Boot

 Databases: 

  • MySQL Database
  • Oracle

In this demo, we would only use two datasources: MySQL and Oracle. 

Before you start: Create a database in MySQL called "mydb".

How it works:

It would be similar to your normal application but with a few changes

  1. The application.properties file would now contain multiple setting each for a different datasource.
  2. You need configuration classes, one for each of the data sources. One of the configuration classes must be set as Primary using the @Primary annotation.
  3. The configuration classes would contain mandatory methods:
    • DataSource method
    • LocalContainerEntityManagerFactoryBean method
    • PlatformTransactionManager method
  4.  We need a model/Entity class and a repository interface.

Step1: Create a SpringBoot project using SpringInitializer and add required dependencies like web, devtools etc.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>11.2.0</version>
    <scope>system</scope>
    <systemPath>C:/oraclexe/app/oracle/product/11.2.0/server/jdbc/lib/ojdbc6.jar</systemPath>
</dependency>

Step 2: Create Entity class as Employee.java and Student.java under Entity package.
Make sure to include All args- constructors as well as no-args constructors as well as getters and setter methods. You can also include toString method as well.

Step 3: Create the Controller class to call the APIs from the mentioned endpoints.
You can create a separate controller class or a combined controlled class. Here I have created a separate Controller class as EmployeeController.java and StudentController.java.

Step 4: Create a Repository interface each for the different Entity class that we have created. We need to create StudentRepository.java and EmployeeRepository.java that will ultimately extends JPARepository.

Step 5: Create a service layer to act as a mediator between Controller and Repository layer to fetch data from the database. 

Step 6: In the application.properties files, we have to give different datasource properties as shown below:


You can see the setting for the two datasources. Take note that the datasources are differentiated based on the prefixes. Just be sure to provide valid name.

Step 7: Now the most important part. We have to create the Database configuration file to connect with the required database.
EmployeeConfiguration.java and StudentConfiguration.java.



i) DataSource method

Take note that in this listing the function is annotated with the @Primary annotation.

ii) LocalContainerEntityManagerFactory


iii) PlatformT
ransactionManager

Step 8: Similarly we have to do for StudentConfiguration.java file. Just don't forget to remove the @Primary annotation from there as we can't have two primary datasource.

The complete contents of both the file is available at the github location.

Step 9: Run the application and call the API based on the Employee or Student data and you will see the data insertion/retrieval will happen from both the databases.


Friday, 25 February 2022

Spring Boot Swagger2

 Spring Boot Swagger2

Swagger2 is an open source project used to generate the REST API documents for RESTful web services. It provides a user interface to access our RESTful web services via the web browser.

To enable the Swagger2 in Spring Boot application, you need to add the following dependencies in our build configurations file.


<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger2</artifactId>
   <version>2.7.0</version>
</dependency>
<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger-ui</artifactId>
   <version>2.7.0</version>
</dependency>

To enable the Swagger 2 we use the annotation @EnableSwagger2 in our SpringBoot Applivation class.


A Docket bean is defined and using its select() method we get an instance of ApiSelectorBuilder. ApiSelectorBuilder we configure the endpoints exposed by Swagger.


After the Docket bean is defined, its select() method returns an instance of ApiSelectorBuilder, which provides a way to control the endpoints exposed by Swagger.


Using the RequestHandlerSelectors and PathSelectors we configure the predicates for selection of RequestHandlers.




These are the only changes required. Now go to http://localhost:8080/swagger-ui.html.
We will see the documentation for the exposed API as follows-




Source Code: Spring Boot Swagger

Reference:  https://www.javainuse.com/spring/boot_swagger_annotations
















Thursday, 24 February 2022

Spring Boot Security + JWT Welcome Example

In this tutorial, we will be developing a Spring Boot application that makes use of JWT authentication for securing an exposed REST API. In this example, we will be making use of hard-coded user values for user authentication.

Any user will be able to consume this API only if it has a valid JSON Web Token (JWT).






Develop a Spring Boot application that exposes a simple REST GET API with mapping /welcome.

Configure Spring Security for JWT. Expose REST POST API with mapping /token using which User will get a valid JSON Web Token. And then, allow the user access to the API /welcome only if it has a valid token.




The Maven project will look as follows:



Spring Security and JWT Configuration

We will be configuring Spring Security and JWT for performing 2 operations-

  • Generating JWT — Expose a POST API with mapping /token. On passing correct username and password it will generate a JSON Web Token(JWT)
  • Validating JWT — If user tries to access GET API with mapping /welcome. It will allow access only if request has a valid JSON Web Token(JWT).


The sequence flow for these operations will be as follows-

Generating JWT




Validating JWT




Add the Spring Security and JWT dependencies

The secret key is combined with the header and the payload to create a unique hash. We are only able to verify this hash if you have the secret key.

jwt.secret=java


JwtUtil

The JwtUtil is responsible for performing JWT operations like creation and validation.It makes use of the io.jsonwebtoken.Jwts for achieving this.

JWTUserDetailsService

JWTUserDetailsService implements the Spring Security UserDetailsService interface. It overrides the loadUserByUsername for fetching user details from the database using the username. The Spring Security Authentication Manager calls this method for getting the user details from the database when authenticating the user details provided by the user. Here we are getting the user details from a hardcoded User List. Also the password for a user is stored in encrypted format using BCrypt. 


JwtAuthenticationController

Expose a POST API /authenticate using the JwtAuthenticationController. The POST API gets username and password in the body- Using Spring Authentication Manager we authenticate the username and password.If the credentials are valid, a JWT token is created using the JWTTokenUtil and provided to the client.

JwtRequest

This class is required for storing the username and password we recieve from the client.

JwtResponse

This is class is required for creating a response containing the JWT to be returned to the user.

JwtRequestFilter

The JwtRequestFilter extends the Spring Web Filter OncePerRequestFilter class. For any incoming request this Filter class gets executed. It checks if the request has a valid JWT token. If it has a valid JWT Token then it sets the Authentication in the context, to specify that the current user is authenticated.

JwtAuthenticationEntryPoint

This class will extend Spring’s AuthenticationEntryPoint class and override its method commence. It rejects every unauthenticated request and send error code 401

WebSecurityConfig

This class extends the WebSecurityConfigurerAdapter is a convenience class that allows customization to both WebSecurity and HttpSecurity.


Start the Spring Boot Application

  • Generate a JSON Web Token -
  • Create a POST request with url localhost:9191/token. Body should have valid username and password. In our case username is "amir" and password is "amir123".






  • Validate the JSON Web Token
  • - Try accessing the url localhost:9191/welcome using the above generated token in the header as follows

Source Code: Spring-boot-Jwt

Reference: https://medium.com/swlh/spring-boot-security-jwt-hello-world-example-b479e457664c















































Wednesday, 16 February 2022

How The Strings Are Stored In The Memory?

 

In Java, strings are special. Java gives some special attention to string types that no other types enjoy such attention. For example, to create the string objects you need not to use ‘new‘ keyword. Where as to create other type of objects you have to use ‘new’ keyword. Like this, strings enjoy some special attention by the java. This attention is worth the while, because the strings are used almost everywhere while developing any kind of applications.

While storing the string objects in the memory also, they are specially treated by the Java. After reading this article, you will come to know how they are specially treated in the memory.

We all know that JVM divides the allocated memory to a Java program into two parts. one is Stack and another one is heap. Stack is used for execution purpose and heap is used for storage purpose. In that heap memory, JVM allocates some memory specially meant for string literals. This part of the heap memory is called String Constant Pool.

Whenever you create a string object using string literal, that object is stored in the string constant pool and whenever you create a string object using new keyword, such object is stored in the heap memory.

For example, when you create string objects like below, they will be stored in the String Constant Pool.

String s1 = "abc";
 
String s2 = "xyz";
 
String s3 = "123";
 
String s4 = "A";


And when you create string objects using new keyword like below, they will be stored in the heap memory.

String s5 = new String("abc");
 
char[] c = {'J', 'A', 'V', 'A'};
 
String s6 = new String(c);
 
String s7 = new String(new StringBuffer());

This is how String Constant Pool looks like in the memory.




One more interesting thing about String Constant Pool is that, pool space is allocated to an object depending upon it’s content. There will be no two objects in the pool having the same content.

This is what happens when you create string objects using string literal,

“When you create a string object using string literal, JVM first checks the content of to be created object. If there exist an object in the pool with the same content, then it returns the reference of that object. It doesn’t create new object. If the content is different from the existing objects then only it creates new object.”

But, when you create string objects using new keyword, a new object is created whether the content is same or not.

This can be proved by using “==” operator. As “==” operator returns true if two objects have same physical address in the memory otherwise it will return false. In the below example, s1 and s2 are created using string literal “abc”. So, s1 == s2 returns true. Where as s3 and s4 are created using new operator having the same content. But, s3 == s4 returns false.

public class StringExamples
{
    public static void main(String[] args)
    {
        //Creating string objects using literals
 
        String s1 = "abc";
 
        String s2 = "abc";
 
        System.out.println(s1 == s2);        //Output : true
 
        //Creating string objects using new operator
 
        String s3 = new String("abc");
 
        String s4 = new String("abc");
 
        System.out.println(s3 == s4);        //Output : false
    }
}


In simple words, there can not be two string objects with same content in the string constant pool. But, there can be two string objects with the same content in the heap memory.