Category: Spring boot complete tutorial with example

Home / Category: Spring boot complete tutorial with example

In this tutorial, we will learn about the Retrofit client and learn how to call rest API in android using Retrofit. As we know Retrofit client is used to calling the third-party APIs from our android application. To integrate Retrofit into our android application we have to follow the below steps:

Permissions For Calling APIs

  1. Add the INTERNET permission inside the AndroidManifest.xml file. Without this permission, we can’t call the APIs.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

If we are calling remote APIs than its fine then you don’t need to add this android:usesCleartextTraffic property, but If we try to call the API from our localhost then android don’t allow us. So if we want to call the localhost API than instead of localhost we have to use the IP address of our network and also we have to add the below line in our AndroidManifest.xml inside the application tag.

android:usesCleartextTraffic="true"

To get your IP address open your cmd and type ipconfig command and copy the IP address from there. So if your localhost API is like

http://localhost:8080/test  
then it will become
http://192.168.1.5:8080/test

Steps to use Retrofit

2. Add the Retrofit client dependency in our app gradle file.

implementation 'com.squareup.retrofit2:retrofit:2.7.2'
implementation 'com.squareup.retrofit2:converter-gson:2.7.2'
implementation 'com.squareup.okhttp3:okhttp:3.6.0'
3. First We will create the design inside our activity_main.xml file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:textColor="@color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.022" />

    <Button
        android:id="@+id/getRequest"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get"
        tools:layout_editor_absoluteX="148dp"
        tools:layout_editor_absoluteY="64dp" />


    <EditText
        android:id="@+id/editText"
        android:layout_width="326dp"
        android:layout_height="39dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:hint="Write Here for Request"
        tools:layout_editor_absoluteX="42dp"
        tools:layout_editor_absoluteY="383dp" />

    <Button
        android:id="@+id/getPath"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Path Variable"
        tools:layout_editor_absoluteX="117dp"
        tools:layout_editor_absoluteY="139dp" />

    <Button
        android:id="@+id/getQuery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Query Param"
        tools:layout_editor_absoluteX="128dp"
        tools:layout_editor_absoluteY="200dp" />

    <Button
        android:id="@+id/getPathAndQuery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get With Path and Query"
        tools:layout_editor_absoluteX="95dp"
        tools:layout_editor_absoluteY="274dp" />

    <Button
        android:id="@+id/post"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Post"
        tools:layout_editor_absoluteX="166dp"
        tools:layout_editor_absoluteY="445dp" />


</LinearLayout>

So our app design will look like below

Spring boot API in android

4. Now we have to define the endpoints that we want to call from our android application. While using retrofit we define these endpoints inside the interface. So create an interface and put the below code there.

package com.example.retorfitapiexample;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;

public interface RetroApis {

    // As we are calling localhost APIs so we change localhost with the IP my actual localhost API is http://localhost:8080/
    String BASE_URL = "http://192.168.1.5:8080/";

    //calling URL = http://localhost:8080/test
    @GET("test")
    Call<Object> getTestData();

    //calling URL = http://localhost:8080/test/123
    @GET("test/{id}")
    Call<Object> getPathVariableData(@Path("id") String id);

    //calling URL = http://localhost:8080/queryTest?queryParam=vasu
    @GET("queryTest")
    Call<Object> getQueryParamData(@Query("queryParam") String queryParam);

    //calling URL = http://localhost:8080/queryTest/123?queryParam=vasu
    @GET("queryTest/{id}")
    Call<Object> getWithQueryAndParamVarTest(@Path("id") String id, @Query("queryParam") String queryParam);

    //calling URL = http://localhost:8080/postTest
    @POST("postTest")
    Call<Object> getPostData(@Body String body);
}

5. Now we have to create a class that is used to get the instance of Retrofit. Here we are creating a Singleton class so we only get the one instance of Retrofit for each call. We create a class and inside it’s default constructor we create the instance of Retrofit. So create a class with any name and put the below code there as we are creating a class with name MyRetrofitClient.java so our class will look like below:

package com.example.retorfitapiexample;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MyRetrofitClient {

    private static MyRetrofitClient myRetrofitClient = null;
    private static RetroApis myRetroApis;

    private MyRetrofitClient() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(myRetroApis.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        myRetroApis = retrofit.create(RetroApis.class);
    }

    public static synchronized MyRetrofitClient getInstance() {
        if (myRetrofitClient == null) {
            myRetrofitClient = new MyRetrofitClient();
        }
        return myRetrofitClient;
    }

    public RetroApis getMyApi() {
        return myRetroApis;
    }
}

6. Code For MainActivity.java

So now time come for writing our main class Code. Now open your MainActivity.java class and initialize all the View widget like text View, edit Text and buttons. we have implemented View.OnClickListener interface and override it’s onClick method in our MainActivity.java. Now our MainActivity.java class look like below:

package com.example.retorfitapiexample;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    TextView textView;
    EditText editText;
    Button getRequestButton;
    Button getRequestWithPathVariableButton;
    Button getRequestWithQueryParamButton;
    Button getRequestWithPathVarAndQueryParamButton;
    Button postRequestButton;

    private static final String EMPTY_STRING = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.textView);
        editText = (EditText) findViewById(R.id.editText);

        getRequestButton = (Button) findViewById(R.id.getRequest);
        getRequestWithPathVariableButton = (Button) findViewById(R.id.getPath);
        getRequestWithQueryParamButton = (Button) findViewById(R.id.getQuery);
        getRequestWithPathVarAndQueryParamButton = (Button) findViewById(R.id.getPathAndQuery);
        postRequestButton = (Button) findViewById(R.id.post);

        getRequestButton.setOnClickListener(this);
        getRequestWithPathVariableButton.setOnClickListener(this);
        getRequestWithQueryParamButton.setOnClickListener(this);
        getRequestWithPathVarAndQueryParamButton.setOnClickListener(this);
        postRequestButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.getRequest:
                getApiDataWithParamORPostData("");
                break;
            case R.id.getPath:
                getApiDataWithParamORPostData("path");
                break;
            case R.id.getQuery:
                getApiDataWithParamORPostData("query");
                break;
            case R.id.getPathAndQuery:
                getApiDataWithParamORPostData("queryAndPath");
                break;
            case R.id.post:
                getApiDataWithParamORPostData("post");
                break;
        }
    }

    private void getApiDataWithParamORPostData(String callType) {
        try {
            Call<Object> call = null;

            if (callType.equals("")) {
                call = MyRetrofitClient.getInstance().getMyApi().getTestData();
            } else if (callType.equals("path")) {
                call = MyRetrofitClient.getInstance().getMyApi().getPathVariableData(editText.getText().toString());
            } else if (callType.equals("query")) {
                call = MyRetrofitClient.getInstance().getMyApi().getQueryParamData(editText.getText().toString());
            } else if (callType.equals("queryAndPath")) {
                call = MyRetrofitClient.getInstance().getMyApi().getWithQueryAndParamVarTest(editText.getText().toString(), editText.getText().toString());
            } else if (callType.equals("post")) {
                call = MyRetrofitClient.getInstance().getMyApi().getPostData(editText.getText().toString());
            }

            call.enqueue(new Callback<Object>() {
                @Override
                public void onResponse(Call<Object> call, Response<Object> response) {
                    textView.setText(response.body().toString());
                }

                @Override
                public void onFailure(Call<Object> call, Throwable t) {
                    textView.setText("Api Call Failed" + t.getMessage());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            textView.setText("Some Exception Occurred in Api CAll");
        }
    }


}
Result of Application

Now We are done Just run your application and see the result.

Spring Boot APIs

As You know we are using local APIs that we have created with the spring boot framework. If you have your APIS to call then you can ignore this section but if you want to create local APIs to test your application then follow the below steps:

Create a Spring boot Project and put the below dependency in your pom.xml file:

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

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-devtools</artifactId>
 <scope>runtime</scope>
 <optional>true</optional>
</dependency>

<dependency>
 <groupId>org.json</groupId>
 <artifactId>json</artifactId>
 <version>20210307</version>
</dependency>

pom.xml

Spring Boot Controller for APIs

Now create a controller class and create the GET and POST APIs there. So just create a simple java class annotate that class with @RestController. And Now create method with @GetMapping to create GET APIs and @PostMapping to create POST APIs. So Now your Spring boot controller is look like below:

package com.javadream;

import org.json.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class APis {

	JSONObject jobj = new JSONObject();

	// URL = http://localhost:8080/test
	@GetMapping("test")
	public String test() {
		jobj.clear();
		jobj.put("requestType", "GET Request");
		return jobj.toString();
	}

	// URL = http://localhost:8080/test/123
	@GetMapping("/test/{id}")
	public String pathVariableTest(@PathVariable String id) {
		jobj.clear();
		jobj.put("requestType", "GET with Path Variable");
		jobj.put("pathVariable", id);
		return jobj.toString();
	}

	// URL = http://localhost:8080/queryTest?queryParam=vasu
	@GetMapping("/queryTest")
	public String queryParamTest(@RequestParam String queryParam) {
		jobj.clear();
		jobj.put("requestType", "GET with Query Param");
		jobj.put("QueryParam", queryParam);
		return jobj.toString();
	}

	//URL = http://localhost:8080/queryTest/123?queryParam=vasu
	@GetMapping("/queryTest/{id}")
	public String queryParamAndPathVarTest(@PathVariable String id, @RequestParam String queryParam) {
		jobj.clear();
		jobj.put("requestType", "GET with Query Param And Path Variable");
		jobj.put("QueryParam", queryParam);
		jobj.put("pathVariable", id);
		return jobj.toString();
	}
	
	@PostMapping("/postTest")
	public String test(@RequestBody String data) {
		jobj.clear();
		jobj.put("requestType", "Post Request");
		jobj.put("payload", data);
		return jobj.toString();
	}

}

Now run your Spring boot application and text your APIs. These are the same APIs that we are calling from our android project.

Download Code

So let’s download the code from Github.

Download Retrofit client code for Android

Download Spring Boot APIs Project

Other Posts you may like

So it’s the end of the tutorial, So if you reached here means you have successfully learned how to call rest API in android using Retrofit. There is some other post that you make like:

On delete and On Update cascading in MySQL complete example

Send SMS to any mobile number in the world using Twilio

Help Others, Please Share

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

x