Category: Spring boot complete tutorial with example

Home / Category: Spring boot complete tutorial with example

In this article, we learn about How to parse JSON in java using JsonParser . JsonParser is used to parse the JsonObject and JsonArray.

As a java developer, we always deal with data in JSON or XML format. And sometimes we have to parse this data to perform some business logic.

And sometimes we have to convert the string into a JSON object or JSON array. So for this, we also use this JSON parser in java.

So in this example, we see how to convert a string into JsonObject and how to parse the JSON data using JsonParser.

To use this JsonParser in java application we have to add the below dependency in our pom.xml file.

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

Now Just take a programming example. In this example, we make a Post request and send some JSON data. And parse this JSON data using the parser.

Let’s take an example that we are trying to parse the below JsonObject.

{
	"name": "vasu",
	"age": 26,
	"email": "vasu@gmail.com"
}

So to parse the above JsonObject I will make the below logic in my controller class.

package com.javadream.jsonparser.controller;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JsonParserController {

	private static final Logger logger = LoggerFactory.getLogger(JsonParserController.class);

	private JSONParser parser = new JSONParser();

	@PostMapping("/parseSimpleJson")
	public String parser(@RequestBody String payload) {
		try {
			logger.info("payload= " + payload);
			JSONObject jObj = (JSONObject) parser.parse(payload);
			String name = jObj.get("name").toString();
			String age = jObj.get("age").toString();
			String email = jObj.get("email").toString();
			
			logger.info("name= "+name + " ,age= "+age + " ,email= "+email);
			return "Your name is "+ name + " and you are " + age + " old. Your email id is" + email ;
 		} catch (Exception e) {
			logger.error(e.getMessage());
			return "Parse Error Try Again";
		}
	}
}

We are using below steps to parse this jsonObject.

  1. We are creating a JSONParser object.
  2. Then receive this JsonObject in String formate in our Post endPoint.
  3. Convert this String payload to JSON object using the parser.
  4. Now we get a JsonObject.
  5. Now we get the object value using a key.

Now Run this application and make a post request with the given data from the postman.

jsonparser

Now take a complex JsonObject example and try to parse that. Suppose I am getting below JsonObject.

{
	"name": "vasu",
	"age": 26,
	"email": "vasu@gmail.com",
	"educationDetail": {
		"college": "GEHU Dehradun",
		"course": "B.Tech",
		"Branch": "CSE"
	}
}

Now we have another JsonObject with the name educationDetail in our main JsoObject. Let’s see how to parse this data.

So to parse this I am creating another post endPoint. See the code to parse this complex object.

	@PostMapping("/parserComplexJson")
	public String parserComplexJson(@RequestBody String payload) {
		try {
			logger.info("payload= " + payload);
			JSONObject jObj = (JSONObject) parser.parse(payload);
			String name = jObj.get("name").toString();
			String age = jObj.get("age").toString();
			String email = jObj.get("email").toString();

			JSONObject educationObj = (JSONObject) jObj.get("educationDetail");
			String collegeName = educationObj.get("college").toString();
			String course = educationObj.get("course").toString();
			String branch = educationObj.get("Branch").toString();

			return "Hi " + name + " you are student of "+ collegeName +" college and your course is "+ course; 
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "Parse Error Try Again";
		}
	}

Now run this application and make a post request with given JsonObject.

jsonparser java

Now take an example of a hard JsonObject where we have a JsonArray inside our main JsonObject.

{
	"name": "vasu",
	"age": 26,
	"email": "vasu@gmail.com",
	"educationDetail": {
		"college": "GEHU Dehradun",
		"course": "B.Tech",
		"Branch": "CSE"
	},
	"matrixEducation": [{
		"10ClassBoard": "Pass 10 class from UP Board"
	}, {
		"12ClassBoard": "pass 12 class from UP Board"
	}]
}

Now try to parse the above JsonObject. For this, I am creating another post endPoint. Look at the code below.

	@PostMapping("/parserHardJson")
	public String parserHardJson(@RequestBody String payload) {
		try {
			logger.info("payload= " + payload);
			JSONObject jObj = (JSONObject) parser.parse(payload);
			String name = jObj.get("name").toString();
			String age = jObj.get("age").toString();
			String email = jObj.get("email").toString();

			JSONObject educationObj = (JSONObject) jObj.get("educationDetail");
			String collegeName = educationObj.get("college").toString();
			String course = educationObj.get("course").toString();
			String branch = educationObj.get("Branch").toString();

			JSONArray matrixDetail = (JSONArray) jObj.get("matrixEducation");
			
			JSONObject highSchoolObj = (JSONObject)matrixDetail.get(0);
			String highSchoolboard = highSchoolObj.get("10ClassBoard").toString();
			
			JSONObject interSchoolObj = (JSONObject)matrixDetail.get(1);
			String interSchoolboard = interSchoolObj.get("12ClassBoard").toString();
			

			return "Hi " + name + " you 10 board is  " + highSchoolboard + " and for 12 is  " + interSchoolboard;
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "Parse Error Try Again";
		}
	}

Now if you see JsonArray is the same as a simple Array. It also stores data at indexes. So here I have two indexes first index store information for 10ClassBoard. and second, store information for 12ClassBoard.

Now your class look like below with all three methods.

package com.javadream.jsonparser.controller;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JsonParserController {

	private static final Logger logger = LoggerFactory.getLogger(JsonParserController.class);

	private JSONParser parser = new JSONParser();

	@PostMapping("/parseSimpleJson")
	public String parser(@RequestBody String payload) {
		try {
			logger.info("payload= " + payload);
			JSONObject jObj = (JSONObject) parser.parse(payload);
			String name = jObj.get("name").toString();
			String age = jObj.get("age").toString();
			String email = jObj.get("email").toString();

			logger.info("name= " + name + " ,age= " + age + " ,email= " + email);
			return "Your name is " + name + " and you are " + age + " old. Your email id is" + email;
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "Parse Error Try Again";
		}
	}

	@PostMapping("/parserComplexJson")
	public String parserComplexJson(@RequestBody String payload) {
		try {
			logger.info("payload= " + payload);
			JSONObject jObj = (JSONObject) parser.parse(payload);
			String name = jObj.get("name").toString();
			String age = jObj.get("age").toString();
			String email = jObj.get("email").toString();

			JSONObject educationObj = (JSONObject) jObj.get("educationDetail");
			String collegeName = educationObj.get("college").toString();
			String course = educationObj.get("course").toString();
			String branch = educationObj.get("Branch").toString();

			return "Hi " + name + " you are student of " + collegeName + " college and your course is " + course;
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "Parse Error Try Again";
		}
	}

	@PostMapping("/parserHardJson")
	public String parserHardJson(@RequestBody String payload) {
		try {
			logger.info("payload= " + payload);
			JSONObject jObj = (JSONObject) parser.parse(payload);
			String name = jObj.get("name").toString();
			String age = jObj.get("age").toString();
			String email = jObj.get("email").toString();

			JSONObject educationObj = (JSONObject) jObj.get("educationDetail");
			String collegeName = educationObj.get("college").toString();
			String course = educationObj.get("course").toString();
			String branch = educationObj.get("Branch").toString();

			JSONArray matrixDetail = (JSONArray) jObj.get("matrixEducation");
			
			JSONObject highSchoolObj = (JSONObject)matrixDetail.get(0);
			String highSchoolboard = highSchoolObj.get("10ClassBoard").toString();
			
			JSONObject interSchoolObj = (JSONObject)matrixDetail.get(1);
			String interSchoolboard = interSchoolObj.get("12ClassBoard").toString();
			

			return "Hi " + name + " you 10 board is  " + highSchoolboard + " and for 12 is  " + interSchoolboard;
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "Parse Error Try Again";
		}
	}
}

Now run your application and make a post request with this hard JsonObject data.

jsonparser

Complete Code on Github: JsonParser Example

You may also like:

Spring boot security using JWT ( JSON WEB TOKENS ).

spring batch example

Spring boot cache example

Actuator in spring boot for monitoring application

Profiles in Spring boot application

Help Others, Please Share

In this article, we will learn about MySQL cascade. We use cascading operation when two tables are dependent on each other.

We apply this MySQL cascade on foreign keys. If any data modify from the parent table then this referenced table data will also modify.

The two most important cascade type are:

  1. ON DELETE cascade
  2. ON UPDATE cascade

ON DELETE cascade

We use ON DELETE cascade when we want that all referenced entities will automatically delete if we delete any parent entity.

Take below Example:

Suppose I have Two Tables

  1. person Table
  2. orders Table

person table structure is like below:

create table person(personId bigint(12) primary key,
name varchar(20),
age int(3));

orders table structure is like below :

create table orders(orderId bigint(12) primary key,
orderName varchar(20),
personId bigint(20),
foreign key(personId) references person(personId)
ON DELETE CASCADE );

If you see in orders table we use ON DELETE CASCADE. It means if we delete row from person table than row from orders table automatically delete which have same personId.

Take below Example to understand this

  1. Insert some data in person table.
  2. Insert some data in orders table.
insert into person values(1,"vasu",26);
insert into person values(2,"Ayush",26);
insert into person values(3,"sushmits",25);

insert into orders values(1,"Shoes", 1);
insert into orders values(2,"Jeans", 1);
insert into orders values(3,"Tshirt", 3);
insert into orders values(4,"Jacket",2 );

Now Our person and ordes table will look like this.

On DELETE cascade MySQL cascade

Now try to delete some data from person table.

delete from person where personId=1;

After execute above query check both the tables data and see the difference.

ON UPDATE cascade MySQL cascade

ON UPDATE cascade

This is the same as ON DELETE cascade. The difference is that instead of delete referenced table data it will update the data.

So we follow the same steps as ON DELETE cascade.

  1. Create person table.
  2. Create orders table with ON UPDATE cascade.
  3. Insert data in both the tables.
  4. Now update data from person table.
  5. Now select data from both the tables and see the differnece.

Follow the above steps:

person Table

create table person(personId bigint(12) primary key,
name varchar(20),
age int(3));

2- orders Table

create table orders(orderId bigint(12) primary key, orderName varchar(20),
personId bigint(20),
foreign key(personId) references person(personId)
ON UPDATE CASCADE );

3- Insert Data in both tables.

insert into person values(1,"vasu",26);
insert into person values(2,"Ayush",26);
insert into person values(3,"sushmits",25);
 
insert into orders values(1,"Shoes", 1);
insert into orders values(2,"Jeans", 1);
insert into orders values(3,"Tshirt", 3);
insert into orders values(4,"Jacket",2 );

4- Update persionId from person table.

update person set personId = 4 where personId = 1;

5- Now see the difference by making select query on both the tables.

mysql cascade

There are 5 options for ON DELETE cascade and they are as below.

  1. ON DELETE CASCADE : This is the default cascade as we used in our example.
  2. ON DELETE SET NULL : This cascade is used to set referenced entities value null if we delete the parent table entity.
  3. ON DELETE SET DEFAULT : This cascade is used to set referenced entities value default if we delete the parent table entity.
  4. ON DELETE RESTRICT: we can not delete the row from the parent table if it has any referenced row with the same id.
  5. ON DELETE NO ACTION: In this cascade, there is no referential delete action performed.

To use the above cascade in orders table the structure is like below:

ON DELETE CASCADE

create table orders(orderId bigint(12) primary key,
orderName varchar(20),
personId bigint(20),
foreign key(personId) references person(personId)
ON DELETE CASCADE );

ON DELETE SET NULL

create table orders(orderId bigint(12) primary key,
orderName varchar(20),
personId bigint(20),
foreign key(personId) references person(personId)
ON DELETE SET NULL );

ON DELETE SET DEFAULT

create table orders(orderId bigint(12) primary key,
orderName varchar(20),
personId bigint(20),
foreign key(personId) references person(personId)
ON DELETE SET DEFAULT );

ON DELETE RESTRICT

create table orders(orderId bigint(12) primary key,
orderName varchar(20),
personId bigint(20),
foreign key(personId) references person(personId)
ON DELETE RESTRICT );

ON DELETE NO ACTION

create table orders(orderId bigint(12) primary key,
orderName varchar(20),
personId bigint(20),
foreign key(personId) references person(personId)
ON DELETE RESTRICT );

The same Cascade is also applicable for ON UPDATE cascade just replace DELETE to UPDATE and remain syntax will be same.

You may also like:

MySQL CASE function Example

MySQL Dates and Times

Database backup in MySql

Reference

https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html

Help Others, Please Share

In this post we will see about Optional in Java 8. Optional Class is introduced in Java 8. So before learning about Optional class first we have to know

What is Optional ?

Optional is a container object that is used to contain not-null objects. Optional class introduced in Java 8 to prevent the NullPointerException.

Optional class is present in java.util package.

Just take an example without optional and check if an object contains null or not.

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {
		String[] name = new String[5];
		System.out.println(name[3].toUpperCase());
	}
}

If you try to run the above class you will get the below run time exception.

Exception in thread "main" java.lang.NullPointerException
	at com.vasu.myfirstproject.OptionalDemo.main(OptionalDemo.java:9)

We will get the java.lang.NullPointerException at runtime because we have not any value at index 3 and we try to convert this null value in Uppercase. java.lang.NullPointerException is the very comman problem that every java programmer will face.

Now Try the above example again and use Java 8 Optional class to prevent this null pointer exception at run time.

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {
		String[] name = new String[5];
		Optional<String> myName = Optional.ofNullable(name[3]);
		if(myName.isPresent()) {
			System.out.println(name[3].toUpperCase());
		}else {
			System.out.println("No value find at the given index");
		}
	}
}

Now if you run the above programe you will get the below output.

No value find at the given index

Now you can see that we use ofNullable() and isPresent() method. This method is the static method of Optional class.

ofNullable() function allowed passed parameter to be null.

isPresent() function returns Boolean. This function return true if any value is present and retun false if null value found.

Optional class provide many static methods and they are:

  1. ofNullable() function allowed passed parameter to be null.
  2. of() function do not allow null value. It will throw NullPointerException if passed parameter is null.
  3. ifPresent() function is execute only if the Optional object is not empty.
  4.  isPresent() function returns Boolean. It return true if value is present otherwise it retun false.
  5. hashCode() function return the hashcode.
  6. get() this function returns the value. Value should be present to use this static function.
  7. orElse() function returns the present value. If value is not present than it will return the default passed value.
  8. orElseGet() function return present value. If value is not present it call other method and return the value.
  9. orElseThrow() function return the value. It will throw Exception if value is not present.

Optional.ofNullable() function Example:

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {
		String name1 = null;
		String name2 = "vasu";
		Optional<String> op1 = Optional.ofNullable(name1);
		System.out.println(op1.isPresent());
	}
}

As you can see we have define name1 as null and name2 as vasu. Now try to pass name1 parameter in ofNullable() function and see the output it will return.

false

Now pass the name2 parameter and see the output.

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {
		String name1 = null;
		String name2 = "vasu";
		Optional<String> op1 = Optional.ofNullable(name2);
		System.out.println(op1.isPresent());
	}
}

Output will be

true

Optional.of() function Example.

This function does not allow null if we try to pass the the null parameter than it will throw run time Exception Just take an example.

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {
		String name1 = null;
		String name2 = "vasu";
		Optional<String> op1 = Optional.of(name1);
		System.out.println(op1.isPresent());
	}
}

If you run this programe it will throw exception because we pass the null parameter. Output will be

Exception in thread "main" java.lang.NullPointerException
	at java.base/java.util.Objects.requireNonNull(Objects.java:221)
	at java.base/java.util.Optional.<init>(Optional.java:107)
	at java.base/java.util.Optional.of(Optional.java:120)
	at com.vasu.myfirstproject.OptionalDemo.main(OptionalDemo.java:10)

Now try to pass not null value as parameter and see the output.

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {
		String name1 = null;
		String name2 = "vasu";
		Optional<String> op1 = Optional.of(name2);
		System.out.println(op1.isPresent());
	}
}

Output

true

Optional.ifPresent() function Example

This function is execute only if the Optional object is not empty Just look at below example

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {

		Optional<String> op1 = Optional.empty();
		Optional<String> op2 = Optional.of("My name is vasu");
		
		op1.ifPresent(obj -> System.out.println(obj));
		op2.ifPresent(obj -> System.out.println(obj.toUpperCase()));
	}
}

If you run the above programe you will get the output like

MY NAME IS VASU

This program print op2 object of Optional in Uppercase because op1 object returns the empty Optional object.

Optional.isPresent and Optional.hashCode() Example

Optiona.isPresent() function retuns true if value is presnt and retuns false if value is null. And Optiona.hashCode() function is used to get the hashCode of object.

Look at the below Example

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {

		String name1 = null;
		String name2 = "vasu";
		
		Optional<String> op1 = Optional.ofNullable(name1);
		Optional<String> op2 = Optional.ofNullable(name2);

		
		System.out.println(op1.isPresent());
		System.out.println(op2.isPresent());
		
		System.out.println(op1.hashCode());
		System.out.println(op2.hashCode());
		
	}
}

Output:
false
true
0
3612237

Optional.get() Example

This function return the present value. For using get() method value should be present.

Just look at below example

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {

		String name1 = null;
		String name2 = "vasu";
		
		Optional<String> op1 = Optional.ofNullable(name1);
		Optional<String> op2 = Optional.ofNullable(name2);

		
		System.out.println(op1.get());	
	}
}

Now run this program and see the output. Output will be a run time exception because we call get() on null.

Output:

Exception in thread "main" java.util.NoSuchElementException: No value present
	at java.base/java.util.Optional.get(Optional.java:148)
	at com.vasu.myfirstproject.OptionalDemo.main(OptionalDemo.java:16)

Now call get() on op2 object and see the output

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {

		String name1 = null;
		String name2 = "vasu";
		
		Optional<String> op1 = Optional.ofNullable(name1);
		Optional<String> op2 = Optional.ofNullable(name2);
		
		System.out.println(op2.get());	
	}
}

Output

vasu

Optional.orElse() , Optional.orElseGet() Example

orElse() and orElseGet() function returns the present value. If value is not present than it will return the default passed value.

package com.vasu.myfirstproject;

import java.util.Optional;

public class OptionalDemo {

	public static void main(String[] args) {

		Optional<String> op1 = Optional.ofNullable("vasu");
		Optional<String> op2 = Optional.empty();
		
		System.out.println(op1.orElse(new String("vishu")));	
		System.out.println(op2.orElse(new String("vishu")));

	}
}

Output

vasu
vishu

You may also like:

Spring Boot Project Using Spring Initializer

Create WAR of Spring Boot Project

Change Running Server Port in Spring Boot

Spring Boot With MySql

How to use multiple database in a single spring boot application

Reference:


Optional (Java Platform SE 8 ) – Oracle Help Center

Help Others, Please Share

In this post we will see about spring batch. So the first question will come in our mind is

What is Spring Boot Batch ?

Spring boot batch is framework that is designed to execute large and robust batch application.

Batch application Example.

As we know we use spring boot batch to execute large task. So here are some application scenario where we use Batch framework.

1- Suppose we have a big CSV file which contains billions rerecords and i want to store that data in the MySQL database.

So if you try yo insert this billions record in one go your application takes a very very long time to execute this task.

And it may also be possible that your database not support this huge amount of insertion.

So in this case we will use Spring boot Batch framework and execute this task in batch chunks means we divide this task of insertion in chunks.

The above scenario we will cover in another application first we see some easy example to learn spring boot batch framework.

In this example we take a list of names and try to process this list data in batch.

Project Structure:

spring batch

There are some keyword in spring boot batch framework. That we use to process our application.

  1. ItemReader
  2. ItemProcessor
  3. ItemWriter
  4. Step
  5. Job
  6. Job Listener
  7. JobBuilderFactory
  8. StepBuilderFactory
  9. JobLauncher
ItemReader :

ItemReader is like entry point it will read your data from file or from the source you define.

ItemProcessor :

ItemProcessor is process the data that you read using ItemReader.

For Example you read a List of names using ItemReader and you want to convert this name in uppercase. So this task is done by ItemProcessor.

ItemWriter :

After Process the data by ItemProcessor we have to write this data. So for this we use ItemWriter.

Step :

After process all above steps ItemReader, ItemProcessor, ItemWriter we will get the steps.

Job :

Now we have to create a Job that executes the Step. Job is an interface and resides in org.springframework.batch.core package.

Job Listener :

This class deines two methods beforeJob and afterJob. As the name suggest this function is used to perform task before and after job execution.

JobBuilderFactory :

JobBuilderFactory is a class that used to create the Job.

StepBuilderFactory :

StepBuilderFactory is a class that used to create the Step.

JobLauncher :

Till now we have create the Job. Now we have to excute this Job for this we will use JobLauncher.

Now Lets do a coding example. We Just create a List of names and print this List name in batch.

To create above Project we have to follow below steps:

1- Add required dependency in your pom.xml file or add from Maven Repositry.

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

2- Now create a class that implements ItemReader interface.

package com.vasu.springbatch;

import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.NonTransientResourceException;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;

public class Reader implements ItemReader<String> {

	private String[] names = {"Vasu","Vishu", "Ayush","Sushmita","konika"};
	private int count;
	
	@Override
	public String read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
		System.out.println("Inside Read Method");
		if(count < names.length) {
			return names[count++];
		}else {
			count = 0;
		}
		return null;
	}

}

3- Create a class that process above list and convert List names into UpperCase.

package com.vasu.springbatch;

import org.springframework.batch.item.ItemProcessor;

public class Processor implements ItemProcessor<String, String> {

	@Override
	public String process(String item) throws Exception {
		System.out.println("Inside Process method");
		return "PROCESSED "+ item.toUpperCase();
	}
}

4- Create Writer class that implement ItemWriter.

package com.vasu.springbatch;

import java.util.List;

import org.springframework.batch.item.ItemWriter;

public class Writer implements ItemWriter<String> {

	@Override
	public void write(List<? extends String> items) throws Exception {
		System.out.println("Inside Write method");
		System.out.println("Data In UpperCase is " + items);
	}
}

5- Create a Job Listener class .

package com.vasu.springbatch;

import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;

public class MyJobListener implements JobExecutionListener {

	@Override
	public void beforeJob(JobExecution jobExecution) {
		System.out.println("Before Job Started");
	}

	@Override
	public void afterJob(JobExecution jobExecution) {
		System.out.println("After Job Ended " + jobExecution.getStatus().toString());
	}
}

6- Now Create a Config class and initialize all the above beans.

package com.vasu.springbatch;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BatchConfig {
	
	@Autowired
	private StepBuilderFactory sdf;
	
	@Autowired
	private JobBuilderFactory jbf;
	
	@Bean
	public Job job() {
		return jbf.get("myFirstBatchJob") 	
				.incrementer(new RunIdIncrementer())
				.listener(listener())
				.start(step())
				.build();
	}
	
	@Bean
	public Step step() {
		return sdf.get("myFirstBatchStep")
				.<String,String>chunk(3)
				.reader(reader())
				.processor(processor())
				.writer(writer())
				.build();
		
	}

	@Bean
	public Reader reader() {
		return new Reader();
	}

	@Bean
	public Writer writer() {
		return new Writer();
	}

	@Bean
	public Processor processor() {
		return new Processor();
	}

	@Bean
	public MyJobListener listener() {
		return new MyJobListener();
	}
}

7- Use @EnableBatchProcessing annotation in your main class.

package com.vasu.springbatch;

import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableBatchProcessing
public class SpringbatchApplication {

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

8- Create a Test Class to test the batch process. In this class autowired JobLauncher.

package com.vasu.springbatch;

import org.junit.jupiter.api.Test;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SpringbatchApplicationTests {

	@Autowired
	JobLauncher launcher;

	@Autowired
	Job job;

	@Test
	void testBatch() throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException {
		JobParameters jobParameters = new JobParametersBuilder()
				.addLong("todayTime", System.currentTimeMillis())
				.toJobParameters();
		launcher.run(job, jobParameters);
	}

}

Now run this class as JUnit Test.

Output:

spring batch

Complete code on Github- Spring batch Github

You may also like

Spring boot security using JWT ( JSON WEB TOKENS ).

HTTPS in Spring Boot

Spring Boot with Apache kafka.

Profiles in Spring boot application

Help Others, Please Share

We know that spring boot framework is an advance framework developed by the pivotal. Using Spring boot we can setup the spring boot hello world example application within 5 minutes.

If we talk about spring framework than this framework will take a very long time to setup the project. We have to define many xml for a tiny task. Using Spring boot we get rid of this and create our project within minutes.

So here we go now it’s time to create the spring boot hello world example. In this Project we just print the Hello Word on our Google Chrome web browser.

To create Spring Boot Hello World project we have to follow the below steps:

  1. First go to the Spring initializr website https://start.spring.io/
  2. Configure Project Metadata configuration
  3. Choose Spring Web dependency from Add Dependency tab.
  4. Click on GENERATE button now you will get a .zip file.
  5. Open your eclipse or any other editor and import this project.
  6. Now make a simple controller class using some spring boot annotation that return simple hello word while calling your end point.

Now follow above steps one by one

1- First we have to go to the spring initializer and here we select Project as Maven Project and Language as Java. Now choose Spring boot version currently we are using 2.3.3.

Now configure the Project Metadata details here you see many options and they are:

Group – It is your package name define so define accordingly here i am define com.vasu

Artifact and Name – Both are same after defining this you will get your complete pacakge like i am defining here myfirstproject. So my package name now become com.vasu.myfirstproject.

Description – Give description about your project.

Package name – It is the combination of Group and Artifact. It will autofill automatically.

Now define your Packaging type here we choose Jar.

Now choose your Java version minimum version is Java 8 for using Spring Boot.

spring boot hello world example
spring boot hello world example
spring boot hello world example

After clicking on GENERATE button you will get your project in .zip format. Now extract this project and open in your eclipse or any other editor.

Now In Your Eclipse Project Structure is like :

spring boot hello world example

your MyfirstprojectApplication.java class is using the annotaion @SpringBootApplication that defines it is you main class you have to run this class to start your project.

Now it’s time to return Hello Word from our application to Chrome Console. So for that create a controller class. We are creating with name MyFirstController.java class.

Here In this class we define two annotaions

  1. @RestController
  2. @GetMapping

@RestController annotation is used to define that our class return object as output we can return any object in this case we simply return the String Object.

@GetMapping annotaion is used to define end point here we define (“/) means if we hit http://localhost:8080 on our browser than we will get the output:

MyFirstController.java
package com.vasu.myfirstproject.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyFirstController {

	@GetMapping("/")
	public String test() {
		return "Hello Word";
	}
}

Application Run Steps:

Right click on MyfirstprojectApplication.java class. Click on Run As now click on Java Application. congrats your application is start now.

Now run your application and hit http://localhost:8080 URL you will get “Hello Word” as output.

spring boot hello world example

Complete code on Github- Spring Boot Hello Word GitHub URL

You may also like:

Create WAR of Spring Boot Project

How to use H2 database in spring boot application

Help Others, Please Share

In this post we will see spring boot https. We Know that our data is going through the network. And if we are using http then our data is visible and anybody can see or intercept this data without any difficulty. spring boot https allows us to encrypt our data over the network so nobody can see our data over the network while transmitting.

For enable HTTPS we follow the below steps.

  1. Go to the bin folder of your JRE installed location and create a certificate using the following command.

Syntax :

keytool -genkey -keystore 
{ GIVE YOUR LOCATION } /{GIVE ANY NAME}.jks
alias tomcat -keyalg RSA -keysize 4096

Example

keytool -genkey -keystore
/usr/local/vasuCertificate.jks 
alias tomcat -keyalg RSA -keysize 4096
2- Copy this certificate inside your resources folder of Project.
3- Make following entry in your application.properties.
# for https
server.port=8442
server.ssl.key-store=classpath:vasuCertificate.jks
server.ssl.key-store-password=vasurajput
server.ssl.key-password=vasurajput
4- Now Make A Controller Class to create some end point.
@RestController
public class HomeController {

private static final Logger logger = LoggerFactory.getLogger("HomeController.class");

  @GetMapping("/")
   public String test() {
    logger.info("Test Controller Call");
     return "index";
   }
}
5- Now create a configuration class for enable HTTPS.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.vasu.HttpsDemo.Controller;

import java.io.File;
import java.io.IOException;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

/**
*
* @author vasu rajput
*/

@Configuration
public class Https {

@Bean
public ServletWebServerFactory servletContainer() {

TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {

@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
  }
};
tomcat.addAdditionalTomcatConnectors(createStandardConnector());
return tomcat;
 }

private Connector createStandardConnector() {

Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
  }
}

As we know for https we define 8443 port. So in above configuration class code we define connector.setRedirectPort(8443) this port.

Now if you follow all above steps so you have successfully confgured the https in spring boot.

Now go to your browser and type http://localhost:8080 you will automatically redirect to https://localhost:8443/ port which uses https.

You may also like:

Let’s Encrypt Certificate in Java with Apache Tomcat

Spring Boot Security With JWT and MySQL

Help Others, Please Share

Java toLowerCase function of string converts the given string into lower case. Return type of this function is String.

For Example if i have a string like “I Like Java Programming Language” and i want to convert this string into lower case then i will use toLowerCase function of String.

package javadream;

import java.util.Locale;

public class JavaDream {

	public static void main(String[] args) {
		 String str = "I Like Java Programming Language";
		 String lowerCase = str.toLowerCase();
		 System.out.println(lowerCase);
	}
}

Output

tolowercase java

As toLowerCase function java also provides toUpperCase function. This function is used to convert given string into upper case.

toUpperCase Function

package javadream;

import java.util.Locale;

public class JavaDream {

	public static void main(String[] args) {
		 String str = "I Like Java Programming Language";
		 String upperCase = str.toUpperCase();
		 System.out.println(upperCase);
	}
}

Output

You may also like

CASE Statement in MySQL Example

Spring Boot Complete Tutorial from Zero to Hero

Refrence:

Java Official Documents

Help Others, Please Share

In this post we will see CASE Statement in SQL. CASE Statement is like if-else block of programming language. Like in programming language we perform some task if the condition is true if not then we perform other task in else block same functionality is used for CASE statement. We use CASE when we have to perform some task based on the condition.

Syntax of Case statement in MySQL is like :

CASE
WHEN SOME_CONDITION THEN CONDITION_RESULT
WHEN SOME_CONDITION THEN CONDITION_RESULT
ELSE ELSE_CONDITION_RESULT
END

For using CASE Statement in SQL just take an Example suppose If i have a table of Student that contains two column name, course. Now i want that if the course is CSE then i will display you have exam tomorrow and for other courses i want to display Enjoy you don’t have exam tomorrow. So in this case we use CASE function.

Student Table:

CASE Statement in SQL

Now we will use CASE function in above table. The query will be like below.

select name,course,
case
when course = "CSE" then "you have Exam tomorrow"
else "Enjoy the day you don't have exam"
end as ExamStatus
from student;
SQL CASE Statement

You may also like:

How to database backup in MySQL

MySQL Dates and Times function example

Integration of Springboot with MySQL Database Example.

Refrences:

MySQL official docs for functions.

Help Others, Please Share

In this post we will see MySQL dates and times related examples. As we know MySQL provide some functions using which we can get date and time and related data. As we know there are many scenario when we have to get date and time and some time we have to perform some mathematics with dates and times also so MySQL inbuilt function is very helpful in all of this . Some of the inbuilt MySQL Dates and Times functions are.

  1. now()
  2. curdate()
  3. curtime()
  4. year()
  5. month()
  6. monthname()
  7. day()
  8. dayname()
  9. dayofmonth()
  10. dayofweek()
  11. dayofyear()

1. now()

now() is a inbuilt function provided by MySQL. This function provide us current date and time of server.

2. curdate()

curdate() is a inbuilt function provided by MySQL. This function provide us current date of the server.

3. curtime()

curtime() is a inbuilt function provided by MySQL. This function provide us current time of the server.

date and time MySQL

4. year()

year() function is used to get the year from the current date. We can use now() and curdate() function with year() to fetch the year.

year() in MySQL

5. month()

This function is used to get the month from the current date of server.

6. monthname()

This function is used to get the name of month from the current date of server.

mont() in MySQL

7. day()

This function is used to get the day from the current date of server. There are many other functions for getting details of day and that are dayname(), dayofmonth(), dayofweek(), dayofyear().

day() in MySQL

You may also like :

How to take databackup in MySQL using commandLine.

MySQL Basic Commands.

Reference :

MySQL official Document for Dates and Times

Help Others, Please Share

In this Post we will see how to take MySQL database backup using command line. First we have to login our MySQL using below command and enter password.

mysql -u vasu -p

Now to show all databases we use below command.

show databases

Now above command will show all the databases list that are present in your MySQL. Now it’s time to backup some database. So to take backup of any database we will use below syntax.

Syntax :
mysqldump -u {Mysql UserName} -p {databaseName} > {location where you want to save}\{Name What you want to give}.sql

Example
mysqldump -u vasu -p myFirstDB > /usr/local/myFirstBackup.sql


After this command hit enter it will ask your Mysql Password Enter the password and you will successfully get the database backup.

Now After getting Backup we have to use it in mysql ,So for storing this backup in mysql we use the command source

Use the Following Syntax for restore database backup

Syntax:

source { location of database backup file }

Example:

source /usr/local/myFirstBackup.sql

If You want to get mysql database backup using cmd in windows then use following steps

First Go to to the bin folder of your mysql using the following path

  1. C:\Program Files\MySQL\MySQL Server 5.7\bin
  2. Now use ALT + D
  3. Now when address bar is highlighted, type cmd in the bar.
  4. Now Use the same command you use above
  5. mysqldump -u root -p yourdatabasename > c:/myfirstbackup.sql
  6. source C:\myFirstBackup.sql

Note : while you using cmd it might be possible that you get the Access is denied error, To resolve this open cmd  via Run as administrator , now use command it will work .

You may also like

How to create user in MySQL

Help Others, Please Share