Category: Spring boot complete tutorial with example

Home / Category: Spring boot complete tutorial with example

In this blog we see Visual studio code editor download for windows 10. So as we know to create a React js application we need two things. First, we have to install the Node Js in our system. And second is we need a code editor. We are going to use the visual studio code editor.

So if you don’t installed Node Js in your system till now so you can follow the below blog to install Node Js in your system.

Install Node Js in Windows system

So after installing Node Js now we have to install the visual studio code editor. We are going to install this editor in the windows system. So we have to follow the below steps:

  1. Go to the visual studio website using the URL https://code.visualstudio.com/download
  2. Choose your system configuration as we have a 64-bit windows system so we are going to click on System Installer of 64-bit.
  3. Now after installation complete right click on the file and click on Show in folder.
  4. Now follow the below steps as per the images to complete the installation of visual studio code.
Visual studio code download for windows 10

So if you reach here congrats you have successfully installed the visual studio code editor. It will automatically open once you click on the Finish button. If not so you can go to the desktop and double click on visual studio code editor it will open.

You may also like

Angular Js Routing integration with spring boot application.

Your Code journey from local to Github repository Install GitHub and push your code to GitHub repo.

Help Others, Please Share

In this blog we see how to install node js on windows 10. Node Js is the server-side javascript run time environment. So if we want to run any javascript code on the server then we have to install the Node Js. So now take an example, Suppose you want to create a project using React Js.

As we know that React js is a javascript library to create or build the user interface. So the question is can we directly run React js application on our machine, So the answer is No.

To run React Js application in your system you have to install the Node Js.

We can easily install the node js on windows 10. So to install Node js you have to follow the below steps:

  1. Go to the Node Js website using the URL https://nodejs.org/en/download/
  2. Choose your system it may be Windows, Mac, or Linux.
  3. In our case it is windows and as we have the 64-bit system so I choose Windows Installer (.msi) 64 bit.
  4. Your installer will start downloading. So after downloading complete right click on this and select show in folder.
  5. Now double click on this and follow the steps as per the below images.

So Congrats now if you reach here you have successfully install the Node js. Now this time to verify that we have installed the Node js so for that press the window button of your computer and search for cmd.

Now after opening this terminal you have to type the below command to check your Node js version.

npm -v

After typing the above command you will get your Node Js version.

You may also like

Your code journey from local to GitHub repository.

Send SMS to any mobile number worldwide using Spring boot and Twilio

Help Others, Please Share

In this example, we learn how to sort Map in java8. . We can sort map by key and sort map by value as well in java. Let’s take an example we have a hash map that has data of the Movies

For Example Movie name is the key of hash map and movie ratings as the value in hash map. So Now we have many scenerio that we can sort this hash map.

Below are the Scenarios to sort the Hash Map in java.

Now we have seen all the scenarios. So take an example of a hash map that contains the movie name as the key. and rating as values.

Our hash map will look like below:

Map<String, Double> ratingMap = new HashMap<>();
ratingMap.put("Inception", 2.0);
ratingMap.put("GoodFellas", 3.0);
ratingMap.put("Thor", 4.5);
ratingMap.put("Alien", 5.0);
ratingMap.put("Joker ", 1.5);

Now we will sort this map on the basis of above scenerios:

Sort Map by key Alphabetically

In Our case we have movie’s name as keys. So after sorting this map we will get all the movies in ascending order.

HashMap<String, Object> sortAlphabat = ratingMap.entrySet().stream()
				.sorted(Map.Entry.comparingByKey(Comparator.naturalOrder().toString().CASE_INSENSITIVE_ORDER))
				.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue,
						LinkedHashMap::new));

Sort Map by Key Alphabetically In Descending order

HashMap<String, Object> sortAlphabatDesc = ratingMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue,
LinkedHashMap::new));

Sort Map by value in ascending order

In our case, we have ratings as hash map values. So after Sort, we will get the result in ascending order on the basis of ratings.

HashMap<String, Object> sortByValueInAscd = ratingMap.entrySet().stream()
				.sorted(Map.Entry.comparingByValue(Comparator.naturalOrder())).collect(Collectors.toMap(
						Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

Sort Map by value in descending order

Now we sort the ratings in the descending orders. So the movie that has the highest rating will come first and so on.

HashMap<String, Object> sortByValueInReverse = ratingMap.entrySet().stream()
				.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

Sometimes we need to sort our map on the basis of some custom sequence. So for example we have a custom list in which we define the rating sequence and we want to sort the map by this custom list. So for this look at the below example.

List<Double> ratinCustomSeq = Arrays.asList(5.0, 2.0, 3.0, 1.5, 4.5);

HashMap<String, Object> sortByCustomSeq = ratingMap.entrySet().stream()
				.sorted(Map.Entry.comparingByValue(Comparator.comparingInt(ratinCustomSeq::indexOf)))
				.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue,LinkedHashMap::new));

What if you need only the movie’s name on the basis of rating ascending order. So for that, we can return the List of movies instead of the hash map after sorting the map. Look at the below example.

Sort Map by values and Return List of keys

List<String> sortByValueAndGetListOfKeys = ratingMap.entrySet().stream()
				.sorted(Comparator.comparing(Map.Entry::getValue)).map(Map.Entry::getKey).collect(Collectors.toList());

So we have cover all the scenerio for sort hash map so your complete class will look like:

package map;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MapSortDemo {
	public static void main(String[] args) {
		Map<String, Double> ratingMap = new HashMap<>();
		ratingMap.put("Inception", 2.0);
		ratingMap.put("GoodFellas", 3.0);
		ratingMap.put("Thor", 4.5);
		ratingMap.put("Alien", 5.0);
		ratingMap.put("Joker ", 1.5);
		
		HashMap<String, Object> sortAlphabat = ratingMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey(Comparator.naturalOrder().toString().CASE_INSENSITIVE_ORDER))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue,
                        LinkedHashMap::new));
		
		System.out.println("Sort map by key Alphabetically Ascending Order => "+ sortAlphabat);
		
		HashMap<String, Object> sortAlphabatDesc = ratingMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue,
                        LinkedHashMap::new));
		
		System.out.println("Sort map by key Alphabetically Descending order=> "+ sortAlphabatDesc);
		
		HashMap<String, Object> sortByValueInAscd = ratingMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.naturalOrder())).collect(Collectors.toMap(
                        Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
		
		System.out.println("Sort map by value in Ascending Order => "+ sortByValueInAscd);
		
		HashMap<String, Object> sortByValueInReverse = ratingMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

		System.out.println("Sort map by value in Descending Order => "+ sortByValueInReverse);
		
		List<Double> ratinCustomSeq = Arrays.asList(5.0, 2.0, 3.0, 1.5, 4.5);
		 
		HashMap<String, Object> sortByCustomSeq = ratingMap.entrySet().stream()
		                .sorted(Map.Entry.comparingByValue(Comparator.comparingInt(ratinCustomSeq::indexOf)))
		                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue,LinkedHashMap::new));
		
		System.out.println("Sort map by custom sequence => "+ sortByCustomSeq);
		
		List<String> sortByValueAndGetListOfKeys = ratingMap.entrySet().stream()
                .sorted(Comparator.comparing(Map.Entry::getValue)).map(Map.Entry::getKey).collect(Collectors.toList());

		System.out.println("Only Movies name after sort by rating values in Ascending order => "+ sortByValueAndGetListOfKeys);
	}
}

Output

java sort map by key

You may also like

Send SMS on any mobile number worldwide using Twilio and Spring boot.

Why you should avoid split() method and use splitAsStrem() method of java8

Parse any json using JsonParser.

Like our facebook page

Help Others, Please Share

In this example, we will learn about how to send SMS to mobile numbers using spring boot and Twilio ( Twilio Java API). So we have to see first that what is Twilio?

Twilio is an American-based cloud communication company that provides many services like Calling, SMS, and IVR. Twilio provides you a free trial of up to 15$. We can use this 15$ to test our application feature for calling or sending SMS.

As we are going to send Text SMS to mobile numbers in this example ( Twilio Java API ). So we have to create a Twilio account. After SignUp to Twilio, we get Account SID and Auth Token. We use these two values in our Spring boot application to send SMS. We can also set up one test number provided by Twilio to Send SMS.

So we will complete this application in Two Steps:

  1. Create the Twilio Account.
  2. Integrate Twilio in our Spring boot application.

Step 1 : Create Twilio Account

You have to follow the below steps to sign up on Twilio.

  1. Open Twilio Website using URL ( https://www.twilio.com/ )
  2. Click on the Sign-up button.
  3. Fill in your details and click on Start your free trial.
  4. After that, you will get a verification link on your email just verify that link.
  5. Now You have to enter your mobile number to verify. After entering the number, you will get an OTP just submit that OTP.
  6. You have to fill in the basic details now means what service you want to use. What will you build with Twilio etc?
  7. Congrats your Twillio Account is set up now.
  8. Now you have to set up a Test number using which you send the SMS. So for that, you have to click on get a trial phone number.

Twilio
Twilio Java API
java Twilio
Twilio java

Now see your dashboard you have all three details that you needed. account SID, accountAuthToken, and a Trial number.

Step 2: Create Spring Boot Application And Integrate Twilio.

1- To Integrate Twilio with Spring boot we use the Twilio SDK. So You can use the below maven dependency for Twilio SDK.

<dependency>
 <groupId>com.twilio.sdk</groupId>
 <artifactId>twilio</artifactId>
 <version>7.34.0</version>
</dependency>

2- Now we follow the simple MVC architecture. We create a Controller class that has a POST method.

This POST Method accepts two parameters that is SMS Text and the mobile number to whom we have to send the SMS.

To accept these parameters we create a POJO class.

Now we create the service class to write the business logic.

In this service class, we initialize the Twilio using account SID and auth Token.

We use the few classes of Twilio one is PhoneNumber, this class is used to convert our string mobile number into a phone number.

Second class is MessageCreator it accepts three parameters:

  1. Receiver Phone Number
  2. Sender Phone Number
  3. SMS text message

Now we have to send the Text Message. So for this MessageCreator class has a method create(). So This method returns the Message class which has some final methods like getPrice(), getStatus().

So we create a controller class now.

package com.javadream.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.javadream.model.MessageModel;
import com.javadream.service.TwilloMessageSenderService;

@RestController
@RequestMapping("/twillo")
public class TwilloController {

	
	@Autowired
	private TwilloMessageSenderService twilloService;
	
	@PostMapping("/sendSMS")
	public String sendSMSByTwillo(@RequestBody MessageModel messageRequest) {
		String sendMessageResponse = twilloService.sendMessage(messageRequest);
		return sendMessageResponse;
	}
}

This is a controller class that has one Post method. So our POST endpoint will be:

http://localhost:8080/twillo/sendSMS

This class accepts a Pojo class as a parameter in the POST method. So we create this Pojo class. And after that, we Autowired our service class. So we also have to create this service class where we write our business logic.

MessageModel.Java

package com.javadream.model;

public class MessageModel {

	private String mobileNumber;
	private String smsText;

	public MessageModel() {
		super();
	}

	public MessageModel(String mobileNumber, String smsText) {
		super();
		this.mobileNumber = mobileNumber;
		this.smsText = smsText;
	}

	public String getMobileNumber() {
		return mobileNumber;
	}

	public void setMobileNumber(String mobileNumber) {
		this.mobileNumber = mobileNumber;
	}

	public String getSmsText() {
		return smsText;
	}

	public void setSmsText(String smsText) {
		this.smsText = smsText;
	}

}

Now we have to create the Service class.

TwilloMessageSenderService.java

package com.javadream.service;

import java.math.BigDecimal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.javadream.model.MessageModel;
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.rest.api.v2010.account.Message.Status;
import com.twilio.rest.api.v2010.account.MessageCreator;
import com.twilio.type.PhoneNumber;

@Service
public class TwilloMessageSenderService {

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

	@Value("${accountSID}")
	private String accountSID;

	@Value("${accountAuthToken}")
	private String accountAuthToken;

	@Value("${twilloSenderNumber}")
	private String twilloSenderNumber;

	public String sendMessage(MessageModel messageRequest) {
		try {
			Twilio.init(accountSID, accountAuthToken);

			String smsText = messageRequest.getSmsText();
			String mobileNumber = messageRequest.getMobileNumber();

			PhoneNumber recieverPhoneNumber = new PhoneNumber(mobileNumber);
			PhoneNumber senderTwilloPhoneNumber = new PhoneNumber(twilloSenderNumber);

			MessageCreator creator = com.twilio.rest.api.v2010.account.Message.creator(recieverPhoneNumber, senderTwilloPhoneNumber, smsText);
			Message create = creator.create();
			
			BigDecimal billingAmount = create.getPrice();
			Status status = create.getStatus();
			
			
			logger.info("Message Send Succesfully to the number " + mobileNumber);
			return "Message Send Succesfully";
		} catch (Exception e) {
			logger.error("Exception in sendMessage Method " + e);
			return "Message Send Fail";
		}

	}

}

Twilio with Spring boot

As you can see we are reding accountSID, accountAuthToken, twilloSenderNumber from the application.properties file. So make this entry in your application. properties file.

application.properties

accountSID=Copy From Twilio Dashboard
accountAuthToken=Copy From Twilio Dashboard
twilloSenderNumber=+1772252

Now Run Your application and hit your POST end point from Postman.

Twilio Spring boot

Note: Make Sure you use +Your Country code before your number in our case we are using an Indian number so we are using +91.

Now check your mobile You will recieve a SMS from Twilio Number.

Twilio Java Api

Get Complete Code On GitHub: Twilio With Spring Boot

Like Our Facebook Page

You may also like:

Why you should avoid Split() methos and use alternate of this splitAsStream() method in java.

Spring Batch Complete tutorial Execute big task in small small chunks

Avoid NullPointerException using java8 optional complate Example

Help Others, Please Share

In this example, we will learn about the Java8 splitAsStream method of the Pattern class. As you have face this scenario many times that you have a string variable and you want to split that.

For Example

String names = "vasu, ayush, sushmita, konika";

Now you want to split this string variable using “,” .

so the old approach that we use before java8 is the split() method.

String[] splitNames = names.split(",");

This is a very bad choice if we use the split() method because we have to avoid the array as much as we can in our code.

So the alternate of split() method is splitAsStream(). splitAsStream belongs to the Pattern class.

Note: If you want to use splitAsStream() method of Pattern class then you must have Java 8 or higher version installed.

splitAsStream() is used to return the stream of String instead of String array. So if we want to split the above String names variable and store the result as a list of strings. So we can use the below syntax :

String names = "vasu, Ayush, Sushmita, Konika";
List<String> splitNames = Pattern.compile(",").splitAsStream(names).collect(Collectors.toList());
splitNames.forEach(System.out::println);
Java 8 Pattern SplitAsStream

Now we know that pattern class resides in java.util.regex package. And it has a method splitAsStream(). This method is used to split the string using the given expression and return the Stream of the list as a result.

Syntax of splitAsStream() method

public Stream<String> splitAsStream(final CharSequence input)

It accepts the CharSequence in our example it is the names variable and returns the Stream of String as a result. In our example, it is returning List<String>.

Example 2:

Now suppose you have to split your string using : expression instead of ,

String names = "vasu:Ayush:Sushmita:Konika";
List<String> splitNames = Pattern.compile(":").splitAsStream(names).collect(Collectors.toList());
splitNames.forEach(System.out::println);

Output

splitAsStream java8

Example 3:

If you have to split your string from a specific word.

String names = "I like JavaDream it has a cool content";
List<String> splitNames = Pattern.compile("JavaDream").splitAsStream(names).collect(Collectors.toList());
splitNames.forEach(System.out::println);

Output

pattern java 8

You may also like:

Optional in java 8 tutorial with Example

Spring Batch Complete Tutorial with example.

Json Parser in Java Complete Example

Help Others, Please Share

In this article, we learn about spring angularjs integration and how to configure Angular JS routing with spring boot.

As we all know that we use angular js for creating single page application. Routing is the main feature of angular js to create a single page application.

It is very easy to integrate angular js with the spring boot application. And we can use either CDN or Maven dependency to create an angular application.

If you want to learn the integration of angular js with the spring boot application using Maven dependency you can check out this post.

What is Angular Js Routing?

As already told you that using angular js we can create the single page application. And routing allows displaying different page content on a single page.

Suppose when my application runs it will display the content of the index.jsp file. So this is my main page and I want to display diff page content on this page only because we are creating a single page application.

Integrate Angular Js with Spring boot application.

To integrate angular js with spring boot we have to follow the below steps:

  1. Create a spring boot web project with starter web dependency.
  2. Create a WEB-INF folder inside webapp folder. And after that create jsp folder inside the WEB-INF folder.
  3. Create JSP files inside the WEB-INF/jsp folder.
  4. Now create a JS folder for the routing.js file inside the static folder.

spring angularjs
spring angularjs example
spring angularjs example

Till now we have created our Project and create JSP inside our WEB-INF/jsp folder. Now add view prefix and suffix for displaying JSP files in your application. properties file.

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

Now open index.jsp file because when we run our application this file content display. Because we map this file to (“/”) endpoint in our controller class.

We add the angular and angular CDN on this page and also add our routing.js file reference in this file that we create inside the static/JS folder.

index.jsp

angular spring data rest
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring Angular Routing Example</title>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>
 <script src="JS/routing.js"></script>

</head>
<body ng-app="myRoutingApp">
<center><h2>This is a Index Page</h2></center>
<hr>
<ul>
  <li><a href="#!home">HOME</a></li>
  <li><a href="#!contact">CONTACT US</a></li>
  <li><a href="#!signup">SIGN UP</a></li>
</ul>

<hr>
<center><div ng-view></div></center>
</body>
</html>

Note: Make sure your href tag value is the same as that you give for when tag in your routing.js file.

routing.js

angular spring data rest
var app = angular.module("myRoutingApp", ["ngRoute"]);
app.config(function($routeProvider) {
  $routeProvider
  .when("/home", {
    templateUrl : "homeEndPoint"
  })
  .when("/contact", {
    templateUrl : "contactUsEndPoint"
  })
  .when("/signup", {
    templateUrl : "signUpEndPoint"
  })
  .otherwise({
	  templateUrl : "defaultEndPoint"
	  });
});

Note: Make Sure your template Url value is the same as that you define in your controller class endPoint.

MyController.java

package com.vasu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class MyController {

	
	@GetMapping("/")
	public String index() {
		return "index";
	}
	
	@GetMapping("/signUpEndPoint")
	public String signUp() {
		return "signup";
	}
	
	@GetMapping("/homeEndPoint")
	public String home() {
		return "home";
	}
	
	@GetMapping("/defaultEndPoint")
	public String defaultRoute() {
		return "default";
	}
	
	@GetMapping("/contactUsEndPoint")
	public String contact() {
		return "contact";
	}
}

Now if you see we use <div ng-view></div> in our index.jsp file this is the place where our routing performs. This means all pages according to routing will display inside this tag.

Now run your application and see output. While after running application our default.jsp page content will display inside <div ng-view></div> tag.

Note: We see by default default.jsp content because we use .otherwise tag inside our routing.jsp file. And no routing is found for “/” so .otherwise template will display.

Download Complete code from Github

You may also like:

Spring boot security using JWT ( JSON WEB TOKENS ).

 How to deploy spring boot application on docker 

Spring Boot With AngularJS Using WebJars

Help Others, Please Share

In this artice we learn how to install github. As we know that Git is an open-source distributed version control software and we use git for versioning our software.

Using git we can upload our code on a central location called git repository. To upload our code on git we require below tools:

  1. A GitHub account
  2. Git installed on your window machine

How to create GitHub account

To create GitHub account you have to follow the below steps:

  1. Go to the GitHub website URL ( open Github ).
  2. Click on SignUp.
  3. Fill the form and click on Create account.
  4. Now you will get an email from GitHub click on the verify link.
How to install github
how to install github on windows
How to install github

How to install github on windows

To install Git on your window system you have to follow the below steps:

  1. Go to the git website using URL ( open git )
  2. Click on download.
  3. Now your download will start.
  4. Go to download folder and open the .exe file.
  5. You have successfully installed the git.
how to install github on windows
github on window
github
github
github

After this click on Next on every window. Do not change the default setting just click on Next on every window.

After completing all steps you will get a window click on Launch Git Bash and after that click on finish.

window github
github on window

Now just check the version of the git using below command.

git --version
github

So congrats till now you have successfully setup both the steps. You have created your account on GitHub and you have also installed git on your window machine.

Till this point we have complete git setup. Now lets see how to upload your file from your computer system to your GitHub repository through the git commands.

Lets see what we are going to do using below steps:

  1. Create a folder on our system.
  2. A .txt file and write some data in that file.
  3. Create a GitHub repository.
  4. Commit our .txt file means give some message to your commit so we can recognizes our version using this message.
  5. Link GitHub repository URL to our folder.
  6. Push our .txt file to the GitHub repository.

To follow above steps you must have some basic knowledge about the below Linux commands.

  1. mkdir
  2. cd
  3. touch
  4. vim

We use mkdir command for creating the folder. In this example we create a folder with name myGitHubFolder.

 mkdir myGitHubFolder

cd command is using for go inside the directory or folder of the given path.

 cd myGitHubFolder/

touch command is using for creating the files. In our case we create a .txt file using this touch command.

touch myGitFile.txt

vim command is using to open the .txt file and use to write some text inside that file.

vim myGitFile.txt

After using the above command a window display. After the press i from your keybord.

i is used for insert. After that write some text in that file and save. For saving data we have to press the below keyword.

esc : wq!

and press enter after typing above keywords.

github
github
github

Till now we have created a Folder with name myGitHubFolder and after that we create a .txt file inside this folder with name myGitFile.txt and put some text inside that.

Now we have to create a GitHub repository and for that we have to Sign in to our GitHub account and create the new repository.

github
how to install github in windows
how to install github in windows
how to install github in windows
how to install github in windows

You have successfully created a GitHub repository and after creating that you will see some commands display on that repository .

git init
git add README.md
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/vasurajput/JavadreamRepositry.git
git push -u origin main

Now open you git bash terminal and follow the below steps:

  1. Initialize git using git init command
  2. Add your .txt file using git add . command.
how to install github in windows

Now add GitHub user and GitHub repository URL to git bash.

github
github on window
how to install github in windows
github
how to install github in windows
how to install github in windows

You may also like:

Spring boot security using JWT ( JSON WEB TOKENS ).

spring batch example

Help Others, Please Share

Copy constructor in java is used to create the copy of an object.

Is there any copy constructor in java by default?

Java does not create any copy constructor by default like c++, We have to create the copy constructor explicitly.

First look at the complete code of copy constructor than we explain it step by step.

package Practice; 

  class Student { 
	private int id; 
	private String name; 

	public Student(Student copy) { 
		this.id = copy.id; 
		this.name = copy.name; 
	} 

	public Student(int id, String name) { 
		this.id = id; 
		this.name = name; 
	} 

	@Override 
	public String toString() { 
		return "Student [id=" + id + ", name=" + name + "]"; 
	} 
} 

public class CopyConstructor { 
	public static void main(String[] args) { 
		Student s1 = new Student(1, "vasu"); 
		Student s2 = new Student(1, "vishu"); 

		Student s3 = new Student(s1); 

		System.out.println(s1); 
		System.out.println(s2); 
		System.out.println(s3); 
	} 

} 

Now Run this programe and see the output.

Student [id=1, name=vasu] 
Student [id=2, name=vishu] 

Student [id=1, name=vasu] 

Explanation of above code:

To create a Copy constructor we have to define our class constructor like below.

class Student { 
 private int id; 
 private String name; 

public Student(Student copy) { 
      this.id = copy.id; 
      this.name = copy.name; 
  } 
}

In above syntax we define a Student class with two fields

  1. Id
  2. name

And a constructor that accept Student class object. And we assign this Student object value to our instance variable.

Now create a parameterized constructor and override the toString() method to see how the copy constructor works. Now our code looks like below:

class Student { 
	private int id; 
	private String name; 

	public Student(Student copy) { 
		this.id = copy.id; 
		this.name = copy.name; 
	} 

	public Student(int id, String name) { 
		this.id = id; 
		this.name = name; 
	} 

	@Override 
	public String toString() { 
		return "Student [id=" + id + ", name=" + name + "]"; 
	} 
} 

As you can see we have a class named Student with two constructor.

  1. Parameterized constructor
  2. Copy Constructor

Parameterized constructor accept id and name as a parameter and assign them to our instance variable.

Copy Constructor accepts a Student object and assigns them to our instance variable.

Now create the main method and create Object of Student class like below.
public static void main(String[] args) { 
		Student s1 = new Student(1, "vasu"); 
		Student s2 = new Student(1, "vishu"); 

		Student s3 = new Student(s1); 
		System.out.println(s1); 
		System.out.println(s2); 
		System.out.println(s3); 
	} 

As you can see we have define two object of class Student s1 and s2.

Now we create another Student object named s3 and assign object s1 to it.

Now we simply print all three objects.

See the result of the s3 object it is the same as the s1 object. This is because of the copy constructor because we pass this s1 object to our copy constructor using the below line of code.

Student s3 = new Student(s1); 

Copy constructor create the shallow copy not deep copy of objects.

Now you are confused why we use a copy constructor if we create the copy of the object using the clone method.

Copy Constructor Vs Clone method.

  1. It is very easy to create a copy of an object using a copy constructor as compare to the Clone method.
  2. If we use the Clone method then we have to implement the Clonable interface and also need to handle CloneNotSupportedException.

You may also like :

Spring boot security using JWT ( JSON WEB TOKENS ).

Optional in java 8 complete example

Help Others, Please Share

We know that we can easily design APIs in a spring boot application. @PathVariable and @RequestParam are the most used annotations of the spring boot framework. Both Spring PathVariable and Spring RequestParam used to extract parameters from GET requests.

Sometimes we need to pass some values in our URL for processing the business logic. And to extract these values we use @PathVariable and @RequestParam annotation of the spring boot framework.

There are two types of URLs that you have seen when you call any GET request API.

1- http://localhost:8080/getUserByName/vasu

2- http://localhost:8080/getUserByName?name=vasu

See the difference between above two URLs. For example we have to fetch a user record by his name and we have to pass the name of user in the URL. So there are two ways you can pass this name in URL like above.

The difference in above two URL is.

1- In the first URL, we pass the name directly like /vasu this way of passing parameter fetched by the @PathVariable annotation.

2- In the Second URL, we pass a name with a parameter like ?name=vasu this way of passing a parameter fetched by the @RequestParam annotation.

Spring PathVariable and Spring RequestParam both annotations are present in Spring boot you just have to add the starter web dependency in your pom.xml file.

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

Now create a Controller class and make two endpoints one for @PathVariable and another for @RequestParam.

package com.vasu.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

	@GetMapping("/getUserByName/{name}")
	public String getName(@PathVariable String name) {
		return "Your name using @Pathvariable is " + name;
	}

	@GetMapping("getUserByName")
	public String getNameReqParam(@RequestParam String name) {
		return "Your name using @RequestParam is " + name;
	}
}

Now run you application and check both the endpoints.

Output of @PathVariable endpoint is

spring pathvariable annotation

Output of @RequestParam endpoint is

spring requestparam annotaion

Everything is fine now. But there is a catch just focus on the below points.

1- Make sure the value inside your {} braces and the value you use with @PathVariable must be same otherwise you will get an exception.

For example @GetMapping(“/getUserByName/{name}“) and @PathVariable String name. In this we use same parameter that is name.

Just change the value and run the application for example if your @PathVariable endpoint is like below.

	@GetMapping("/getUserByName/{name1}")
	public String getName(@PathVariable String name) {
		return "Your name using @Pathvariable is " + name;
	}

In the above code, we change the parameter to {name1} and the parameter with @PathVariable is the name. Now run the application and hit the URL you will get an exception like below.

Spring pathvariable

And in console exception like below

[org.springframework.web.bind.MissingPathVariableException: Missing URI template variable 'name' for method parameter of type String]

So if you want to use the different parameter names in both places then you have to use the name attribute of @PathVariable annotation like below.

@GetMapping("/getUserByName/{name1}")
public String getName(@PathVariable(name = "name1") String name) {
return "Your name using @Pathvariable is " + name;
	}

Now run your application the same api will work now.

Do the same change and play with @RequestParam endpoint also and see the differences.

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 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

x