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 .



















Testing controller

------Controller------------- @RestController @RequestMapping("/items") public class ItemController {     private final ItemServic...