Thursday, December 30, 2021

How Asynchoronus javascript works behind the scene

We already know when a function is called it invoked into execution stack of javascript engine.
When the work is finished it popped from the stack . But when asynchoronus js callback is in 
your code then the invoked into WEB API section of javascript engine and the callback is wait 
into the Web API until the wait is finished. But the other function will push into stack and 
after finished will popped from the stack .After then the callback will enqueue into message
queue and will pushed into execution stack if the stack is empty. Though it is called in stack and 
asynchoronus js is run in Web API so it will not harm our normal execution .That's why as
asynchoronus is non-block. Event loop will always check if stack is empty and the function is 
in Message queue.






Difference between synchoronus js and asynchoronus js

 --In synchoronus js code is execute line by line by one thread. 

--In asynchoronus js code is execute in background.

   -- We pass in callback that run once the function has finished its works.

   --Move on immediate : Non-blocking.

Saturday, December 25, 2021

Singly Linked List operations

public class SinglyLinkedList {

       private ListNode head;

private static class ListNode {

private int data;

private ListNode next;

public ListNode(int data) {

this.data = data;

this.next = null;

}

}

// printing singly linked list

public void displayList(ListNode head) {

ListNode current = head;

while (current != null) {

System.out.println(current.data);

current = current.next;

}

}

// Reverse the linked list

public ListNode reverse(ListNode head) {

if (head == null) {

return head;

}

ListNode current = head;

ListNode previous = null;

ListNode next = null;

while (current != null) {

next = current.next;

current.next = previous;

previous = current;

current = next;

}

return previous;

}

public static void main(String[] args) {

// creating nodes

SinglyLinkedList sl = new SinglyLinkedList();

sl.head = new ListNode(10);

ListNode second = new ListNode(1);

ListNode third = new ListNode(2);

ListNode fourth = new ListNode(3);

// connecting nodes together

sl.head.next = second;

second.next = third;

third.next = fourth;

fourth.next = null;

sl.displayList(sl.head);

SinglyLinkedList.ListNode reverse = sl.reverse(sl.head);

sl.displayList(reverse);

}

}


Tuesday, December 21, 2021

String sorting using bubble sort

                String input = "geeksforgeeks";

char[] inputAr = input.toCharArray();

char temp;

for (int i = 0; i < inputAr.length ; i++) {// no of pass controller

for (int j = 0; j < inputAr.length -i- 1; j++) {

if (inputAr[j] > inputAr[j+1]) { //comparing with adjacent character.

temp = inputAr[j];

inputAr[j] = inputAr[j+1];

inputAr[j+1] = temp;

}

}

}

for (int i = 0; i < inputAr.length ; i++) {

System.out.println(inputAr[i]);

}

Monday, December 20, 2021

Inheritance in ES6

 First let see the example of how inheritance works in ES5.

var Person5 = function (name, yearOfBirth, job) {

    this.name = name;

    this.yearofBirth = yearOfBirth;

    this.job = job;

}

Person5.prototype.calculateAge = function() {

    var age = new Date().getFullYear() - this.yearOfBirth;

    console.log(age);

}

var Athlete5 = function(name, yearOfBirth, job, olympicGames, medals) {

    Person5.call(this, name, yearOfBirth, job);

    this.olympicGames = olympicGames;

    this.medals = medals;

}

Athlete5.prototype = Object.create(Person5.prototype); //will create new instance and point prototype of Person5                                                                                           to Athlete5. So that now we can access the prototype of                                                                                             Person5 using object of Athlete5.

var johnAthlete5 = new Athlete5('lokman', 1990, 'engineer', 'swimmer', 3);

johnAthlete5.calculateAge();

Here ,Athlete5 is inheriting Person5. 


//ES6
class Person6 {
    constructor(name, yearOfBirth, job) {
        this.name = name;
        this.yearofBirth = yearOfBirth;
        this.job = job;
    }

    calculateAge() {
        var age = new Date().getFullYear() - this.yearofBirth;
        console.log(age);
    }

}

class Athlete6 extends Person6 {
    constructor(name, yearOfBirth, job, olympicGames, medal) {
        super(name, yearOfBirth, job);
        this.olympicGames = olympicGames;
        this.medals = medal;
    }
    
    wonmedals(){
        this.wonmedals++;
        console.log(this.medals);
    }

}

const johnatlete6 = new Athlete6("john",1989,"engineer","tokyo",1);
johnatlete6.calculateAge();
johnatlete6.wonmedals();


Sunday, December 19, 2021

Class in ES6

 //ES5

var person5 = function (name, yearOfBirth, job) {

    this.name = name;

    this.yearofBirth = yearOfBirth;

    this.job = job;

}

person5.prototype.calculateAge = function () {

    var age = new Date().getFullYear - this.yearOfBirth;

    console.log(age);

}

var john5 = new person5('lokman', 1990, 'engineer');

//ES6

class Person6 {

    constructor(name, yearOfBirth, job) {

        this.name = name;

        this.yearofBirth = yearOfBirth;

        this.job = job;

    }

  calculateAge() {

        var age = new Date().getFullYear - this.yearOfBirth;

        console.log(age);

    }

    static greetings(){

        console.log('hey there ');

    }

}

const john6 = new  Person6('lokman',1990,'engineer');

we can define static function in ES6 which will attach to a class. So we can not call it using object of the class.

Person6.greetings();

points to remember:

class definition are not hoisted unlike function constructor.



Global exception handling

 If we write exception handler into the controller then we can not re-use it . Then need to write again which will violate co-usability rule.

So, to avoid code duplication we can define global exception handler using @ControllerAdvice.

@ControllerAdvice:

--Its similar to pre-processor/filter.

--Pre process request to controller.

-- Preprocess responses to handle exception.

--Perfect for global exception handling.


let's refactor our previous exception handling code-


@ControllerAdvice

public class StudentRestHandlerException{

@ExceptionHandler

public ResponseEntity<StudentErrorResponse> handleException(StudentNotFound  exc){

StudentErrorResponse errorResponse = new StudentErrorResponse();

errorResponse.setStatus(HttpStatus.Not_found.value());

errorResponse.setMessage(exc.getMessage());

errorResponse.setTimeStamp(System.currentTimeMillis());

return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);// will return a json .jackson                                                                                                                           will convert the pojo to json .

}

What if the user request using character in request parameter without giving integer value . then server again will show an ugly message .so we should handle it . so lets create another exception handler ..

@ExceptionHandler

public ResponseEntity<StudentErrorResponse> handleException(Exception ex){

StudentErrorResponse errorResponse = new StudentErrorResponse();

errorResponse.setStatus(HttpStatus.BAD_REQUEST.value());

errorResponse.setMessage(exc.getMessage());

errorResponse.setTimeStamp(System.currentTimeMillis());

return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);

}

}





Thursday, December 16, 2021

Spring rest exception handling


When we call a rest service with bad end points then it will throw an exception what will show lots of ugly information from the server . So we can modify  the exception information by developing our own custom exception.

lets see the practical example-

1. Creating our custom exception response pojo class that we want to sent back to the client.

public class StudentErrorResponse{

private int status;

private String message;

private long timestamp;

public StudentErrorResponse(int status,String message,long timeStamp){

        this.status = status;

        this.message = message;

        this.timeStamp = timeStamp;

    }

//Appropriate getter and setter for the properties

}

Now let's create our custom exception class.

public class StudentNotFound extends RuntimeException{

public StudentNotFound(String message,Throwable cause){

super(message,cause);

}

public StudentNotFound(String message){

super(message);

}

public StudentNotFound(String cause){

super(cause);

}

}

Now lets  throws exception from our rest controller if student is not found,

@RestController

@RequestMapping("/api")

public class StudentRestController{

 private List<Student> students ;

@PostConstruct  //defining @PostConstruct will load data only once after class has been loaded .

public void loadData(){

        students = new ArrayList<Student>();

        students.add(new Student("lokman","hossain"));

        students.add(new Student("sadia","muna"));

}

@GetMapping("/students")

public List<Student> getStudents(){

  return students;

    }

@GetMapping("/students/{studentId}")

public Student getStudent(@PathVariable int studentId){

if((studentId>students.size() )|| (studentId<0))

    throw new StudentNotFound("Student not found with the given student id:"+studentId);

return students.get(studentId);

}

//Adding exception handler

@ExceptionHandler

public ResponseEntity<StudentErrorResponse> handleException(StudentNotFound  exc){

StudentErrorResponse errorResponse = new StudentErrorResponse();

errorResponse.setStatus(HttpStatus.Not_found.value());

errorResponse.setMessage(exc.getMessage());

errorResponse.setTimeStamp(System.currentTimeMillis());

return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);// will return a json .jackson                                                                                                                           will convert the pojo to json .

}

What if the user request using character in request parameter without giving integer value . then server again will show an ugly message .so we should handle it . so lets create another exception handler ..

@ExceptionHandler

public ResponseEntity<StudentErrorResponse> handleException(Exception ex){

StudentErrorResponse errorResponse = new StudentErrorResponse();

errorResponse.setStatus(HttpStatus.BAD_REQUEST.value());

errorResponse.setMessage(exc.getMessage());

errorResponse.setTimeStamp(System.currentTimeMillis());

return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);

}

}







Tuesday, December 14, 2021

How spring rest and jackson convert java pojo to json behind the scene


Lets see a practical example-

POJO:

public class Student{

private String firstName;

private String lastName;

public Student(String firstName,String lastName){

    this.firstName = firstName;

    this.lastName = lastName;

}

public void setFirstName(String firstName){

      this.firstName = firstName;

}

public String getFirstName(){

     return firstName;

}

public void setLastName(String lastName){

      this.lastName= lastName;

}

public String getLastName(){

     return lastName;

  }

}

RestController:

@RestController

@RequestMapping("/api")

public class StudentRestController{

@GetMapping("/students")

public List<Student> getStudents(){

        List<Student> students = new ArrayList<Student>();

        students.add(new Student("lokman","hossain"));

        students.add(new Student("sadia","muna"));

    return students;

    }

}

If we hit to that given end point (/api/students/) it will send a json array with two json object . So how it convert into json .

jackson convert the java pojo into json and sends back to the client .



















MIME content type

 MIME stands for Multipurpose Internet mail-extension.

MIME describes the response format sends by server to the client.

Syntax:

type/sub-type

Ex:text/html,application/json etc.

HTTP response code

Server sends http response code with http response header.
Every response code has individual meaning .
let see some of the status code-

100-199 ----Informational
200-299-----Successful
300-399-----Redirection
400-499-----Client error (ex-404 file not found)
500-599-----Internal server error(ex-500 internal server error)

Http reqeust and response structure

 A http request has 3 parts-

1.Request line-The http command(Ex-get,post,put,delete)

2.Header variable-Request meta data(Ex-connection ,keep alive etc)

3.Message body-Content of the message(payload)


A http response has also 3 different areas-

1.Response line-Server protocol and status code

2.Header variable-response metadata(ex:content type-json,xml,size and length of the data etc)

3.Message body(list of customer as json/xml) 

Sunday, December 12, 2021

How jackson convert json to pojo?

 By default jackson use appropriate getter and setter method to bind data .

lets see and example ,

Json to pojo--



let's see a practical example-

we have a file containing a json object representing student . Then read json object from the file and convert it to student object.

.import java.io.File;

.import com.fasterxml.jackson.databind.ObjectMapper;

public class MainApp{

  public static void main(String[] args){

           ObjectMapper objectMapper  = new ObjectMapper();

           Student student = objectMapper.readValue(new File("sample.json"),Student.class);

        }

}

In this example objectMapper will read value from sample.json file and convert that json object into student object using corresponding setter methods.

N.B:When we converting json to pojo it will call setter but in vice versa it will call getter .But what if the corresponding getter and setter are not found then it will throw exception . So how we can avoid some property if needed .Then we can use special annotation -

@JsonIgnoreProperties(ignoreUnknown=true)

public class Student{

    private int id;//has setter and getter

    private String firstName;//has setter and getter

    private String lastName;

}

Data binding ?

 Data binding is the process of converting json to java pojo or java pojo to json .

spring uses jackson project for data binding .

-jackson  is data binding API.

package: com.fasterxml.jackson.databind

 Maven dependency:

<dependency>

     <groupId>com.fasterxml.jackson.core</groupId>

    <artifactId>jackson-databind</artifactId>

    <version>2.9.0</version>

</dependency>



What is json?

 JSON- Javascript object notation.

-- Lightweight data format for storing and exchanging data(as plain text).

--Language independent.

JSON object example-

{

    "id":1,

    "name":"Rafik",

   "age":20

}

Object members are name value pair. Name and value are delimited by colon(:)

N.B: Name are always in double quote("").


Nested JSON object

{

    "id":1,

    "name":"Sadia siddika muna",

    age:24,

    department:{

                      "name":"english",

                        "department code":101

                    }

}

JSON arrays:

{

     "id":101,

     "name":"muna",

     "address":"Barishal",

     "languages":["java","python","javascript"]

}

Let's see a simple JSON array example having 3 objects.

{

        "employees":[

          {"name":"muna","email":"muna@gmail.com","age":24},

          {"name":"sadia","email":"sadia@gmail.com","age":24},

          {"name":"siddika","email":"siddika@gmail.com","age":24},

 ]

}

Friday, December 3, 2021

Minimum maven dependencies for spring security

 We should add those below dependencies to pom.xml-

<dependency>

            <groupId>org.springframework.security</groupId>

            <artifactId>spring-security-web</artifactId>

             <version>${springsecurity.version}</version>

</dependency>

<dependency>

            <groupId>org.springframework.security</groupId>

            <artifactId>spring-security-config</artifactId>

             <version>${springsecurity.version}</version>

</dependency>


Fluent interface pattern

 public class UserConfigurationManager {     private String userName;     private String password;     private UserConfigurationManager() { ...