Spring ResponseEntity, ResponseBody, ResonseStatus

ResponseEntity represents an HTTP response, including headers, body, and status in a spring restful API. While @ResponseBody puts the return value into the body of the response of API, ResponseEntity also allows us to add headers and status code as well.

Prerequisite :

Let’s take a Java Entity Model Class called “Dependant” to be used in this example.

@Entity
@Table(name = "Dependant")
public class Dependant implements Serializable {

    @Id
    private int deptid;

    @Column(name="firstname")
    private String firstname;

    @Column(name="lastname")
    private String lastname;

    // getter, setter methods ...
}

1. ResponseEntity

Example

Let’s create a simple REST API which returns Dependant class object which we made above, wrapped inside the ResponseEntity.

@GetMapping("/dependant/id/{id}")
public ResponseEntity<Dependant> getDependantbyId(@PathVariable int id){
        
    Dependant dept = new Dependant();
    dept = dependantRepository.findBydeptid(id);
   
    HttpHeaders headers = new HttpHeaders();
    headers.add("Custom-Header", "foo - Department");

    return ResponseEntity.status(HttpStatus.OK).headers(headers).body(dept);
}

We give ResponseEntity a custom status code, headers, and a body.

OUTPUT

Status : 200 OK

Custom-Header →foo - Department
Content-Type →application/json;charset=UTF-8
Transfer-Encoding →chunked
Date →Tue, 25 Feb 2020 07:48:58 GMT

and body as shown below

{
    "deptid": 1,
    "firstname": "Donald",
    "lastname": "T",
}

2. @ResponseBody

Example

In this example we try to achieve the same as as ResponseEntity but @ResponseBody only returns the body, in this case only the Dependant class object.

@GetMapping("/dependant/id/{id}")
@ResponseBody
public Dependant getDependant2byId(@PathVariable int id){

    Dependant dept = new Dependant();
    dept = dependantRepository.findBydeptid(id);
    
    return dept;
}

With @ResponseBody, only the body is returned. The headers and status code are provided by Spring.

3. @ResponseStatus

@ResponseStatus marks a method or exception class with the status code and reason message that should be returned. The status code is applied to the HTTP response when the handler method is invoked, or whenever the specified exception is thrown.
It overrides status information set by other means, like ResponseEntity or redirect.

Example : Custom Exceptions

@GetMapping("/dependant/id/{id}")
@ResponseBody
public Dependant getDependantbyId(@PathVariable int id){

	if(id>10){
		throw new MyCustomException("the id is not in range");
	}
	Dependant dept = new Dependant();
	dept = dependantRepository.findBydeptid(id);

	return dept;
}
	
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "No such dependant with this id")
public class MyCustomException extends RuntimeException {

    public MyCustomException(String message){
        super(message);
    }
}

Summary

In this article, we looked into ResponseEntity, ResponseBody and ResponseStatus functionalities/annotations. We learnt it by simple examples.
Please let us know if you have any questions or concerns related to the topic in the comments section below.
Hope you liked it !


React Router

React Router is a standard library for routing in a React app. It enables the navigation among views of various components in a React Application and allows changing the browser URL.

Super Easy installation

Create a react app first and when you are done with that then do a simple npm install of react-router-dom as shown below.

npx create-react-app demo-app
cd demo-app

npm install react-router-dom

Now after installing react-router-dom, add its components to your React app.

import { 
    BrowserRouter as Router, 
    Link, 
    Route, 
    Switch 
} from 'react-router-dom'; 

Four main components :

  • BrowserRouter : It is the parent component and the other Child components which we need to create routes for are wrapped inside this component.
    BrowserRouter is a router implementation that uses the HTML5 history API(pushState, replaceState and the popstate event) to keep your UI in sync with the URL.
  • Link : It works like html anchor tags, this is used to create routes and implement the navigation in the application.
  • Route : Route is used to conditionally open a component/page based on the link selected.
  • Switch : Switch component is used to render only the first route that matches the location rather than rendering all matching routes.

Example to showcase the React Router using the above components :

import React from "react";
import {
  BrowserRouter as Router,
  Link,
  Switch,
  Route,
} from "react-router-dom";

// This site has 3 pages, all of which are rendered
// dynamically in the browser (not server rendered).

// Although the page does not ever refresh, notice how
// React Router keeps the URL up to date as you navigate
// through the site. This preserves the browser history,
// making sure things like the back button and bookmarks
// work properly.

export default function RouteExample() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About Us</Link>
          </li>
          <li>
            <Link to="/dashboard">Dashboard</Link>
          </li>
        </ul>

        <hr />

        <Switch>
          <Route exact path="/">
            <Home />
          </Route>
          <Route path="/about">
            <About />
          </Route>
          <Route path="/dashboard">
            <Dashboard />
          </Route>
        </Switch>
      </div>
    </Router>
  );
}

// You can think of these components as "pages"
 in your app.

function Home() {
  return (
    <div>
      <h2>Home</h2>
    </div>
  );
}

function About() {
  return (
    <div>
      <h2>About Us</h2>
    </div>
  );
}

function Dashboard() {
  return (
    <div>
      <h2>Dashboard</h2>
    </div>
  );
}

Summary

In this article, we learnt about react routing using react-router-dom which can be installed as a node dependency and then used in any react app to navigate between the pages.
Please let us know in the comments below about your thoughts and queries.
Hope you liked it !


JSX – Reactjs

JSX is a syntax extension to JavaScript. Stands for javascript XML. It allows us to write HTML along with javascript in react.

Look at the below variable declaration.

const test = <h1>Hello, world!</h1>;

This tag syntax is neither a string nor HTML. It is called JSX, and it is a syntax extension to JavaScript.
JSX is recommended to use in React as it comes with the full power of JavaScript.

One Good Reason to answer Why JSX ?

Instead of artificially separating technologies by putting markup and logic in separate files, React separates concerns with loosely coupled units called “components” that contain both of them in single file.

Now adding expression in the JSX.

Example

const name = 'John Doe';
const element = <h1>Hello, {name}</h1>;

ReactDOM.render(
  element,
  document.getElementById('root')
);

so you can add any kind of valid javascript expression inside the curly braces.

Summary

In this article, we learnt about JSX in react.
Please let us know in the comments below about your thoughts and queries.
Hope you liked it !


Lifecycle methods in Reactjs

We will look into lifecycle methods in react. In applications with many components, it’s very important to free up resources taken by the components when they are destroyed.

We can add some code when a components mounts and unmounts.

shouldComponentUpdate – allows the developer to prevent unnecessary re-rendering of a component by returning false if a render is not required.

mounting – means when a component is rendered for the first time.

unmounting – means when the DOM produced by the component is removed.

render – is the most important lifecycle method and the only required one in any component. It is usually called every time the component’s state is updated, which should be reflected in the user interface.

These methods are called “lifecycle methods”.

Example

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {name: "John"};
  }

  componentDidMount() {
	// do something
  }

  componentWillUnmount() {
	// do something
  }

  render() {
    return (
      <div>
        <h1>Hello, {this.state.name}!</h1>
      </div>
    );
  }
}

Summary

In this article, we learnt about lifecycle methods of react.
Please let us know in the comments below about your thoughts and queries.
Hope you liked it !


API call in Reactjs using fetch method

In this article we will see how to do a REST API call in a reactjs component using

  • fetch method
  • inside useEffect hook

Below is a sample code which demonstrates this.

Example:

import React, { useEffect } from 'react';

function App() {

// Note: the empty deps array [] means
// this useEffect will run once
// similar to componentDidMount()

useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then(res => res.json())
.then(
(result) => {
console.log('result : ',result);
},
).catch((e) => console.log(e))
}, [])

return null
}

export default App;

Summary

In this article, we learnt how to call a rest api end point using fetch method in react useEffect hook.
Please let us know in the comments below about your thoughts and queries.
Hope you liked it !


State and Props in React

Let’s see how React handles data. It’s done in 2 ways using state and the props.

Props

One of the method is using properties( a.k.a Props )
Lets see how to handle data using props:

export const Parent : () => {

  const name = "John";
  const address = "address";

  return(
	<Child
		name = {name}
		address = {address}
	></Child>
        )
};

interface IChild {
  name : string;
  address : string;
}

import React, FC from "react"; // FC : FunctionComponent

export const Child : FC<IChild> = (props) => {

  const fathersName = props.name;
  const address = props.address;

};

State

You can think of a state as a shopping cart, where you add/remove/modify items before the purchase.
In the same way here React has state where you can add/remove/modify data for a particular component or within the state of entire application.

import React, {useState} from "react";

export const SampleFuncComponent : () => {

const [name,setName] = useState("");
const [flag,setFlag] = useState()<boolean>;

const userName = "John Doe";
const userActive = true;

setName(userName);
setFlag(userActive);

// now you can use the state variables around this code

const completeName = name; // "John Doe"

if(flag){
const active = flag; // true
}

};

Summary

In this article, we learnt how react handles data between the components, two ways to transfer data using state and props.
Please let us know in the comments below about your thoughts and queries.
Hope you liked it !


How to create a README file

How to create README file for your git code

What is a README?

A well formatted text file that is used to document important information about your GIT project for any user who starts to use it for the first time.

Sample README.md file

Generally there is just 1 README.md file per project. But if needed it can also be created for each module in a project.

How to create a README?

Most commonly used format for README files are markdown language. That’s why you see a file extension ‘.md’. markdown language can be thought similar to HTML.

Steps to create a README.md:

When a new git project is created a blank markdown file README.md file is created automatically.

  1. Open the README.md file using a text editor. You can use text editor like Notepad, notepad++, Sublime etc.
  2. Edit the file using markdown language. Learn markdown language syntax from here.
  3. Commit the file to git to see the preview . Alternatively, you can use any editor like  Atom, Emacs, Sublime TextVim to create and preview the file.

You can also directly open the file in Git UI and edit it using the markdown language. Git UI also has an option to Preview the file .

That’s It !

Sample README File:

Find below the template of a README.md file written using markdown language syntax.

Copy the below to any text editor to begin creating your README.md file.

# Header H1
Header H1 is used to display the Project heading. 

## Sub Topic Headings H2
Sub Topic Headings H2 is used for sub sections like Configurations, Authors etc.

````
pip install boto
````

The above formatting is used to create a box which can display code or command in a well formatted manner.


## Usage

Below is another example of displaying
````python
import csv

with open("sample.csv","r") as csvinput: # read input csv file
    reader = csv.reader(csvinput) # create a reader
    for row in reader:
        print(row[0])
````

 

OUTPUT README :

The output of sample README.md after committing the file in git looks like below.

Markdown Syntax

As git README.md file is created using markdown language, learning some basic markdown syntax can be very useful to style your README.md file.

Learn syntax for the following most commonly used elements in the git README.md

  • Text formatting
  • List creation
  • Code block creation
  • Table creation

Text Formatting:

Bold: To create text as bold enclose it in double stars or double underscore.

Italic :  To create text as bold enclose it in single star or single underscore.

Syntax:

**bold** OR __bold__

*Italic* OR _Italic_

Output:

bold OR bold
Italic OR Italic

Lists:

Ordered lists: Markdown syntax for creating numbered list is just by putting numbers in front of each row.

Syntax:

1. One
2. Two
3. Three

Output:

  1. One
  2. Two
  3. Three

Unordered lists: Bulleted lists can be created using star or dashes.

Syntax 1:

* Star is used to create a bullet list item
* Item 2

Output:

  • Star is used to create a bullet list item
  • Item 2

Syntax 2:

- You can also use Dashes instead of stars
- Parent Item
 - Item 1
 - Item 2

Output:

  • You can also use Dashes instead of stars
  • Parent Item
  • Item 1
  • Item 2

Code Blocks:

Backticks are used to create code blocks .For inline code wrap it in single backticks.

Syntax:

`variable a = 20`

Output:

variable a = 20

For multiline code block : Use spaces for indentation & use 4 backticks for code blocks without indentation:

Syntax:

if(IndentationRequired)
print(“use 4 spaces”)

Output:

    if(IndentationRequired) 
        print(“use 4 spaces”)

Syntax:

````
if(IndentationNotRequired)
print(“use 4 spaces”)
````

Output:

if(IndentationNotRequired) 
print(“use 4 spaces”)

Create Tables:

Tables are created using dashes and pipes. Dashes are used to underline the headers and pipes are used to separate the columns.Check the example below.

Syntax:

Column 1|Column 2
--------------|--------------
Row element| Row element

Output:

Column 1Column 2
Row elementRow element

Summary

In this article, we learnt what is readme and we also learnt how to create a readme file for your project.
I hope you liked it !


Microservices Design Patterns

Today there is a growing demand for microservices in the market. It has become a go-to solution to build APIs and application. Designing microservices may also have architectural challenges. To avoid any design based difficulty in future a developer must know some common microservices design patterns for building microservices.

What are MicroServices?

It is an implementation of a functionality in the form of service, which is self contained and implements a single business capability.

Principles Behind Microservices

You need to know on what principles microservices are designed and architectured.

  1. Resilient Services – one service goes down, entire application doesn’t go down.
  2. Scalability
  3. Independent and Autonomous Services
  4. Availability – services are available 24×7
  5. Decentralization – control is not at one place, its segregated
  6. Real Time Load Balancing –
  7. Seamless API Integration and continous monitoring
  8. Isolation from Failures – error in one service will not affect others

Design Patterns

1. Aggregator

Collects Related Items of Data and displays them Based on DRY principle.

An aggregator design pattern is design in which it invokes various other microservices which further has different data stores from which they fetch required data. Then show the aggregated data.

2. API Gateway

API Gateway acts as an entry point to forward the clients requests to appropriate microservices. Then, with the help of the load balancer, the load of the request is handled and the request is sent to the respective services.

3. Chained Or Chain of Responsibility

Produces a single output which is a combination of multiple chained outputs. Request passed to all the services and output is collected from all services.

4. Asynchronous Messaging

All the services can communicate with each other, but they do not have to communicate with each other sequentially.

5. Database Or Shared Data

DB can be per service Or shared database

6. Event Sourcing

Creates Events Regarding the changes in the application state.

7. Branch

Branch microservices design pattern is that in which you process the requests and response from two or more independent microservices.

8. CQRS ( Command Query Responsibility Segregator)

In this design pattern the application will be divided into 2 parts, Command and the Query.
The Command part will handle CRUD operations and the Query part will handle the materialized views.

9. Circuit Breaker

This design pattern is basically to handle fail scenarios of the microservices, for instance if a service it down, the system will still request and wait for response, but using circuit breaker pattern, after receiving consecutive failures in response, the system will trip and any further request made to this service will fail, this will save performance of the system.

10. Decomposition

It is always a good idea to break your application into small units. With the help of this pattern, either you can decompose an application based on business capability or on based on the sub-domains.
Vine Pattern or the Strangler Pattern further helps in decomposing big monolithic applications into small units.

Summary

In this article, we learnt about Microservices Design patterns for microservices development and its importance, we also read about principles behind microservices and had a look at various types of design patterns.

I hope you liked it !


Merge Sort

Merge Sort is a Divide and Conquer algorithm. How this works is, it first divides input array in two halves, calls itself for the two halves and then merges the two sorted halves.

The Idea is :

The mergeSort method should recursively sort the subarray array[l..r] i.e. after calling mergeSort(array,l,r) the elements from index l to index r of array should be sorted in ascending order.

Time complexity :

Time complexity of Merge Sort is O(nLogn) in all 3 cases (worst, average and best) as merge sort always divides the array into two halves and take linear time to merge two halves.

MergeSort Code :

class MergeSort {

// Main method
public static void main(String args[]) {
int arr[] = { 11, 10, 12, 4, 6, 5 };

System.out.println("Given Unsorted Array :");
printArray(arr);

MergeSort ob = new MergeSort();
ob.mergeSort(arr, 0, arr.length - 1);

System.out.println("\nSorted array :");
printArray(arr);
}

// The method that sorts arr[l..r] using merge()
void mergeSort(int arr[], int l, int r) {
if (l < r) {
// Find the middle point
int m = (l + r) / 2;

// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);

// Merge the sorted halves
merge(arr, l, m, r);
}
}

/*
* Merges two subarrays of arr[]. First subarray is arr[left..mid] Second
* subarray is arr[mid+1..right]
*/
void merge(int arr[], int l, int m, int r) {
// Find sizes of two subarrays to be merged
int size1 = m - l + 1;
int size2 = r - m;

/* Create temp arrays */
int Left[] = new int[size1];
int Right[] = new int[size2];

/* Copy data to temp arrays */
for (int i = 0; i < size1; ++i)
Left[i] = arr[l + i];
for (int j = 0; j < size2; ++j)
Right[j] = arr[m + 1 + j];

/* Merge the temp arrays */

// Initial indexes of first and second subarrays
int i = 0, j = 0;

// Initial index of merged subarray array
int k = l;

while (i < size1 && j < size2) {
if (Left[i] <= Right[j]) {
arr[k] = Left[i];
i++;
} else {
arr[k] = Right[j];
j++;
}
k++;
}

/* Copy remaining elements of Left[] if any */
while (i < size1) {
arr[k] = Left[i];
i++;
k++;
}

/* Copy remaining elements of Right[] if any */
while (j < size2) {
arr[k] = Right[j];
j++;
k++;
}
}

// method to print array of size n
static void printArray(int arr[]) {
for (int i = 0; i < arr.length; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}

}

OUTPUT

Given Unsorted Array :
11 10 12 4 6 5

Sorted array :
4 5 6 10 11 12

Summary

In this tutorial, we saw the concept of merge sorting algorithm and we wrote a recursive merge sorting code in java. I suggest copy this code in your favorite IDE and test it.
I hope you liked it !